1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 if (!B) return QualType(); 83 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 84 // FIXME: It's unclear where we're supposed to take the type from, and 85 // this actually matters for arrays of unknown bound. Eg: 86 // 87 // extern int arr[]; void f() { extern int arr[3]; }; 88 // constexpr int *p = &arr[1]; // valid? 89 // 90 // For now, we take the array bound from the most recent declaration. 91 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 92 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 93 QualType T = Redecl->getType(); 94 if (!T->isIncompleteArrayType()) 95 return T; 96 } 97 return D->getType(); 98 } 99 100 if (B.is<TypeInfoLValue>()) 101 return B.getTypeInfoType(); 102 103 if (B.is<DynamicAllocLValue>()) 104 return B.getDynamicAllocType(); 105 106 const Expr *Base = B.get<const Expr*>(); 107 108 // For a materialized temporary, the type of the temporary we materialized 109 // may not be the type of the expression. 110 if (const MaterializeTemporaryExpr *MTE = 111 dyn_cast<MaterializeTemporaryExpr>(Base)) { 112 SmallVector<const Expr *, 2> CommaLHSs; 113 SmallVector<SubobjectAdjustment, 2> Adjustments; 114 const Expr *Temp = MTE->getSubExpr(); 115 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 116 Adjustments); 117 // Keep any cv-qualifiers from the reference if we generated a temporary 118 // for it directly. Otherwise use the type after adjustment. 119 if (!Adjustments.empty()) 120 return Inner->getType(); 121 } 122 123 return Base->getType(); 124 } 125 126 /// Get an LValue path entry, which is known to not be an array index, as a 127 /// field declaration. 128 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 129 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 130 } 131 /// Get an LValue path entry, which is known to not be an array index, as a 132 /// base class declaration. 133 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 134 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 135 } 136 /// Determine whether this LValue path entry for a base class names a virtual 137 /// base class. 138 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 139 return E.getAsBaseOrMember().getInt(); 140 } 141 142 /// Given an expression, determine the type used to store the result of 143 /// evaluating that expression. 144 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 145 if (E->isRValue()) 146 return E->getType(); 147 return Ctx.getLValueReferenceType(E->getType()); 148 } 149 150 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 151 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 152 const FunctionDecl *Callee = CE->getDirectCallee(); 153 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 154 } 155 156 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 157 /// This will look through a single cast. 158 /// 159 /// Returns null if we couldn't unwrap a function with alloc_size. 160 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 161 if (!E->getType()->isPointerType()) 162 return nullptr; 163 164 E = E->IgnoreParens(); 165 // If we're doing a variable assignment from e.g. malloc(N), there will 166 // probably be a cast of some kind. In exotic cases, we might also see a 167 // top-level ExprWithCleanups. Ignore them either way. 168 if (const auto *FE = dyn_cast<FullExpr>(E)) 169 E = FE->getSubExpr()->IgnoreParens(); 170 171 if (const auto *Cast = dyn_cast<CastExpr>(E)) 172 E = Cast->getSubExpr()->IgnoreParens(); 173 174 if (const auto *CE = dyn_cast<CallExpr>(E)) 175 return getAllocSizeAttr(CE) ? CE : nullptr; 176 return nullptr; 177 } 178 179 /// Determines whether or not the given Base contains a call to a function 180 /// with the alloc_size attribute. 181 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 182 const auto *E = Base.dyn_cast<const Expr *>(); 183 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 184 } 185 186 /// The bound to claim that an array of unknown bound has. 187 /// The value in MostDerivedArraySize is undefined in this case. So, set it 188 /// to an arbitrary value that's likely to loudly break things if it's used. 189 static const uint64_t AssumedSizeForUnsizedArray = 190 std::numeric_limits<uint64_t>::max() / 2; 191 192 /// Determines if an LValue with the given LValueBase will have an unsized 193 /// array in its designator. 194 /// Find the path length and type of the most-derived subobject in the given 195 /// path, and find the size of the containing array, if any. 196 static unsigned 197 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 198 ArrayRef<APValue::LValuePathEntry> Path, 199 uint64_t &ArraySize, QualType &Type, bool &IsArray, 200 bool &FirstEntryIsUnsizedArray) { 201 // This only accepts LValueBases from APValues, and APValues don't support 202 // arrays that lack size info. 203 assert(!isBaseAnAllocSizeCall(Base) && 204 "Unsized arrays shouldn't appear here"); 205 unsigned MostDerivedLength = 0; 206 Type = getType(Base); 207 208 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 209 if (Type->isArrayType()) { 210 const ArrayType *AT = Ctx.getAsArrayType(Type); 211 Type = AT->getElementType(); 212 MostDerivedLength = I + 1; 213 IsArray = true; 214 215 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 216 ArraySize = CAT->getSize().getZExtValue(); 217 } else { 218 assert(I == 0 && "unexpected unsized array designator"); 219 FirstEntryIsUnsizedArray = true; 220 ArraySize = AssumedSizeForUnsizedArray; 221 } 222 } else if (Type->isAnyComplexType()) { 223 const ComplexType *CT = Type->castAs<ComplexType>(); 224 Type = CT->getElementType(); 225 ArraySize = 2; 226 MostDerivedLength = I + 1; 227 IsArray = true; 228 } else if (const FieldDecl *FD = getAsField(Path[I])) { 229 Type = FD->getType(); 230 ArraySize = 0; 231 MostDerivedLength = I + 1; 232 IsArray = false; 233 } else { 234 // Path[I] describes a base class. 235 ArraySize = 0; 236 IsArray = false; 237 } 238 } 239 return MostDerivedLength; 240 } 241 242 /// A path from a glvalue to a subobject of that glvalue. 243 struct SubobjectDesignator { 244 /// True if the subobject was named in a manner not supported by C++11. Such 245 /// lvalues can still be folded, but they are not core constant expressions 246 /// and we cannot perform lvalue-to-rvalue conversions on them. 247 unsigned Invalid : 1; 248 249 /// Is this a pointer one past the end of an object? 250 unsigned IsOnePastTheEnd : 1; 251 252 /// Indicator of whether the first entry is an unsized array. 253 unsigned FirstEntryIsAnUnsizedArray : 1; 254 255 /// Indicator of whether the most-derived object is an array element. 256 unsigned MostDerivedIsArrayElement : 1; 257 258 /// The length of the path to the most-derived object of which this is a 259 /// subobject. 260 unsigned MostDerivedPathLength : 28; 261 262 /// The size of the array of which the most-derived object is an element. 263 /// This will always be 0 if the most-derived object is not an array 264 /// element. 0 is not an indicator of whether or not the most-derived object 265 /// is an array, however, because 0-length arrays are allowed. 266 /// 267 /// If the current array is an unsized array, the value of this is 268 /// undefined. 269 uint64_t MostDerivedArraySize; 270 271 /// The type of the most derived object referred to by this address. 272 QualType MostDerivedType; 273 274 typedef APValue::LValuePathEntry PathEntry; 275 276 /// The entries on the path from the glvalue to the designated subobject. 277 SmallVector<PathEntry, 8> Entries; 278 279 SubobjectDesignator() : Invalid(true) {} 280 281 explicit SubobjectDesignator(QualType T) 282 : Invalid(false), IsOnePastTheEnd(false), 283 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 284 MostDerivedPathLength(0), MostDerivedArraySize(0), 285 MostDerivedType(T) {} 286 287 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 288 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 289 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 290 MostDerivedPathLength(0), MostDerivedArraySize(0) { 291 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 292 if (!Invalid) { 293 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 294 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 295 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 296 if (V.getLValueBase()) { 297 bool IsArray = false; 298 bool FirstIsUnsizedArray = false; 299 MostDerivedPathLength = findMostDerivedSubobject( 300 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 301 MostDerivedType, IsArray, FirstIsUnsizedArray); 302 MostDerivedIsArrayElement = IsArray; 303 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 304 } 305 } 306 } 307 308 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 309 unsigned NewLength) { 310 if (Invalid) 311 return; 312 313 assert(Base && "cannot truncate path for null pointer"); 314 assert(NewLength <= Entries.size() && "not a truncation"); 315 316 if (NewLength == Entries.size()) 317 return; 318 Entries.resize(NewLength); 319 320 bool IsArray = false; 321 bool FirstIsUnsizedArray = false; 322 MostDerivedPathLength = findMostDerivedSubobject( 323 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 324 FirstIsUnsizedArray); 325 MostDerivedIsArrayElement = IsArray; 326 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 327 } 328 329 void setInvalid() { 330 Invalid = true; 331 Entries.clear(); 332 } 333 334 /// Determine whether the most derived subobject is an array without a 335 /// known bound. 336 bool isMostDerivedAnUnsizedArray() const { 337 assert(!Invalid && "Calling this makes no sense on invalid designators"); 338 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 339 } 340 341 /// Determine what the most derived array's size is. Results in an assertion 342 /// failure if the most derived array lacks a size. 343 uint64_t getMostDerivedArraySize() const { 344 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 345 return MostDerivedArraySize; 346 } 347 348 /// Determine whether this is a one-past-the-end pointer. 349 bool isOnePastTheEnd() const { 350 assert(!Invalid); 351 if (IsOnePastTheEnd) 352 return true; 353 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 354 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 355 MostDerivedArraySize) 356 return true; 357 return false; 358 } 359 360 /// Get the range of valid index adjustments in the form 361 /// {maximum value that can be subtracted from this pointer, 362 /// maximum value that can be added to this pointer} 363 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 364 if (Invalid || isMostDerivedAnUnsizedArray()) 365 return {0, 0}; 366 367 // [expr.add]p4: For the purposes of these operators, a pointer to a 368 // nonarray object behaves the same as a pointer to the first element of 369 // an array of length one with the type of the object as its element type. 370 bool IsArray = MostDerivedPathLength == Entries.size() && 371 MostDerivedIsArrayElement; 372 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 373 : (uint64_t)IsOnePastTheEnd; 374 uint64_t ArraySize = 375 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 376 return {ArrayIndex, ArraySize - ArrayIndex}; 377 } 378 379 /// Check that this refers to a valid subobject. 380 bool isValidSubobject() const { 381 if (Invalid) 382 return false; 383 return !isOnePastTheEnd(); 384 } 385 /// Check that this refers to a valid subobject, and if not, produce a 386 /// relevant diagnostic and set the designator as invalid. 387 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 388 389 /// Get the type of the designated object. 390 QualType getType(ASTContext &Ctx) const { 391 assert(!Invalid && "invalid designator has no subobject type"); 392 return MostDerivedPathLength == Entries.size() 393 ? MostDerivedType 394 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 395 } 396 397 /// Update this designator to refer to the first element within this array. 398 void addArrayUnchecked(const ConstantArrayType *CAT) { 399 Entries.push_back(PathEntry::ArrayIndex(0)); 400 401 // This is a most-derived object. 402 MostDerivedType = CAT->getElementType(); 403 MostDerivedIsArrayElement = true; 404 MostDerivedArraySize = CAT->getSize().getZExtValue(); 405 MostDerivedPathLength = Entries.size(); 406 } 407 /// Update this designator to refer to the first element within the array of 408 /// elements of type T. This is an array of unknown size. 409 void addUnsizedArrayUnchecked(QualType ElemTy) { 410 Entries.push_back(PathEntry::ArrayIndex(0)); 411 412 MostDerivedType = ElemTy; 413 MostDerivedIsArrayElement = true; 414 // The value in MostDerivedArraySize is undefined in this case. So, set it 415 // to an arbitrary value that's likely to loudly break things if it's 416 // used. 417 MostDerivedArraySize = AssumedSizeForUnsizedArray; 418 MostDerivedPathLength = Entries.size(); 419 } 420 /// Update this designator to refer to the given base or member of this 421 /// object. 422 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 423 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 424 425 // If this isn't a base class, it's a new most-derived object. 426 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 427 MostDerivedType = FD->getType(); 428 MostDerivedIsArrayElement = false; 429 MostDerivedArraySize = 0; 430 MostDerivedPathLength = Entries.size(); 431 } 432 } 433 /// Update this designator to refer to the given complex component. 434 void addComplexUnchecked(QualType EltTy, bool Imag) { 435 Entries.push_back(PathEntry::ArrayIndex(Imag)); 436 437 // This is technically a most-derived object, though in practice this 438 // is unlikely to matter. 439 MostDerivedType = EltTy; 440 MostDerivedIsArrayElement = true; 441 MostDerivedArraySize = 2; 442 MostDerivedPathLength = Entries.size(); 443 } 444 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 445 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 446 const APSInt &N); 447 /// Add N to the address of this subobject. 448 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 449 if (Invalid || !N) return; 450 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 451 if (isMostDerivedAnUnsizedArray()) { 452 diagnoseUnsizedArrayPointerArithmetic(Info, E); 453 // Can't verify -- trust that the user is doing the right thing (or if 454 // not, trust that the caller will catch the bad behavior). 455 // FIXME: Should we reject if this overflows, at least? 456 Entries.back() = PathEntry::ArrayIndex( 457 Entries.back().getAsArrayIndex() + TruncatedN); 458 return; 459 } 460 461 // [expr.add]p4: For the purposes of these operators, a pointer to a 462 // nonarray object behaves the same as a pointer to the first element of 463 // an array of length one with the type of the object as its element type. 464 bool IsArray = MostDerivedPathLength == Entries.size() && 465 MostDerivedIsArrayElement; 466 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 467 : (uint64_t)IsOnePastTheEnd; 468 uint64_t ArraySize = 469 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 470 471 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 472 // Calculate the actual index in a wide enough type, so we can include 473 // it in the note. 474 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 475 (llvm::APInt&)N += ArrayIndex; 476 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 477 diagnosePointerArithmetic(Info, E, N); 478 setInvalid(); 479 return; 480 } 481 482 ArrayIndex += TruncatedN; 483 assert(ArrayIndex <= ArraySize && 484 "bounds check succeeded for out-of-bounds index"); 485 486 if (IsArray) 487 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 488 else 489 IsOnePastTheEnd = (ArrayIndex != 0); 490 } 491 }; 492 493 /// A stack frame in the constexpr call stack. 494 class CallStackFrame : public interp::Frame { 495 public: 496 EvalInfo &Info; 497 498 /// Parent - The caller of this stack frame. 499 CallStackFrame *Caller; 500 501 /// Callee - The function which was called. 502 const FunctionDecl *Callee; 503 504 /// This - The binding for the this pointer in this call, if any. 505 const LValue *This; 506 507 /// Arguments - Parameter bindings for this function call, indexed by 508 /// parameters' function scope indices. 509 APValue *Arguments; 510 511 /// Source location information about the default argument or default 512 /// initializer expression we're evaluating, if any. 513 CurrentSourceLocExprScope CurSourceLocExprScope; 514 515 // Note that we intentionally use std::map here so that references to 516 // values are stable. 517 typedef std::pair<const void *, unsigned> MapKeyTy; 518 typedef std::map<MapKeyTy, APValue> MapTy; 519 /// Temporaries - Temporary lvalues materialized within this stack frame. 520 MapTy Temporaries; 521 522 /// CallLoc - The location of the call expression for this call. 523 SourceLocation CallLoc; 524 525 /// Index - The call index of this call. 526 unsigned Index; 527 528 /// The stack of integers for tracking version numbers for temporaries. 529 SmallVector<unsigned, 2> TempVersionStack = {1}; 530 unsigned CurTempVersion = TempVersionStack.back(); 531 532 unsigned getTempVersion() const { return TempVersionStack.back(); } 533 534 void pushTempVersion() { 535 TempVersionStack.push_back(++CurTempVersion); 536 } 537 538 void popTempVersion() { 539 TempVersionStack.pop_back(); 540 } 541 542 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 543 // on the overall stack usage of deeply-recursing constexpr evaluations. 544 // (We should cache this map rather than recomputing it repeatedly.) 545 // But let's try this and see how it goes; we can look into caching the map 546 // as a later change. 547 548 /// LambdaCaptureFields - Mapping from captured variables/this to 549 /// corresponding data members in the closure class. 550 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 551 FieldDecl *LambdaThisCaptureField; 552 553 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 554 const FunctionDecl *Callee, const LValue *This, 555 APValue *Arguments); 556 ~CallStackFrame(); 557 558 // Return the temporary for Key whose version number is Version. 559 APValue *getTemporary(const void *Key, unsigned Version) { 560 MapKeyTy KV(Key, Version); 561 auto LB = Temporaries.lower_bound(KV); 562 if (LB != Temporaries.end() && LB->first == KV) 563 return &LB->second; 564 // Pair (Key,Version) wasn't found in the map. Check that no elements 565 // in the map have 'Key' as their key. 566 assert((LB == Temporaries.end() || LB->first.first != Key) && 567 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 568 "Element with key 'Key' found in map"); 569 return nullptr; 570 } 571 572 // Return the current temporary for Key in the map. 573 APValue *getCurrentTemporary(const void *Key) { 574 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 575 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 576 return &std::prev(UB)->second; 577 return nullptr; 578 } 579 580 // Return the version number of the current temporary for Key. 581 unsigned getCurrentTemporaryVersion(const void *Key) const { 582 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 583 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 584 return std::prev(UB)->first.second; 585 return 0; 586 } 587 588 /// Allocate storage for an object of type T in this stack frame. 589 /// Populates LV with a handle to the created object. Key identifies 590 /// the temporary within the stack frame, and must not be reused without 591 /// bumping the temporary version number. 592 template<typename KeyT> 593 APValue &createTemporary(const KeyT *Key, QualType T, 594 bool IsLifetimeExtended, LValue &LV); 595 596 void describe(llvm::raw_ostream &OS) override; 597 598 Frame *getCaller() const override { return Caller; } 599 SourceLocation getCallLocation() const override { return CallLoc; } 600 const FunctionDecl *getCallee() const override { return Callee; } 601 602 bool isStdFunction() const { 603 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 604 if (DC->isStdNamespace()) 605 return true; 606 return false; 607 } 608 }; 609 610 /// Temporarily override 'this'. 611 class ThisOverrideRAII { 612 public: 613 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 614 : Frame(Frame), OldThis(Frame.This) { 615 if (Enable) 616 Frame.This = NewThis; 617 } 618 ~ThisOverrideRAII() { 619 Frame.This = OldThis; 620 } 621 private: 622 CallStackFrame &Frame; 623 const LValue *OldThis; 624 }; 625 } 626 627 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 628 const LValue &This, QualType ThisType); 629 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 630 APValue::LValueBase LVBase, APValue &Value, 631 QualType T); 632 633 namespace { 634 /// A cleanup, and a flag indicating whether it is lifetime-extended. 635 class Cleanup { 636 llvm::PointerIntPair<APValue*, 1, bool> Value; 637 APValue::LValueBase Base; 638 QualType T; 639 640 public: 641 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 642 bool IsLifetimeExtended) 643 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} 644 645 bool isLifetimeExtended() const { return Value.getInt(); } 646 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 647 if (RunDestructors) { 648 SourceLocation Loc; 649 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 650 Loc = VD->getLocation(); 651 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 652 Loc = E->getExprLoc(); 653 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 654 } 655 *Value.getPointer() = APValue(); 656 return true; 657 } 658 659 bool hasSideEffect() { 660 return T.isDestructedType(); 661 } 662 }; 663 664 /// A reference to an object whose construction we are currently evaluating. 665 struct ObjectUnderConstruction { 666 APValue::LValueBase Base; 667 ArrayRef<APValue::LValuePathEntry> Path; 668 friend bool operator==(const ObjectUnderConstruction &LHS, 669 const ObjectUnderConstruction &RHS) { 670 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 671 } 672 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 673 return llvm::hash_combine(Obj.Base, Obj.Path); 674 } 675 }; 676 enum class ConstructionPhase { 677 None, 678 Bases, 679 AfterBases, 680 AfterFields, 681 Destroying, 682 DestroyingBases 683 }; 684 } 685 686 namespace llvm { 687 template<> struct DenseMapInfo<ObjectUnderConstruction> { 688 using Base = DenseMapInfo<APValue::LValueBase>; 689 static ObjectUnderConstruction getEmptyKey() { 690 return {Base::getEmptyKey(), {}}; } 691 static ObjectUnderConstruction getTombstoneKey() { 692 return {Base::getTombstoneKey(), {}}; 693 } 694 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 695 return hash_value(Object); 696 } 697 static bool isEqual(const ObjectUnderConstruction &LHS, 698 const ObjectUnderConstruction &RHS) { 699 return LHS == RHS; 700 } 701 }; 702 } 703 704 namespace { 705 /// A dynamically-allocated heap object. 706 struct DynAlloc { 707 /// The value of this heap-allocated object. 708 APValue Value; 709 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 710 /// or a CallExpr (the latter is for direct calls to operator new inside 711 /// std::allocator<T>::allocate). 712 const Expr *AllocExpr = nullptr; 713 714 enum Kind { 715 New, 716 ArrayNew, 717 StdAllocator 718 }; 719 720 /// Get the kind of the allocation. This must match between allocation 721 /// and deallocation. 722 Kind getKind() const { 723 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 724 return NE->isArray() ? ArrayNew : New; 725 assert(isa<CallExpr>(AllocExpr)); 726 return StdAllocator; 727 } 728 }; 729 730 struct DynAllocOrder { 731 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 732 return L.getIndex() < R.getIndex(); 733 } 734 }; 735 736 /// EvalInfo - This is a private struct used by the evaluator to capture 737 /// information about a subexpression as it is folded. It retains information 738 /// about the AST context, but also maintains information about the folded 739 /// expression. 740 /// 741 /// If an expression could be evaluated, it is still possible it is not a C 742 /// "integer constant expression" or constant expression. If not, this struct 743 /// captures information about how and why not. 744 /// 745 /// One bit of information passed *into* the request for constant folding 746 /// indicates whether the subexpression is "evaluated" or not according to C 747 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 748 /// evaluate the expression regardless of what the RHS is, but C only allows 749 /// certain things in certain situations. 750 class EvalInfo : public interp::State { 751 public: 752 ASTContext &Ctx; 753 754 /// EvalStatus - Contains information about the evaluation. 755 Expr::EvalStatus &EvalStatus; 756 757 /// CurrentCall - The top of the constexpr call stack. 758 CallStackFrame *CurrentCall; 759 760 /// CallStackDepth - The number of calls in the call stack right now. 761 unsigned CallStackDepth; 762 763 /// NextCallIndex - The next call index to assign. 764 unsigned NextCallIndex; 765 766 /// StepsLeft - The remaining number of evaluation steps we're permitted 767 /// to perform. This is essentially a limit for the number of statements 768 /// we will evaluate. 769 unsigned StepsLeft; 770 771 /// Enable the experimental new constant interpreter. If an expression is 772 /// not supported by the interpreter, an error is triggered. 773 bool EnableNewConstInterp; 774 775 /// BottomFrame - The frame in which evaluation started. This must be 776 /// initialized after CurrentCall and CallStackDepth. 777 CallStackFrame BottomFrame; 778 779 /// A stack of values whose lifetimes end at the end of some surrounding 780 /// evaluation frame. 781 llvm::SmallVector<Cleanup, 16> CleanupStack; 782 783 /// EvaluatingDecl - This is the declaration whose initializer is being 784 /// evaluated, if any. 785 APValue::LValueBase EvaluatingDecl; 786 787 enum class EvaluatingDeclKind { 788 None, 789 /// We're evaluating the construction of EvaluatingDecl. 790 Ctor, 791 /// We're evaluating the destruction of EvaluatingDecl. 792 Dtor, 793 }; 794 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 795 796 /// EvaluatingDeclValue - This is the value being constructed for the 797 /// declaration whose initializer is being evaluated, if any. 798 APValue *EvaluatingDeclValue; 799 800 /// Set of objects that are currently being constructed. 801 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 802 ObjectsUnderConstruction; 803 804 /// Current heap allocations, along with the location where each was 805 /// allocated. We use std::map here because we need stable addresses 806 /// for the stored APValues. 807 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 808 809 /// The number of heap allocations performed so far in this evaluation. 810 unsigned NumHeapAllocs = 0; 811 812 struct EvaluatingConstructorRAII { 813 EvalInfo &EI; 814 ObjectUnderConstruction Object; 815 bool DidInsert; 816 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 817 bool HasBases) 818 : EI(EI), Object(Object) { 819 DidInsert = 820 EI.ObjectsUnderConstruction 821 .insert({Object, HasBases ? ConstructionPhase::Bases 822 : ConstructionPhase::AfterBases}) 823 .second; 824 } 825 void finishedConstructingBases() { 826 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 827 } 828 void finishedConstructingFields() { 829 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 830 } 831 ~EvaluatingConstructorRAII() { 832 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 833 } 834 }; 835 836 struct EvaluatingDestructorRAII { 837 EvalInfo &EI; 838 ObjectUnderConstruction Object; 839 bool DidInsert; 840 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 841 : EI(EI), Object(Object) { 842 DidInsert = EI.ObjectsUnderConstruction 843 .insert({Object, ConstructionPhase::Destroying}) 844 .second; 845 } 846 void startedDestroyingBases() { 847 EI.ObjectsUnderConstruction[Object] = 848 ConstructionPhase::DestroyingBases; 849 } 850 ~EvaluatingDestructorRAII() { 851 if (DidInsert) 852 EI.ObjectsUnderConstruction.erase(Object); 853 } 854 }; 855 856 ConstructionPhase 857 isEvaluatingCtorDtor(APValue::LValueBase Base, 858 ArrayRef<APValue::LValuePathEntry> Path) { 859 return ObjectsUnderConstruction.lookup({Base, Path}); 860 } 861 862 /// If we're currently speculatively evaluating, the outermost call stack 863 /// depth at which we can mutate state, otherwise 0. 864 unsigned SpeculativeEvaluationDepth = 0; 865 866 /// The current array initialization index, if we're performing array 867 /// initialization. 868 uint64_t ArrayInitIndex = -1; 869 870 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 871 /// notes attached to it will also be stored, otherwise they will not be. 872 bool HasActiveDiagnostic; 873 874 /// Have we emitted a diagnostic explaining why we couldn't constant 875 /// fold (not just why it's not strictly a constant expression)? 876 bool HasFoldFailureDiagnostic; 877 878 /// Whether or not we're in a context where the front end requires a 879 /// constant value. 880 bool InConstantContext; 881 882 /// Whether we're checking that an expression is a potential constant 883 /// expression. If so, do not fail on constructs that could become constant 884 /// later on (such as a use of an undefined global). 885 bool CheckingPotentialConstantExpression = false; 886 887 /// Whether we're checking for an expression that has undefined behavior. 888 /// If so, we will produce warnings if we encounter an operation that is 889 /// always undefined. 890 bool CheckingForUndefinedBehavior = false; 891 892 enum EvaluationMode { 893 /// Evaluate as a constant expression. Stop if we find that the expression 894 /// is not a constant expression. 895 EM_ConstantExpression, 896 897 /// Evaluate as a constant expression. Stop if we find that the expression 898 /// is not a constant expression. Some expressions can be retried in the 899 /// optimizer if we don't constant fold them here, but in an unevaluated 900 /// context we try to fold them immediately since the optimizer never 901 /// gets a chance to look at it. 902 EM_ConstantExpressionUnevaluated, 903 904 /// Fold the expression to a constant. Stop if we hit a side-effect that 905 /// we can't model. 906 EM_ConstantFold, 907 908 /// Evaluate in any way we know how. Don't worry about side-effects that 909 /// can't be modeled. 910 EM_IgnoreSideEffects, 911 } EvalMode; 912 913 /// Are we checking whether the expression is a potential constant 914 /// expression? 915 bool checkingPotentialConstantExpression() const override { 916 return CheckingPotentialConstantExpression; 917 } 918 919 /// Are we checking an expression for overflow? 920 // FIXME: We should check for any kind of undefined or suspicious behavior 921 // in such constructs, not just overflow. 922 bool checkingForUndefinedBehavior() const override { 923 return CheckingForUndefinedBehavior; 924 } 925 926 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 927 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 928 CallStackDepth(0), NextCallIndex(1), 929 StepsLeft(C.getLangOpts().ConstexprStepLimit), 930 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 931 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 932 EvaluatingDecl((const ValueDecl *)nullptr), 933 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 934 HasFoldFailureDiagnostic(false), InConstantContext(false), 935 EvalMode(Mode) {} 936 937 ~EvalInfo() { 938 discardCleanups(); 939 } 940 941 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 942 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 943 EvaluatingDecl = Base; 944 IsEvaluatingDecl = EDK; 945 EvaluatingDeclValue = &Value; 946 } 947 948 bool CheckCallLimit(SourceLocation Loc) { 949 // Don't perform any constexpr calls (other than the call we're checking) 950 // when checking a potential constant expression. 951 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 952 return false; 953 if (NextCallIndex == 0) { 954 // NextCallIndex has wrapped around. 955 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 956 return false; 957 } 958 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 959 return true; 960 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 961 << getLangOpts().ConstexprCallDepth; 962 return false; 963 } 964 965 std::pair<CallStackFrame *, unsigned> 966 getCallFrameAndDepth(unsigned CallIndex) { 967 assert(CallIndex && "no call index in getCallFrameAndDepth"); 968 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 969 // be null in this loop. 970 unsigned Depth = CallStackDepth; 971 CallStackFrame *Frame = CurrentCall; 972 while (Frame->Index > CallIndex) { 973 Frame = Frame->Caller; 974 --Depth; 975 } 976 if (Frame->Index == CallIndex) 977 return {Frame, Depth}; 978 return {nullptr, 0}; 979 } 980 981 bool nextStep(const Stmt *S) { 982 if (!StepsLeft) { 983 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 984 return false; 985 } 986 --StepsLeft; 987 return true; 988 } 989 990 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 991 992 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 993 Optional<DynAlloc*> Result; 994 auto It = HeapAllocs.find(DA); 995 if (It != HeapAllocs.end()) 996 Result = &It->second; 997 return Result; 998 } 999 1000 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1001 struct StdAllocatorCaller { 1002 unsigned FrameIndex; 1003 QualType ElemType; 1004 explicit operator bool() const { return FrameIndex != 0; }; 1005 }; 1006 1007 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1008 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1009 Call = Call->Caller) { 1010 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1011 if (!MD) 1012 continue; 1013 const IdentifierInfo *FnII = MD->getIdentifier(); 1014 if (!FnII || !FnII->isStr(FnName)) 1015 continue; 1016 1017 const auto *CTSD = 1018 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1019 if (!CTSD) 1020 continue; 1021 1022 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1023 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1024 if (CTSD->isInStdNamespace() && ClassII && 1025 ClassII->isStr("allocator") && TAL.size() >= 1 && 1026 TAL[0].getKind() == TemplateArgument::Type) 1027 return {Call->Index, TAL[0].getAsType()}; 1028 } 1029 1030 return {}; 1031 } 1032 1033 void performLifetimeExtension() { 1034 // Disable the cleanups for lifetime-extended temporaries. 1035 CleanupStack.erase( 1036 std::remove_if(CleanupStack.begin(), CleanupStack.end(), 1037 [](Cleanup &C) { return C.isLifetimeExtended(); }), 1038 CleanupStack.end()); 1039 } 1040 1041 /// Throw away any remaining cleanups at the end of evaluation. If any 1042 /// cleanups would have had a side-effect, note that as an unmodeled 1043 /// side-effect and return false. Otherwise, return true. 1044 bool discardCleanups() { 1045 for (Cleanup &C : CleanupStack) { 1046 if (C.hasSideEffect() && !noteSideEffect()) { 1047 CleanupStack.clear(); 1048 return false; 1049 } 1050 } 1051 CleanupStack.clear(); 1052 return true; 1053 } 1054 1055 private: 1056 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1057 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1058 1059 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1060 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1061 1062 void setFoldFailureDiagnostic(bool Flag) override { 1063 HasFoldFailureDiagnostic = Flag; 1064 } 1065 1066 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1067 1068 ASTContext &getCtx() const override { return Ctx; } 1069 1070 // If we have a prior diagnostic, it will be noting that the expression 1071 // isn't a constant expression. This diagnostic is more important, 1072 // unless we require this evaluation to produce a constant expression. 1073 // 1074 // FIXME: We might want to show both diagnostics to the user in 1075 // EM_ConstantFold mode. 1076 bool hasPriorDiagnostic() override { 1077 if (!EvalStatus.Diag->empty()) { 1078 switch (EvalMode) { 1079 case EM_ConstantFold: 1080 case EM_IgnoreSideEffects: 1081 if (!HasFoldFailureDiagnostic) 1082 break; 1083 // We've already failed to fold something. Keep that diagnostic. 1084 LLVM_FALLTHROUGH; 1085 case EM_ConstantExpression: 1086 case EM_ConstantExpressionUnevaluated: 1087 setActiveDiagnostic(false); 1088 return true; 1089 } 1090 } 1091 return false; 1092 } 1093 1094 unsigned getCallStackDepth() override { return CallStackDepth; } 1095 1096 public: 1097 /// Should we continue evaluation after encountering a side-effect that we 1098 /// couldn't model? 1099 bool keepEvaluatingAfterSideEffect() { 1100 switch (EvalMode) { 1101 case EM_IgnoreSideEffects: 1102 return true; 1103 1104 case EM_ConstantExpression: 1105 case EM_ConstantExpressionUnevaluated: 1106 case EM_ConstantFold: 1107 // By default, assume any side effect might be valid in some other 1108 // evaluation of this expression from a different context. 1109 return checkingPotentialConstantExpression() || 1110 checkingForUndefinedBehavior(); 1111 } 1112 llvm_unreachable("Missed EvalMode case"); 1113 } 1114 1115 /// Note that we have had a side-effect, and determine whether we should 1116 /// keep evaluating. 1117 bool noteSideEffect() { 1118 EvalStatus.HasSideEffects = true; 1119 return keepEvaluatingAfterSideEffect(); 1120 } 1121 1122 /// Should we continue evaluation after encountering undefined behavior? 1123 bool keepEvaluatingAfterUndefinedBehavior() { 1124 switch (EvalMode) { 1125 case EM_IgnoreSideEffects: 1126 case EM_ConstantFold: 1127 return true; 1128 1129 case EM_ConstantExpression: 1130 case EM_ConstantExpressionUnevaluated: 1131 return checkingForUndefinedBehavior(); 1132 } 1133 llvm_unreachable("Missed EvalMode case"); 1134 } 1135 1136 /// Note that we hit something that was technically undefined behavior, but 1137 /// that we can evaluate past it (such as signed overflow or floating-point 1138 /// division by zero.) 1139 bool noteUndefinedBehavior() override { 1140 EvalStatus.HasUndefinedBehavior = true; 1141 return keepEvaluatingAfterUndefinedBehavior(); 1142 } 1143 1144 /// Should we continue evaluation as much as possible after encountering a 1145 /// construct which can't be reduced to a value? 1146 bool keepEvaluatingAfterFailure() const override { 1147 if (!StepsLeft) 1148 return false; 1149 1150 switch (EvalMode) { 1151 case EM_ConstantExpression: 1152 case EM_ConstantExpressionUnevaluated: 1153 case EM_ConstantFold: 1154 case EM_IgnoreSideEffects: 1155 return checkingPotentialConstantExpression() || 1156 checkingForUndefinedBehavior(); 1157 } 1158 llvm_unreachable("Missed EvalMode case"); 1159 } 1160 1161 /// Notes that we failed to evaluate an expression that other expressions 1162 /// directly depend on, and determine if we should keep evaluating. This 1163 /// should only be called if we actually intend to keep evaluating. 1164 /// 1165 /// Call noteSideEffect() instead if we may be able to ignore the value that 1166 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1167 /// 1168 /// (Foo(), 1) // use noteSideEffect 1169 /// (Foo() || true) // use noteSideEffect 1170 /// Foo() + 1 // use noteFailure 1171 LLVM_NODISCARD bool noteFailure() { 1172 // Failure when evaluating some expression often means there is some 1173 // subexpression whose evaluation was skipped. Therefore, (because we 1174 // don't track whether we skipped an expression when unwinding after an 1175 // evaluation failure) every evaluation failure that bubbles up from a 1176 // subexpression implies that a side-effect has potentially happened. We 1177 // skip setting the HasSideEffects flag to true until we decide to 1178 // continue evaluating after that point, which happens here. 1179 bool KeepGoing = keepEvaluatingAfterFailure(); 1180 EvalStatus.HasSideEffects |= KeepGoing; 1181 return KeepGoing; 1182 } 1183 1184 class ArrayInitLoopIndex { 1185 EvalInfo &Info; 1186 uint64_t OuterIndex; 1187 1188 public: 1189 ArrayInitLoopIndex(EvalInfo &Info) 1190 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1191 Info.ArrayInitIndex = 0; 1192 } 1193 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1194 1195 operator uint64_t&() { return Info.ArrayInitIndex; } 1196 }; 1197 }; 1198 1199 /// Object used to treat all foldable expressions as constant expressions. 1200 struct FoldConstant { 1201 EvalInfo &Info; 1202 bool Enabled; 1203 bool HadNoPriorDiags; 1204 EvalInfo::EvaluationMode OldMode; 1205 1206 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1207 : Info(Info), 1208 Enabled(Enabled), 1209 HadNoPriorDiags(Info.EvalStatus.Diag && 1210 Info.EvalStatus.Diag->empty() && 1211 !Info.EvalStatus.HasSideEffects), 1212 OldMode(Info.EvalMode) { 1213 if (Enabled) 1214 Info.EvalMode = EvalInfo::EM_ConstantFold; 1215 } 1216 void keepDiagnostics() { Enabled = false; } 1217 ~FoldConstant() { 1218 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1219 !Info.EvalStatus.HasSideEffects) 1220 Info.EvalStatus.Diag->clear(); 1221 Info.EvalMode = OldMode; 1222 } 1223 }; 1224 1225 /// RAII object used to set the current evaluation mode to ignore 1226 /// side-effects. 1227 struct IgnoreSideEffectsRAII { 1228 EvalInfo &Info; 1229 EvalInfo::EvaluationMode OldMode; 1230 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1231 : Info(Info), OldMode(Info.EvalMode) { 1232 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1233 } 1234 1235 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1236 }; 1237 1238 /// RAII object used to optionally suppress diagnostics and side-effects from 1239 /// a speculative evaluation. 1240 class SpeculativeEvaluationRAII { 1241 EvalInfo *Info = nullptr; 1242 Expr::EvalStatus OldStatus; 1243 unsigned OldSpeculativeEvaluationDepth; 1244 1245 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1246 Info = Other.Info; 1247 OldStatus = Other.OldStatus; 1248 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1249 Other.Info = nullptr; 1250 } 1251 1252 void maybeRestoreState() { 1253 if (!Info) 1254 return; 1255 1256 Info->EvalStatus = OldStatus; 1257 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1258 } 1259 1260 public: 1261 SpeculativeEvaluationRAII() = default; 1262 1263 SpeculativeEvaluationRAII( 1264 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1265 : Info(&Info), OldStatus(Info.EvalStatus), 1266 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1267 Info.EvalStatus.Diag = NewDiag; 1268 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1269 } 1270 1271 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1272 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1273 moveFromAndCancel(std::move(Other)); 1274 } 1275 1276 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1277 maybeRestoreState(); 1278 moveFromAndCancel(std::move(Other)); 1279 return *this; 1280 } 1281 1282 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1283 }; 1284 1285 /// RAII object wrapping a full-expression or block scope, and handling 1286 /// the ending of the lifetime of temporaries created within it. 1287 template<bool IsFullExpression> 1288 class ScopeRAII { 1289 EvalInfo &Info; 1290 unsigned OldStackSize; 1291 public: 1292 ScopeRAII(EvalInfo &Info) 1293 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1294 // Push a new temporary version. This is needed to distinguish between 1295 // temporaries created in different iterations of a loop. 1296 Info.CurrentCall->pushTempVersion(); 1297 } 1298 bool destroy(bool RunDestructors = true) { 1299 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1300 OldStackSize = -1U; 1301 return OK; 1302 } 1303 ~ScopeRAII() { 1304 if (OldStackSize != -1U) 1305 destroy(false); 1306 // Body moved to a static method to encourage the compiler to inline away 1307 // instances of this class. 1308 Info.CurrentCall->popTempVersion(); 1309 } 1310 private: 1311 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1312 unsigned OldStackSize) { 1313 assert(OldStackSize <= Info.CleanupStack.size() && 1314 "running cleanups out of order?"); 1315 1316 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1317 // for a full-expression scope. 1318 bool Success = true; 1319 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1320 if (!(IsFullExpression && 1321 Info.CleanupStack[I - 1].isLifetimeExtended())) { 1322 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1323 Success = false; 1324 break; 1325 } 1326 } 1327 } 1328 1329 // Compact lifetime-extended cleanups. 1330 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1331 if (IsFullExpression) 1332 NewEnd = 1333 std::remove_if(NewEnd, Info.CleanupStack.end(), 1334 [](Cleanup &C) { return !C.isLifetimeExtended(); }); 1335 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1336 return Success; 1337 } 1338 }; 1339 typedef ScopeRAII<false> BlockScopeRAII; 1340 typedef ScopeRAII<true> FullExpressionRAII; 1341 } 1342 1343 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1344 CheckSubobjectKind CSK) { 1345 if (Invalid) 1346 return false; 1347 if (isOnePastTheEnd()) { 1348 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1349 << CSK; 1350 setInvalid(); 1351 return false; 1352 } 1353 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1354 // must actually be at least one array element; even a VLA cannot have a 1355 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1356 return true; 1357 } 1358 1359 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1360 const Expr *E) { 1361 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1362 // Do not set the designator as invalid: we can represent this situation, 1363 // and correct handling of __builtin_object_size requires us to do so. 1364 } 1365 1366 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1367 const Expr *E, 1368 const APSInt &N) { 1369 // If we're complaining, we must be able to statically determine the size of 1370 // the most derived array. 1371 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1372 Info.CCEDiag(E, diag::note_constexpr_array_index) 1373 << N << /*array*/ 0 1374 << static_cast<unsigned>(getMostDerivedArraySize()); 1375 else 1376 Info.CCEDiag(E, diag::note_constexpr_array_index) 1377 << N << /*non-array*/ 1; 1378 setInvalid(); 1379 } 1380 1381 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1382 const FunctionDecl *Callee, const LValue *This, 1383 APValue *Arguments) 1384 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1385 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1386 Info.CurrentCall = this; 1387 ++Info.CallStackDepth; 1388 } 1389 1390 CallStackFrame::~CallStackFrame() { 1391 assert(Info.CurrentCall == this && "calls retired out of order"); 1392 --Info.CallStackDepth; 1393 Info.CurrentCall = Caller; 1394 } 1395 1396 static bool isRead(AccessKinds AK) { 1397 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1398 } 1399 1400 static bool isModification(AccessKinds AK) { 1401 switch (AK) { 1402 case AK_Read: 1403 case AK_ReadObjectRepresentation: 1404 case AK_MemberCall: 1405 case AK_DynamicCast: 1406 case AK_TypeId: 1407 return false; 1408 case AK_Assign: 1409 case AK_Increment: 1410 case AK_Decrement: 1411 case AK_Construct: 1412 case AK_Destroy: 1413 return true; 1414 } 1415 llvm_unreachable("unknown access kind"); 1416 } 1417 1418 static bool isAnyAccess(AccessKinds AK) { 1419 return isRead(AK) || isModification(AK); 1420 } 1421 1422 /// Is this an access per the C++ definition? 1423 static bool isFormalAccess(AccessKinds AK) { 1424 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1425 } 1426 1427 /// Is this kind of axcess valid on an indeterminate object value? 1428 static bool isValidIndeterminateAccess(AccessKinds AK) { 1429 switch (AK) { 1430 case AK_Read: 1431 case AK_Increment: 1432 case AK_Decrement: 1433 // These need the object's value. 1434 return false; 1435 1436 case AK_ReadObjectRepresentation: 1437 case AK_Assign: 1438 case AK_Construct: 1439 case AK_Destroy: 1440 // Construction and destruction don't need the value. 1441 return true; 1442 1443 case AK_MemberCall: 1444 case AK_DynamicCast: 1445 case AK_TypeId: 1446 // These aren't really meaningful on scalars. 1447 return true; 1448 } 1449 llvm_unreachable("unknown access kind"); 1450 } 1451 1452 namespace { 1453 struct ComplexValue { 1454 private: 1455 bool IsInt; 1456 1457 public: 1458 APSInt IntReal, IntImag; 1459 APFloat FloatReal, FloatImag; 1460 1461 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1462 1463 void makeComplexFloat() { IsInt = false; } 1464 bool isComplexFloat() const { return !IsInt; } 1465 APFloat &getComplexFloatReal() { return FloatReal; } 1466 APFloat &getComplexFloatImag() { return FloatImag; } 1467 1468 void makeComplexInt() { IsInt = true; } 1469 bool isComplexInt() const { return IsInt; } 1470 APSInt &getComplexIntReal() { return IntReal; } 1471 APSInt &getComplexIntImag() { return IntImag; } 1472 1473 void moveInto(APValue &v) const { 1474 if (isComplexFloat()) 1475 v = APValue(FloatReal, FloatImag); 1476 else 1477 v = APValue(IntReal, IntImag); 1478 } 1479 void setFrom(const APValue &v) { 1480 assert(v.isComplexFloat() || v.isComplexInt()); 1481 if (v.isComplexFloat()) { 1482 makeComplexFloat(); 1483 FloatReal = v.getComplexFloatReal(); 1484 FloatImag = v.getComplexFloatImag(); 1485 } else { 1486 makeComplexInt(); 1487 IntReal = v.getComplexIntReal(); 1488 IntImag = v.getComplexIntImag(); 1489 } 1490 } 1491 }; 1492 1493 struct LValue { 1494 APValue::LValueBase Base; 1495 CharUnits Offset; 1496 SubobjectDesignator Designator; 1497 bool IsNullPtr : 1; 1498 bool InvalidBase : 1; 1499 1500 const APValue::LValueBase getLValueBase() const { return Base; } 1501 CharUnits &getLValueOffset() { return Offset; } 1502 const CharUnits &getLValueOffset() const { return Offset; } 1503 SubobjectDesignator &getLValueDesignator() { return Designator; } 1504 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1505 bool isNullPointer() const { return IsNullPtr;} 1506 1507 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1508 unsigned getLValueVersion() const { return Base.getVersion(); } 1509 1510 void moveInto(APValue &V) const { 1511 if (Designator.Invalid) 1512 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1513 else { 1514 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1515 V = APValue(Base, Offset, Designator.Entries, 1516 Designator.IsOnePastTheEnd, IsNullPtr); 1517 } 1518 } 1519 void setFrom(ASTContext &Ctx, const APValue &V) { 1520 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1521 Base = V.getLValueBase(); 1522 Offset = V.getLValueOffset(); 1523 InvalidBase = false; 1524 Designator = SubobjectDesignator(Ctx, V); 1525 IsNullPtr = V.isNullPointer(); 1526 } 1527 1528 void set(APValue::LValueBase B, bool BInvalid = false) { 1529 #ifndef NDEBUG 1530 // We only allow a few types of invalid bases. Enforce that here. 1531 if (BInvalid) { 1532 const auto *E = B.get<const Expr *>(); 1533 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1534 "Unexpected type of invalid base"); 1535 } 1536 #endif 1537 1538 Base = B; 1539 Offset = CharUnits::fromQuantity(0); 1540 InvalidBase = BInvalid; 1541 Designator = SubobjectDesignator(getType(B)); 1542 IsNullPtr = false; 1543 } 1544 1545 void setNull(ASTContext &Ctx, QualType PointerTy) { 1546 Base = (Expr *)nullptr; 1547 Offset = 1548 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1549 InvalidBase = false; 1550 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1551 IsNullPtr = true; 1552 } 1553 1554 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1555 set(B, true); 1556 } 1557 1558 std::string toString(ASTContext &Ctx, QualType T) const { 1559 APValue Printable; 1560 moveInto(Printable); 1561 return Printable.getAsString(Ctx, T); 1562 } 1563 1564 private: 1565 // Check that this LValue is not based on a null pointer. If it is, produce 1566 // a diagnostic and mark the designator as invalid. 1567 template <typename GenDiagType> 1568 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1569 if (Designator.Invalid) 1570 return false; 1571 if (IsNullPtr) { 1572 GenDiag(); 1573 Designator.setInvalid(); 1574 return false; 1575 } 1576 return true; 1577 } 1578 1579 public: 1580 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1581 CheckSubobjectKind CSK) { 1582 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1583 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1584 }); 1585 } 1586 1587 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1588 AccessKinds AK) { 1589 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1590 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1591 }); 1592 } 1593 1594 // Check this LValue refers to an object. If not, set the designator to be 1595 // invalid and emit a diagnostic. 1596 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1597 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1598 Designator.checkSubobject(Info, E, CSK); 1599 } 1600 1601 void addDecl(EvalInfo &Info, const Expr *E, 1602 const Decl *D, bool Virtual = false) { 1603 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1604 Designator.addDeclUnchecked(D, Virtual); 1605 } 1606 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1607 if (!Designator.Entries.empty()) { 1608 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1609 Designator.setInvalid(); 1610 return; 1611 } 1612 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1613 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1614 Designator.FirstEntryIsAnUnsizedArray = true; 1615 Designator.addUnsizedArrayUnchecked(ElemTy); 1616 } 1617 } 1618 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1619 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1620 Designator.addArrayUnchecked(CAT); 1621 } 1622 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1623 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1624 Designator.addComplexUnchecked(EltTy, Imag); 1625 } 1626 void clearIsNullPointer() { 1627 IsNullPtr = false; 1628 } 1629 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1630 const APSInt &Index, CharUnits ElementSize) { 1631 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1632 // but we're not required to diagnose it and it's valid in C++.) 1633 if (!Index) 1634 return; 1635 1636 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1637 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1638 // offsets. 1639 uint64_t Offset64 = Offset.getQuantity(); 1640 uint64_t ElemSize64 = ElementSize.getQuantity(); 1641 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1642 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1643 1644 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1645 Designator.adjustIndex(Info, E, Index); 1646 clearIsNullPointer(); 1647 } 1648 void adjustOffset(CharUnits N) { 1649 Offset += N; 1650 if (N.getQuantity()) 1651 clearIsNullPointer(); 1652 } 1653 }; 1654 1655 struct MemberPtr { 1656 MemberPtr() {} 1657 explicit MemberPtr(const ValueDecl *Decl) : 1658 DeclAndIsDerivedMember(Decl, false), Path() {} 1659 1660 /// The member or (direct or indirect) field referred to by this member 1661 /// pointer, or 0 if this is a null member pointer. 1662 const ValueDecl *getDecl() const { 1663 return DeclAndIsDerivedMember.getPointer(); 1664 } 1665 /// Is this actually a member of some type derived from the relevant class? 1666 bool isDerivedMember() const { 1667 return DeclAndIsDerivedMember.getInt(); 1668 } 1669 /// Get the class which the declaration actually lives in. 1670 const CXXRecordDecl *getContainingRecord() const { 1671 return cast<CXXRecordDecl>( 1672 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1673 } 1674 1675 void moveInto(APValue &V) const { 1676 V = APValue(getDecl(), isDerivedMember(), Path); 1677 } 1678 void setFrom(const APValue &V) { 1679 assert(V.isMemberPointer()); 1680 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1681 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1682 Path.clear(); 1683 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1684 Path.insert(Path.end(), P.begin(), P.end()); 1685 } 1686 1687 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1688 /// whether the member is a member of some class derived from the class type 1689 /// of the member pointer. 1690 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1691 /// Path - The path of base/derived classes from the member declaration's 1692 /// class (exclusive) to the class type of the member pointer (inclusive). 1693 SmallVector<const CXXRecordDecl*, 4> Path; 1694 1695 /// Perform a cast towards the class of the Decl (either up or down the 1696 /// hierarchy). 1697 bool castBack(const CXXRecordDecl *Class) { 1698 assert(!Path.empty()); 1699 const CXXRecordDecl *Expected; 1700 if (Path.size() >= 2) 1701 Expected = Path[Path.size() - 2]; 1702 else 1703 Expected = getContainingRecord(); 1704 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1705 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1706 // if B does not contain the original member and is not a base or 1707 // derived class of the class containing the original member, the result 1708 // of the cast is undefined. 1709 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1710 // (D::*). We consider that to be a language defect. 1711 return false; 1712 } 1713 Path.pop_back(); 1714 return true; 1715 } 1716 /// Perform a base-to-derived member pointer cast. 1717 bool castToDerived(const CXXRecordDecl *Derived) { 1718 if (!getDecl()) 1719 return true; 1720 if (!isDerivedMember()) { 1721 Path.push_back(Derived); 1722 return true; 1723 } 1724 if (!castBack(Derived)) 1725 return false; 1726 if (Path.empty()) 1727 DeclAndIsDerivedMember.setInt(false); 1728 return true; 1729 } 1730 /// Perform a derived-to-base member pointer cast. 1731 bool castToBase(const CXXRecordDecl *Base) { 1732 if (!getDecl()) 1733 return true; 1734 if (Path.empty()) 1735 DeclAndIsDerivedMember.setInt(true); 1736 if (isDerivedMember()) { 1737 Path.push_back(Base); 1738 return true; 1739 } 1740 return castBack(Base); 1741 } 1742 }; 1743 1744 /// Compare two member pointers, which are assumed to be of the same type. 1745 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1746 if (!LHS.getDecl() || !RHS.getDecl()) 1747 return !LHS.getDecl() && !RHS.getDecl(); 1748 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1749 return false; 1750 return LHS.Path == RHS.Path; 1751 } 1752 } 1753 1754 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1755 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1756 const LValue &This, const Expr *E, 1757 bool AllowNonLiteralTypes = false); 1758 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1759 bool InvalidBaseOK = false); 1760 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1761 bool InvalidBaseOK = false); 1762 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1763 EvalInfo &Info); 1764 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1765 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1766 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1767 EvalInfo &Info); 1768 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1769 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1770 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1771 EvalInfo &Info); 1772 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1773 1774 /// Evaluate an integer or fixed point expression into an APResult. 1775 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1776 EvalInfo &Info); 1777 1778 /// Evaluate only a fixed point expression into an APResult. 1779 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1780 EvalInfo &Info); 1781 1782 //===----------------------------------------------------------------------===// 1783 // Misc utilities 1784 //===----------------------------------------------------------------------===// 1785 1786 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1787 /// preserving its value (by extending by up to one bit as needed). 1788 static void negateAsSigned(APSInt &Int) { 1789 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1790 Int = Int.extend(Int.getBitWidth() + 1); 1791 Int.setIsSigned(true); 1792 } 1793 Int = -Int; 1794 } 1795 1796 template<typename KeyT> 1797 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1798 bool IsLifetimeExtended, LValue &LV) { 1799 unsigned Version = getTempVersion(); 1800 APValue::LValueBase Base(Key, Index, Version); 1801 LV.set(Base); 1802 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1803 assert(Result.isAbsent() && "temporary created multiple times"); 1804 1805 // If we're creating a temporary immediately in the operand of a speculative 1806 // evaluation, don't register a cleanup to be run outside the speculative 1807 // evaluation context, since we won't actually be able to initialize this 1808 // object. 1809 if (Index <= Info.SpeculativeEvaluationDepth) { 1810 if (T.isDestructedType()) 1811 Info.noteSideEffect(); 1812 } else { 1813 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); 1814 } 1815 return Result; 1816 } 1817 1818 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1819 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1820 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1821 return nullptr; 1822 } 1823 1824 DynamicAllocLValue DA(NumHeapAllocs++); 1825 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1826 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1827 std::forward_as_tuple(DA), std::tuple<>()); 1828 assert(Result.second && "reused a heap alloc index?"); 1829 Result.first->second.AllocExpr = E; 1830 return &Result.first->second.Value; 1831 } 1832 1833 /// Produce a string describing the given constexpr call. 1834 void CallStackFrame::describe(raw_ostream &Out) { 1835 unsigned ArgIndex = 0; 1836 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1837 !isa<CXXConstructorDecl>(Callee) && 1838 cast<CXXMethodDecl>(Callee)->isInstance(); 1839 1840 if (!IsMemberCall) 1841 Out << *Callee << '('; 1842 1843 if (This && IsMemberCall) { 1844 APValue Val; 1845 This->moveInto(Val); 1846 Val.printPretty(Out, Info.Ctx, 1847 This->Designator.MostDerivedType); 1848 // FIXME: Add parens around Val if needed. 1849 Out << "->" << *Callee << '('; 1850 IsMemberCall = false; 1851 } 1852 1853 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1854 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1855 if (ArgIndex > (unsigned)IsMemberCall) 1856 Out << ", "; 1857 1858 const ParmVarDecl *Param = *I; 1859 const APValue &Arg = Arguments[ArgIndex]; 1860 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1861 1862 if (ArgIndex == 0 && IsMemberCall) 1863 Out << "->" << *Callee << '('; 1864 } 1865 1866 Out << ')'; 1867 } 1868 1869 /// Evaluate an expression to see if it had side-effects, and discard its 1870 /// result. 1871 /// \return \c true if the caller should keep evaluating. 1872 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1873 APValue Scratch; 1874 if (!Evaluate(Scratch, Info, E)) 1875 // We don't need the value, but we might have skipped a side effect here. 1876 return Info.noteSideEffect(); 1877 return true; 1878 } 1879 1880 /// Should this call expression be treated as a string literal? 1881 static bool IsStringLiteralCall(const CallExpr *E) { 1882 unsigned Builtin = E->getBuiltinCallee(); 1883 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1884 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1885 } 1886 1887 static bool IsGlobalLValue(APValue::LValueBase B) { 1888 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1889 // constant expression of pointer type that evaluates to... 1890 1891 // ... a null pointer value, or a prvalue core constant expression of type 1892 // std::nullptr_t. 1893 if (!B) return true; 1894 1895 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1896 // ... the address of an object with static storage duration, 1897 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1898 return VD->hasGlobalStorage(); 1899 // ... the address of a function, 1900 // ... the address of a GUID [MS extension], 1901 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1902 } 1903 1904 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1905 return true; 1906 1907 const Expr *E = B.get<const Expr*>(); 1908 switch (E->getStmtClass()) { 1909 default: 1910 return false; 1911 case Expr::CompoundLiteralExprClass: { 1912 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1913 return CLE->isFileScope() && CLE->isLValue(); 1914 } 1915 case Expr::MaterializeTemporaryExprClass: 1916 // A materialized temporary might have been lifetime-extended to static 1917 // storage duration. 1918 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1919 // A string literal has static storage duration. 1920 case Expr::StringLiteralClass: 1921 case Expr::PredefinedExprClass: 1922 case Expr::ObjCStringLiteralClass: 1923 case Expr::ObjCEncodeExprClass: 1924 return true; 1925 case Expr::ObjCBoxedExprClass: 1926 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1927 case Expr::CallExprClass: 1928 return IsStringLiteralCall(cast<CallExpr>(E)); 1929 // For GCC compatibility, &&label has static storage duration. 1930 case Expr::AddrLabelExprClass: 1931 return true; 1932 // A Block literal expression may be used as the initialization value for 1933 // Block variables at global or local static scope. 1934 case Expr::BlockExprClass: 1935 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1936 case Expr::ImplicitValueInitExprClass: 1937 // FIXME: 1938 // We can never form an lvalue with an implicit value initialization as its 1939 // base through expression evaluation, so these only appear in one case: the 1940 // implicit variable declaration we invent when checking whether a constexpr 1941 // constructor can produce a constant expression. We must assume that such 1942 // an expression might be a global lvalue. 1943 return true; 1944 } 1945 } 1946 1947 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1948 return LVal.Base.dyn_cast<const ValueDecl*>(); 1949 } 1950 1951 static bool IsLiteralLValue(const LValue &Value) { 1952 if (Value.getLValueCallIndex()) 1953 return false; 1954 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1955 return E && !isa<MaterializeTemporaryExpr>(E); 1956 } 1957 1958 static bool IsWeakLValue(const LValue &Value) { 1959 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1960 return Decl && Decl->isWeak(); 1961 } 1962 1963 static bool isZeroSized(const LValue &Value) { 1964 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1965 if (Decl && isa<VarDecl>(Decl)) { 1966 QualType Ty = Decl->getType(); 1967 if (Ty->isArrayType()) 1968 return Ty->isIncompleteType() || 1969 Decl->getASTContext().getTypeSize(Ty) == 0; 1970 } 1971 return false; 1972 } 1973 1974 static bool HasSameBase(const LValue &A, const LValue &B) { 1975 if (!A.getLValueBase()) 1976 return !B.getLValueBase(); 1977 if (!B.getLValueBase()) 1978 return false; 1979 1980 if (A.getLValueBase().getOpaqueValue() != 1981 B.getLValueBase().getOpaqueValue()) { 1982 const Decl *ADecl = GetLValueBaseDecl(A); 1983 if (!ADecl) 1984 return false; 1985 const Decl *BDecl = GetLValueBaseDecl(B); 1986 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1987 return false; 1988 } 1989 1990 return IsGlobalLValue(A.getLValueBase()) || 1991 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1992 A.getLValueVersion() == B.getLValueVersion()); 1993 } 1994 1995 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1996 assert(Base && "no location for a null lvalue"); 1997 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1998 if (VD) 1999 Info.Note(VD->getLocation(), diag::note_declared_at); 2000 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2001 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2002 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2003 // FIXME: Produce a note for dangling pointers too. 2004 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2005 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2006 diag::note_constexpr_dynamic_alloc_here); 2007 } 2008 // We have no information to show for a typeid(T) object. 2009 } 2010 2011 enum class CheckEvaluationResultKind { 2012 ConstantExpression, 2013 FullyInitialized, 2014 }; 2015 2016 /// Materialized temporaries that we've already checked to determine if they're 2017 /// initializsed by a constant expression. 2018 using CheckedTemporaries = 2019 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2020 2021 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2022 EvalInfo &Info, SourceLocation DiagLoc, 2023 QualType Type, const APValue &Value, 2024 Expr::ConstExprUsage Usage, 2025 SourceLocation SubobjectLoc, 2026 CheckedTemporaries &CheckedTemps); 2027 2028 /// Check that this reference or pointer core constant expression is a valid 2029 /// value for an address or reference constant expression. Return true if we 2030 /// can fold this expression, whether or not it's a constant expression. 2031 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2032 QualType Type, const LValue &LVal, 2033 Expr::ConstExprUsage Usage, 2034 CheckedTemporaries &CheckedTemps) { 2035 bool IsReferenceType = Type->isReferenceType(); 2036 2037 APValue::LValueBase Base = LVal.getLValueBase(); 2038 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2039 2040 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2041 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2042 if (FD->isConsteval()) { 2043 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2044 << !Type->isAnyPointerType(); 2045 Info.Note(FD->getLocation(), diag::note_declared_at); 2046 return false; 2047 } 2048 } 2049 } 2050 2051 // Check that the object is a global. Note that the fake 'this' object we 2052 // manufacture when checking potential constant expressions is conservatively 2053 // assumed to be global here. 2054 if (!IsGlobalLValue(Base)) { 2055 if (Info.getLangOpts().CPlusPlus11) { 2056 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2057 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2058 << IsReferenceType << !Designator.Entries.empty() 2059 << !!VD << VD; 2060 2061 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2062 if (VarD && VarD->isConstexpr()) { 2063 // Non-static local constexpr variables have unintuitive semantics: 2064 // constexpr int a = 1; 2065 // constexpr const int *p = &a; 2066 // ... is invalid because the address of 'a' is not constant. Suggest 2067 // adding a 'static' in this case. 2068 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2069 << VarD 2070 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2071 } else { 2072 NoteLValueLocation(Info, Base); 2073 } 2074 } else { 2075 Info.FFDiag(Loc); 2076 } 2077 // Don't allow references to temporaries to escape. 2078 return false; 2079 } 2080 assert((Info.checkingPotentialConstantExpression() || 2081 LVal.getLValueCallIndex() == 0) && 2082 "have call index for global lvalue"); 2083 2084 if (Base.is<DynamicAllocLValue>()) { 2085 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2086 << IsReferenceType << !Designator.Entries.empty(); 2087 NoteLValueLocation(Info, Base); 2088 return false; 2089 } 2090 2091 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2092 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2093 // Check if this is a thread-local variable. 2094 if (Var->getTLSKind()) 2095 // FIXME: Diagnostic! 2096 return false; 2097 2098 // A dllimport variable never acts like a constant. 2099 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2100 // FIXME: Diagnostic! 2101 return false; 2102 } 2103 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2104 // __declspec(dllimport) must be handled very carefully: 2105 // We must never initialize an expression with the thunk in C++. 2106 // Doing otherwise would allow the same id-expression to yield 2107 // different addresses for the same function in different translation 2108 // units. However, this means that we must dynamically initialize the 2109 // expression with the contents of the import address table at runtime. 2110 // 2111 // The C language has no notion of ODR; furthermore, it has no notion of 2112 // dynamic initialization. This means that we are permitted to 2113 // perform initialization with the address of the thunk. 2114 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2115 FD->hasAttr<DLLImportAttr>()) 2116 // FIXME: Diagnostic! 2117 return false; 2118 } 2119 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2120 Base.dyn_cast<const Expr *>())) { 2121 if (CheckedTemps.insert(MTE).second) { 2122 QualType TempType = getType(Base); 2123 if (TempType.isDestructedType()) { 2124 Info.FFDiag(MTE->getExprLoc(), 2125 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2126 << TempType; 2127 return false; 2128 } 2129 2130 APValue *V = MTE->getOrCreateValue(false); 2131 assert(V && "evasluation result refers to uninitialised temporary"); 2132 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2133 Info, MTE->getExprLoc(), TempType, *V, 2134 Usage, SourceLocation(), CheckedTemps)) 2135 return false; 2136 } 2137 } 2138 2139 // Allow address constant expressions to be past-the-end pointers. This is 2140 // an extension: the standard requires them to point to an object. 2141 if (!IsReferenceType) 2142 return true; 2143 2144 // A reference constant expression must refer to an object. 2145 if (!Base) { 2146 // FIXME: diagnostic 2147 Info.CCEDiag(Loc); 2148 return true; 2149 } 2150 2151 // Does this refer one past the end of some object? 2152 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2153 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2154 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2155 << !Designator.Entries.empty() << !!VD << VD; 2156 NoteLValueLocation(Info, Base); 2157 } 2158 2159 return true; 2160 } 2161 2162 /// Member pointers are constant expressions unless they point to a 2163 /// non-virtual dllimport member function. 2164 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2165 SourceLocation Loc, 2166 QualType Type, 2167 const APValue &Value, 2168 Expr::ConstExprUsage Usage) { 2169 const ValueDecl *Member = Value.getMemberPointerDecl(); 2170 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2171 if (!FD) 2172 return true; 2173 if (FD->isConsteval()) { 2174 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2175 Info.Note(FD->getLocation(), diag::note_declared_at); 2176 return false; 2177 } 2178 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2179 !FD->hasAttr<DLLImportAttr>(); 2180 } 2181 2182 /// Check that this core constant expression is of literal type, and if not, 2183 /// produce an appropriate diagnostic. 2184 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2185 const LValue *This = nullptr) { 2186 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2187 return true; 2188 2189 // C++1y: A constant initializer for an object o [...] may also invoke 2190 // constexpr constructors for o and its subobjects even if those objects 2191 // are of non-literal class types. 2192 // 2193 // C++11 missed this detail for aggregates, so classes like this: 2194 // struct foo_t { union { int i; volatile int j; } u; }; 2195 // are not (obviously) initializable like so: 2196 // __attribute__((__require_constant_initialization__)) 2197 // static const foo_t x = {{0}}; 2198 // because "i" is a subobject with non-literal initialization (due to the 2199 // volatile member of the union). See: 2200 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2201 // Therefore, we use the C++1y behavior. 2202 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2203 return true; 2204 2205 // Prvalue constant expressions must be of literal types. 2206 if (Info.getLangOpts().CPlusPlus11) 2207 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2208 << E->getType(); 2209 else 2210 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2211 return false; 2212 } 2213 2214 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2215 EvalInfo &Info, SourceLocation DiagLoc, 2216 QualType Type, const APValue &Value, 2217 Expr::ConstExprUsage Usage, 2218 SourceLocation SubobjectLoc, 2219 CheckedTemporaries &CheckedTemps) { 2220 if (!Value.hasValue()) { 2221 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2222 << true << Type; 2223 if (SubobjectLoc.isValid()) 2224 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2225 return false; 2226 } 2227 2228 // We allow _Atomic(T) to be initialized from anything that T can be 2229 // initialized from. 2230 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2231 Type = AT->getValueType(); 2232 2233 // Core issue 1454: For a literal constant expression of array or class type, 2234 // each subobject of its value shall have been initialized by a constant 2235 // expression. 2236 if (Value.isArray()) { 2237 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2238 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2239 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2240 Value.getArrayInitializedElt(I), Usage, 2241 SubobjectLoc, CheckedTemps)) 2242 return false; 2243 } 2244 if (!Value.hasArrayFiller()) 2245 return true; 2246 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2247 Value.getArrayFiller(), Usage, SubobjectLoc, 2248 CheckedTemps); 2249 } 2250 if (Value.isUnion() && Value.getUnionField()) { 2251 return CheckEvaluationResult( 2252 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2253 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2254 CheckedTemps); 2255 } 2256 if (Value.isStruct()) { 2257 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2258 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2259 unsigned BaseIndex = 0; 2260 for (const CXXBaseSpecifier &BS : CD->bases()) { 2261 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2262 Value.getStructBase(BaseIndex), Usage, 2263 BS.getBeginLoc(), CheckedTemps)) 2264 return false; 2265 ++BaseIndex; 2266 } 2267 } 2268 for (const auto *I : RD->fields()) { 2269 if (I->isUnnamedBitfield()) 2270 continue; 2271 2272 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2273 Value.getStructField(I->getFieldIndex()), 2274 Usage, I->getLocation(), CheckedTemps)) 2275 return false; 2276 } 2277 } 2278 2279 if (Value.isLValue() && 2280 CERK == CheckEvaluationResultKind::ConstantExpression) { 2281 LValue LVal; 2282 LVal.setFrom(Info.Ctx, Value); 2283 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2284 CheckedTemps); 2285 } 2286 2287 if (Value.isMemberPointer() && 2288 CERK == CheckEvaluationResultKind::ConstantExpression) 2289 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2290 2291 // Everything else is fine. 2292 return true; 2293 } 2294 2295 /// Check that this core constant expression value is a valid value for a 2296 /// constant expression. If not, report an appropriate diagnostic. Does not 2297 /// check that the expression is of literal type. 2298 static bool 2299 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2300 const APValue &Value, 2301 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2302 // Nothing to check for a constant expression of type 'cv void'. 2303 if (Type->isVoidType()) 2304 return true; 2305 2306 CheckedTemporaries CheckedTemps; 2307 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2308 Info, DiagLoc, Type, Value, Usage, 2309 SourceLocation(), CheckedTemps); 2310 } 2311 2312 /// Check that this evaluated value is fully-initialized and can be loaded by 2313 /// an lvalue-to-rvalue conversion. 2314 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2315 QualType Type, const APValue &Value) { 2316 CheckedTemporaries CheckedTemps; 2317 return CheckEvaluationResult( 2318 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2319 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2320 } 2321 2322 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2323 /// "the allocated storage is deallocated within the evaluation". 2324 static bool CheckMemoryLeaks(EvalInfo &Info) { 2325 if (!Info.HeapAllocs.empty()) { 2326 // We can still fold to a constant despite a compile-time memory leak, 2327 // so long as the heap allocation isn't referenced in the result (we check 2328 // that in CheckConstantExpression). 2329 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2330 diag::note_constexpr_memory_leak) 2331 << unsigned(Info.HeapAllocs.size() - 1); 2332 } 2333 return true; 2334 } 2335 2336 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2337 // A null base expression indicates a null pointer. These are always 2338 // evaluatable, and they are false unless the offset is zero. 2339 if (!Value.getLValueBase()) { 2340 Result = !Value.getLValueOffset().isZero(); 2341 return true; 2342 } 2343 2344 // We have a non-null base. These are generally known to be true, but if it's 2345 // a weak declaration it can be null at runtime. 2346 Result = true; 2347 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2348 return !Decl || !Decl->isWeak(); 2349 } 2350 2351 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2352 switch (Val.getKind()) { 2353 case APValue::None: 2354 case APValue::Indeterminate: 2355 return false; 2356 case APValue::Int: 2357 Result = Val.getInt().getBoolValue(); 2358 return true; 2359 case APValue::FixedPoint: 2360 Result = Val.getFixedPoint().getBoolValue(); 2361 return true; 2362 case APValue::Float: 2363 Result = !Val.getFloat().isZero(); 2364 return true; 2365 case APValue::ComplexInt: 2366 Result = Val.getComplexIntReal().getBoolValue() || 2367 Val.getComplexIntImag().getBoolValue(); 2368 return true; 2369 case APValue::ComplexFloat: 2370 Result = !Val.getComplexFloatReal().isZero() || 2371 !Val.getComplexFloatImag().isZero(); 2372 return true; 2373 case APValue::LValue: 2374 return EvalPointerValueAsBool(Val, Result); 2375 case APValue::MemberPointer: 2376 Result = Val.getMemberPointerDecl(); 2377 return true; 2378 case APValue::Vector: 2379 case APValue::Array: 2380 case APValue::Struct: 2381 case APValue::Union: 2382 case APValue::AddrLabelDiff: 2383 return false; 2384 } 2385 2386 llvm_unreachable("unknown APValue kind"); 2387 } 2388 2389 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2390 EvalInfo &Info) { 2391 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2392 APValue Val; 2393 if (!Evaluate(Val, Info, E)) 2394 return false; 2395 return HandleConversionToBool(Val, Result); 2396 } 2397 2398 template<typename T> 2399 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2400 const T &SrcValue, QualType DestType) { 2401 Info.CCEDiag(E, diag::note_constexpr_overflow) 2402 << SrcValue << DestType; 2403 return Info.noteUndefinedBehavior(); 2404 } 2405 2406 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2407 QualType SrcType, const APFloat &Value, 2408 QualType DestType, APSInt &Result) { 2409 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2410 // Determine whether we are converting to unsigned or signed. 2411 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2412 2413 Result = APSInt(DestWidth, !DestSigned); 2414 bool ignored; 2415 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2416 & APFloat::opInvalidOp) 2417 return HandleOverflow(Info, E, Value, DestType); 2418 return true; 2419 } 2420 2421 /// Get rounding mode used for evaluation of the specified expression. 2422 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2423 /// dynamic. 2424 /// If rounding mode is unknown at compile time, still try to evaluate the 2425 /// expression. If the result is exact, it does not depend on rounding mode. 2426 /// So return "tonearest" mode instead of "dynamic". 2427 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2428 bool &DynamicRM) { 2429 llvm::RoundingMode RM = 2430 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2431 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2432 if (DynamicRM) 2433 RM = llvm::RoundingMode::NearestTiesToEven; 2434 return RM; 2435 } 2436 2437 /// Check if the given evaluation result is allowed for constant evaluation. 2438 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2439 APFloat::opStatus St) { 2440 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2441 if ((St & APFloat::opInexact) && 2442 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2443 // Inexact result means that it depends on rounding mode. If the requested 2444 // mode is dynamic, the evaluation cannot be made in compile time. 2445 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2446 return false; 2447 } 2448 2449 if (St & APFloat::opStatus::opInvalidOp) { 2450 // There is no usefully definable result. 2451 Info.FFDiag(E); 2452 return false; 2453 } 2454 2455 // FIXME: if: 2456 // - evaluation triggered other FP exception, and 2457 // - exception mode is not "ignore", and 2458 // - the expression being evaluated is not a part of global variable 2459 // initializer, 2460 // the evaluation probably need to be rejected. 2461 return true; 2462 } 2463 2464 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2465 QualType SrcType, QualType DestType, 2466 APFloat &Result) { 2467 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2468 bool DynamicRM; 2469 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2470 APFloat::opStatus St; 2471 APFloat Value = Result; 2472 bool ignored; 2473 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2474 return checkFloatingPointResult(Info, E, St); 2475 } 2476 2477 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2478 QualType DestType, QualType SrcType, 2479 const APSInt &Value) { 2480 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2481 // Figure out if this is a truncate, extend or noop cast. 2482 // If the input is signed, do a sign extend, noop, or truncate. 2483 APSInt Result = Value.extOrTrunc(DestWidth); 2484 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2485 if (DestType->isBooleanType()) 2486 Result = Value.getBoolValue(); 2487 return Result; 2488 } 2489 2490 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2491 QualType SrcType, const APSInt &Value, 2492 QualType DestType, APFloat &Result) { 2493 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2494 Result.convertFromAPInt(Value, Value.isSigned(), 2495 APFloat::rmNearestTiesToEven); 2496 return true; 2497 } 2498 2499 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2500 APValue &Value, const FieldDecl *FD) { 2501 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2502 2503 if (!Value.isInt()) { 2504 // Trying to store a pointer-cast-to-integer into a bitfield. 2505 // FIXME: In this case, we should provide the diagnostic for casting 2506 // a pointer to an integer. 2507 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2508 Info.FFDiag(E); 2509 return false; 2510 } 2511 2512 APSInt &Int = Value.getInt(); 2513 unsigned OldBitWidth = Int.getBitWidth(); 2514 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2515 if (NewBitWidth < OldBitWidth) 2516 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2517 return true; 2518 } 2519 2520 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2521 llvm::APInt &Res) { 2522 APValue SVal; 2523 if (!Evaluate(SVal, Info, E)) 2524 return false; 2525 if (SVal.isInt()) { 2526 Res = SVal.getInt(); 2527 return true; 2528 } 2529 if (SVal.isFloat()) { 2530 Res = SVal.getFloat().bitcastToAPInt(); 2531 return true; 2532 } 2533 if (SVal.isVector()) { 2534 QualType VecTy = E->getType(); 2535 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2536 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2537 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2538 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2539 Res = llvm::APInt::getNullValue(VecSize); 2540 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2541 APValue &Elt = SVal.getVectorElt(i); 2542 llvm::APInt EltAsInt; 2543 if (Elt.isInt()) { 2544 EltAsInt = Elt.getInt(); 2545 } else if (Elt.isFloat()) { 2546 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2547 } else { 2548 // Don't try to handle vectors of anything other than int or float 2549 // (not sure if it's possible to hit this case). 2550 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2551 return false; 2552 } 2553 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2554 if (BigEndian) 2555 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2556 else 2557 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2558 } 2559 return true; 2560 } 2561 // Give up if the input isn't an int, float, or vector. For example, we 2562 // reject "(v4i16)(intptr_t)&a". 2563 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2564 return false; 2565 } 2566 2567 /// Perform the given integer operation, which is known to need at most BitWidth 2568 /// bits, and check for overflow in the original type (if that type was not an 2569 /// unsigned type). 2570 template<typename Operation> 2571 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2572 const APSInt &LHS, const APSInt &RHS, 2573 unsigned BitWidth, Operation Op, 2574 APSInt &Result) { 2575 if (LHS.isUnsigned()) { 2576 Result = Op(LHS, RHS); 2577 return true; 2578 } 2579 2580 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2581 Result = Value.trunc(LHS.getBitWidth()); 2582 if (Result.extend(BitWidth) != Value) { 2583 if (Info.checkingForUndefinedBehavior()) 2584 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2585 diag::warn_integer_constant_overflow) 2586 << Result.toString(10) << E->getType(); 2587 else 2588 return HandleOverflow(Info, E, Value, E->getType()); 2589 } 2590 return true; 2591 } 2592 2593 /// Perform the given binary integer operation. 2594 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2595 BinaryOperatorKind Opcode, APSInt RHS, 2596 APSInt &Result) { 2597 switch (Opcode) { 2598 default: 2599 Info.FFDiag(E); 2600 return false; 2601 case BO_Mul: 2602 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2603 std::multiplies<APSInt>(), Result); 2604 case BO_Add: 2605 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2606 std::plus<APSInt>(), Result); 2607 case BO_Sub: 2608 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2609 std::minus<APSInt>(), Result); 2610 case BO_And: Result = LHS & RHS; return true; 2611 case BO_Xor: Result = LHS ^ RHS; return true; 2612 case BO_Or: Result = LHS | RHS; return true; 2613 case BO_Div: 2614 case BO_Rem: 2615 if (RHS == 0) { 2616 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2617 return false; 2618 } 2619 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2620 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2621 // this operation and gives the two's complement result. 2622 if (RHS.isNegative() && RHS.isAllOnesValue() && 2623 LHS.isSigned() && LHS.isMinSignedValue()) 2624 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2625 E->getType()); 2626 return true; 2627 case BO_Shl: { 2628 if (Info.getLangOpts().OpenCL) 2629 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2630 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2631 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2632 RHS.isUnsigned()); 2633 else if (RHS.isSigned() && RHS.isNegative()) { 2634 // During constant-folding, a negative shift is an opposite shift. Such 2635 // a shift is not a constant expression. 2636 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2637 RHS = -RHS; 2638 goto shift_right; 2639 } 2640 shift_left: 2641 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2642 // the shifted type. 2643 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2644 if (SA != RHS) { 2645 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2646 << RHS << E->getType() << LHS.getBitWidth(); 2647 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2648 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2649 // operand, and must not overflow the corresponding unsigned type. 2650 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2651 // E1 x 2^E2 module 2^N. 2652 if (LHS.isNegative()) 2653 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2654 else if (LHS.countLeadingZeros() < SA) 2655 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2656 } 2657 Result = LHS << SA; 2658 return true; 2659 } 2660 case BO_Shr: { 2661 if (Info.getLangOpts().OpenCL) 2662 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2663 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2664 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2665 RHS.isUnsigned()); 2666 else if (RHS.isSigned() && RHS.isNegative()) { 2667 // During constant-folding, a negative shift is an opposite shift. Such a 2668 // shift is not a constant expression. 2669 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2670 RHS = -RHS; 2671 goto shift_left; 2672 } 2673 shift_right: 2674 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2675 // shifted type. 2676 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2677 if (SA != RHS) 2678 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2679 << RHS << E->getType() << LHS.getBitWidth(); 2680 Result = LHS >> SA; 2681 return true; 2682 } 2683 2684 case BO_LT: Result = LHS < RHS; return true; 2685 case BO_GT: Result = LHS > RHS; return true; 2686 case BO_LE: Result = LHS <= RHS; return true; 2687 case BO_GE: Result = LHS >= RHS; return true; 2688 case BO_EQ: Result = LHS == RHS; return true; 2689 case BO_NE: Result = LHS != RHS; return true; 2690 case BO_Cmp: 2691 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2692 } 2693 } 2694 2695 /// Perform the given binary floating-point operation, in-place, on LHS. 2696 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2697 APFloat &LHS, BinaryOperatorKind Opcode, 2698 const APFloat &RHS) { 2699 bool DynamicRM; 2700 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2701 APFloat::opStatus St; 2702 switch (Opcode) { 2703 default: 2704 Info.FFDiag(E); 2705 return false; 2706 case BO_Mul: 2707 St = LHS.multiply(RHS, RM); 2708 break; 2709 case BO_Add: 2710 St = LHS.add(RHS, RM); 2711 break; 2712 case BO_Sub: 2713 St = LHS.subtract(RHS, RM); 2714 break; 2715 case BO_Div: 2716 // [expr.mul]p4: 2717 // If the second operand of / or % is zero the behavior is undefined. 2718 if (RHS.isZero()) 2719 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2720 St = LHS.divide(RHS, RM); 2721 break; 2722 } 2723 2724 // [expr.pre]p4: 2725 // If during the evaluation of an expression, the result is not 2726 // mathematically defined [...], the behavior is undefined. 2727 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2728 if (LHS.isNaN()) { 2729 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2730 return Info.noteUndefinedBehavior(); 2731 } 2732 2733 return checkFloatingPointResult(Info, E, St); 2734 } 2735 2736 static bool handleLogicalOpForVector(const APInt &LHSValue, 2737 BinaryOperatorKind Opcode, 2738 const APInt &RHSValue, APInt &Result) { 2739 bool LHS = (LHSValue != 0); 2740 bool RHS = (RHSValue != 0); 2741 2742 if (Opcode == BO_LAnd) 2743 Result = LHS && RHS; 2744 else 2745 Result = LHS || RHS; 2746 return true; 2747 } 2748 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2749 BinaryOperatorKind Opcode, 2750 const APFloat &RHSValue, APInt &Result) { 2751 bool LHS = !LHSValue.isZero(); 2752 bool RHS = !RHSValue.isZero(); 2753 2754 if (Opcode == BO_LAnd) 2755 Result = LHS && RHS; 2756 else 2757 Result = LHS || RHS; 2758 return true; 2759 } 2760 2761 static bool handleLogicalOpForVector(const APValue &LHSValue, 2762 BinaryOperatorKind Opcode, 2763 const APValue &RHSValue, APInt &Result) { 2764 // The result is always an int type, however operands match the first. 2765 if (LHSValue.getKind() == APValue::Int) 2766 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2767 RHSValue.getInt(), Result); 2768 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2769 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2770 RHSValue.getFloat(), Result); 2771 } 2772 2773 template <typename APTy> 2774 static bool 2775 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2776 const APTy &RHSValue, APInt &Result) { 2777 switch (Opcode) { 2778 default: 2779 llvm_unreachable("unsupported binary operator"); 2780 case BO_EQ: 2781 Result = (LHSValue == RHSValue); 2782 break; 2783 case BO_NE: 2784 Result = (LHSValue != RHSValue); 2785 break; 2786 case BO_LT: 2787 Result = (LHSValue < RHSValue); 2788 break; 2789 case BO_GT: 2790 Result = (LHSValue > RHSValue); 2791 break; 2792 case BO_LE: 2793 Result = (LHSValue <= RHSValue); 2794 break; 2795 case BO_GE: 2796 Result = (LHSValue >= RHSValue); 2797 break; 2798 } 2799 2800 return true; 2801 } 2802 2803 static bool handleCompareOpForVector(const APValue &LHSValue, 2804 BinaryOperatorKind Opcode, 2805 const APValue &RHSValue, APInt &Result) { 2806 // The result is always an int type, however operands match the first. 2807 if (LHSValue.getKind() == APValue::Int) 2808 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2809 RHSValue.getInt(), Result); 2810 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2811 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2812 RHSValue.getFloat(), Result); 2813 } 2814 2815 // Perform binary operations for vector types, in place on the LHS. 2816 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2817 BinaryOperatorKind Opcode, 2818 APValue &LHSValue, 2819 const APValue &RHSValue) { 2820 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2821 "Operation not supported on vector types"); 2822 2823 const auto *VT = E->getType()->castAs<VectorType>(); 2824 unsigned NumElements = VT->getNumElements(); 2825 QualType EltTy = VT->getElementType(); 2826 2827 // In the cases (typically C as I've observed) where we aren't evaluating 2828 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2829 // just give up. 2830 if (!LHSValue.isVector()) { 2831 assert(LHSValue.isLValue() && 2832 "A vector result that isn't a vector OR uncalculated LValue"); 2833 Info.FFDiag(E); 2834 return false; 2835 } 2836 2837 assert(LHSValue.getVectorLength() == NumElements && 2838 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2839 2840 SmallVector<APValue, 4> ResultElements; 2841 2842 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2843 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2844 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2845 2846 if (EltTy->isIntegerType()) { 2847 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2848 EltTy->isUnsignedIntegerType()}; 2849 bool Success = true; 2850 2851 if (BinaryOperator::isLogicalOp(Opcode)) 2852 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2853 else if (BinaryOperator::isComparisonOp(Opcode)) 2854 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2855 else 2856 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2857 RHSElt.getInt(), EltResult); 2858 2859 if (!Success) { 2860 Info.FFDiag(E); 2861 return false; 2862 } 2863 ResultElements.emplace_back(EltResult); 2864 2865 } else if (EltTy->isFloatingType()) { 2866 assert(LHSElt.getKind() == APValue::Float && 2867 RHSElt.getKind() == APValue::Float && 2868 "Mismatched LHS/RHS/Result Type"); 2869 APFloat LHSFloat = LHSElt.getFloat(); 2870 2871 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2872 RHSElt.getFloat())) { 2873 Info.FFDiag(E); 2874 return false; 2875 } 2876 2877 ResultElements.emplace_back(LHSFloat); 2878 } 2879 } 2880 2881 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2882 return true; 2883 } 2884 2885 /// Cast an lvalue referring to a base subobject to a derived class, by 2886 /// truncating the lvalue's path to the given length. 2887 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2888 const RecordDecl *TruncatedType, 2889 unsigned TruncatedElements) { 2890 SubobjectDesignator &D = Result.Designator; 2891 2892 // Check we actually point to a derived class object. 2893 if (TruncatedElements == D.Entries.size()) 2894 return true; 2895 assert(TruncatedElements >= D.MostDerivedPathLength && 2896 "not casting to a derived class"); 2897 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2898 return false; 2899 2900 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2901 const RecordDecl *RD = TruncatedType; 2902 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2903 if (RD->isInvalidDecl()) return false; 2904 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2905 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2906 if (isVirtualBaseClass(D.Entries[I])) 2907 Result.Offset -= Layout.getVBaseClassOffset(Base); 2908 else 2909 Result.Offset -= Layout.getBaseClassOffset(Base); 2910 RD = Base; 2911 } 2912 D.Entries.resize(TruncatedElements); 2913 return true; 2914 } 2915 2916 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2917 const CXXRecordDecl *Derived, 2918 const CXXRecordDecl *Base, 2919 const ASTRecordLayout *RL = nullptr) { 2920 if (!RL) { 2921 if (Derived->isInvalidDecl()) return false; 2922 RL = &Info.Ctx.getASTRecordLayout(Derived); 2923 } 2924 2925 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2926 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2927 return true; 2928 } 2929 2930 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2931 const CXXRecordDecl *DerivedDecl, 2932 const CXXBaseSpecifier *Base) { 2933 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2934 2935 if (!Base->isVirtual()) 2936 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2937 2938 SubobjectDesignator &D = Obj.Designator; 2939 if (D.Invalid) 2940 return false; 2941 2942 // Extract most-derived object and corresponding type. 2943 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2944 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2945 return false; 2946 2947 // Find the virtual base class. 2948 if (DerivedDecl->isInvalidDecl()) return false; 2949 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2950 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2951 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2952 return true; 2953 } 2954 2955 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2956 QualType Type, LValue &Result) { 2957 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2958 PathE = E->path_end(); 2959 PathI != PathE; ++PathI) { 2960 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2961 *PathI)) 2962 return false; 2963 Type = (*PathI)->getType(); 2964 } 2965 return true; 2966 } 2967 2968 /// Cast an lvalue referring to a derived class to a known base subobject. 2969 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2970 const CXXRecordDecl *DerivedRD, 2971 const CXXRecordDecl *BaseRD) { 2972 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2973 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2974 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2975 llvm_unreachable("Class must be derived from the passed in base class!"); 2976 2977 for (CXXBasePathElement &Elem : Paths.front()) 2978 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2979 return false; 2980 return true; 2981 } 2982 2983 /// Update LVal to refer to the given field, which must be a member of the type 2984 /// currently described by LVal. 2985 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2986 const FieldDecl *FD, 2987 const ASTRecordLayout *RL = nullptr) { 2988 if (!RL) { 2989 if (FD->getParent()->isInvalidDecl()) return false; 2990 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2991 } 2992 2993 unsigned I = FD->getFieldIndex(); 2994 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2995 LVal.addDecl(Info, E, FD); 2996 return true; 2997 } 2998 2999 /// Update LVal to refer to the given indirect field. 3000 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3001 LValue &LVal, 3002 const IndirectFieldDecl *IFD) { 3003 for (const auto *C : IFD->chain()) 3004 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3005 return false; 3006 return true; 3007 } 3008 3009 /// Get the size of the given type in char units. 3010 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3011 QualType Type, CharUnits &Size) { 3012 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3013 // extension. 3014 if (Type->isVoidType() || Type->isFunctionType()) { 3015 Size = CharUnits::One(); 3016 return true; 3017 } 3018 3019 if (Type->isDependentType()) { 3020 Info.FFDiag(Loc); 3021 return false; 3022 } 3023 3024 if (!Type->isConstantSizeType()) { 3025 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3026 // FIXME: Better diagnostic. 3027 Info.FFDiag(Loc); 3028 return false; 3029 } 3030 3031 Size = Info.Ctx.getTypeSizeInChars(Type); 3032 return true; 3033 } 3034 3035 /// Update a pointer value to model pointer arithmetic. 3036 /// \param Info - Information about the ongoing evaluation. 3037 /// \param E - The expression being evaluated, for diagnostic purposes. 3038 /// \param LVal - The pointer value to be updated. 3039 /// \param EltTy - The pointee type represented by LVal. 3040 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3041 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3042 LValue &LVal, QualType EltTy, 3043 APSInt Adjustment) { 3044 CharUnits SizeOfPointee; 3045 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3046 return false; 3047 3048 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3049 return true; 3050 } 3051 3052 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3053 LValue &LVal, QualType EltTy, 3054 int64_t Adjustment) { 3055 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3056 APSInt::get(Adjustment)); 3057 } 3058 3059 /// Update an lvalue to refer to a component of a complex number. 3060 /// \param Info - Information about the ongoing evaluation. 3061 /// \param LVal - The lvalue to be updated. 3062 /// \param EltTy - The complex number's component type. 3063 /// \param Imag - False for the real component, true for the imaginary. 3064 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3065 LValue &LVal, QualType EltTy, 3066 bool Imag) { 3067 if (Imag) { 3068 CharUnits SizeOfComponent; 3069 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3070 return false; 3071 LVal.Offset += SizeOfComponent; 3072 } 3073 LVal.addComplex(Info, E, EltTy, Imag); 3074 return true; 3075 } 3076 3077 /// Try to evaluate the initializer for a variable declaration. 3078 /// 3079 /// \param Info Information about the ongoing evaluation. 3080 /// \param E An expression to be used when printing diagnostics. 3081 /// \param VD The variable whose initializer should be obtained. 3082 /// \param Frame The frame in which the variable was created. Must be null 3083 /// if this variable is not local to the evaluation. 3084 /// \param Result Filled in with a pointer to the value of the variable. 3085 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3086 const VarDecl *VD, CallStackFrame *Frame, 3087 APValue *&Result, const LValue *LVal) { 3088 3089 // If this is a parameter to an active constexpr function call, perform 3090 // argument substitution. 3091 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 3092 // Assume arguments of a potential constant expression are unknown 3093 // constant expressions. 3094 if (Info.checkingPotentialConstantExpression()) 3095 return false; 3096 if (!Frame || !Frame->Arguments) { 3097 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD; 3098 return false; 3099 } 3100 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 3101 return true; 3102 } 3103 3104 // If this is a local variable, dig out its value. 3105 if (Frame) { 3106 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 3107 : Frame->getCurrentTemporary(VD); 3108 if (!Result) { 3109 // Assume variables referenced within a lambda's call operator that were 3110 // not declared within the call operator are captures and during checking 3111 // of a potential constant expression, assume they are unknown constant 3112 // expressions. 3113 assert(isLambdaCallOperator(Frame->Callee) && 3114 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3115 "missing value for local variable"); 3116 if (Info.checkingPotentialConstantExpression()) 3117 return false; 3118 // FIXME: implement capture evaluation during constant expr evaluation. 3119 Info.FFDiag(E->getBeginLoc(), 3120 diag::note_unimplemented_constexpr_lambda_feature_ast) 3121 << "captures not currently allowed"; 3122 return false; 3123 } 3124 return true; 3125 } 3126 3127 // Dig out the initializer, and use the declaration which it's attached to. 3128 // FIXME: We should eventually check whether the variable has a reachable 3129 // initializing declaration. 3130 const Expr *Init = VD->getAnyInitializer(VD); 3131 if (!Init) { 3132 // Don't diagnose during potential constant expression checking; an 3133 // initializer might be added later. 3134 if (!Info.checkingPotentialConstantExpression()) { 3135 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3136 << VD; 3137 Info.Note(VD->getLocation(), diag::note_declared_at); 3138 } 3139 return false; 3140 } 3141 3142 if (Init->isValueDependent()) { 3143 // The DeclRefExpr is not value-dependent, but the variable it refers to 3144 // has a value-dependent initializer. This should only happen in 3145 // constant-folding cases, where the variable is not actually of a suitable 3146 // type for use in a constant expression (otherwise the DeclRefExpr would 3147 // have been value-dependent too), so diagnose that. 3148 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3149 if (!Info.checkingPotentialConstantExpression()) { 3150 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3151 ? diag::note_constexpr_ltor_non_constexpr 3152 : diag::note_constexpr_ltor_non_integral, 1) 3153 << VD << VD->getType(); 3154 Info.Note(VD->getLocation(), diag::note_declared_at); 3155 } 3156 return false; 3157 } 3158 3159 // If we're currently evaluating the initializer of this declaration, use that 3160 // in-flight value. 3161 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 3162 Result = Info.EvaluatingDeclValue; 3163 return true; 3164 } 3165 3166 // Check that we can fold the initializer. In C++, we will have already done 3167 // this in the cases where it matters for conformance. 3168 SmallVector<PartialDiagnosticAt, 8> Notes; 3169 if (!VD->evaluateValue(Notes)) { 3170 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3171 Notes.size() + 1) << VD; 3172 Info.Note(VD->getLocation(), diag::note_declared_at); 3173 Info.addNotes(Notes); 3174 return false; 3175 } 3176 3177 // Check that the variable is actually usable in constant expressions. 3178 if (!VD->checkInitIsICE()) { 3179 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 3180 Notes.size() + 1) << VD; 3181 Info.Note(VD->getLocation(), diag::note_declared_at); 3182 Info.addNotes(Notes); 3183 } 3184 3185 // Never use the initializer of a weak variable, not even for constant 3186 // folding. We can't be sure that this is the definition that will be used. 3187 if (VD->isWeak()) { 3188 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3189 Info.Note(VD->getLocation(), diag::note_declared_at); 3190 return false; 3191 } 3192 3193 Result = VD->getEvaluatedValue(); 3194 return true; 3195 } 3196 3197 static bool IsConstNonVolatile(QualType T) { 3198 Qualifiers Quals = T.getQualifiers(); 3199 return Quals.hasConst() && !Quals.hasVolatile(); 3200 } 3201 3202 /// Get the base index of the given base class within an APValue representing 3203 /// the given derived class. 3204 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3205 const CXXRecordDecl *Base) { 3206 Base = Base->getCanonicalDecl(); 3207 unsigned Index = 0; 3208 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3209 E = Derived->bases_end(); I != E; ++I, ++Index) { 3210 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3211 return Index; 3212 } 3213 3214 llvm_unreachable("base class missing from derived class's bases list"); 3215 } 3216 3217 /// Extract the value of a character from a string literal. 3218 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3219 uint64_t Index) { 3220 assert(!isa<SourceLocExpr>(Lit) && 3221 "SourceLocExpr should have already been converted to a StringLiteral"); 3222 3223 // FIXME: Support MakeStringConstant 3224 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3225 std::string Str; 3226 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3227 assert(Index <= Str.size() && "Index too large"); 3228 return APSInt::getUnsigned(Str.c_str()[Index]); 3229 } 3230 3231 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3232 Lit = PE->getFunctionName(); 3233 const StringLiteral *S = cast<StringLiteral>(Lit); 3234 const ConstantArrayType *CAT = 3235 Info.Ctx.getAsConstantArrayType(S->getType()); 3236 assert(CAT && "string literal isn't an array"); 3237 QualType CharType = CAT->getElementType(); 3238 assert(CharType->isIntegerType() && "unexpected character type"); 3239 3240 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3241 CharType->isUnsignedIntegerType()); 3242 if (Index < S->getLength()) 3243 Value = S->getCodeUnit(Index); 3244 return Value; 3245 } 3246 3247 // Expand a string literal into an array of characters. 3248 // 3249 // FIXME: This is inefficient; we should probably introduce something similar 3250 // to the LLVM ConstantDataArray to make this cheaper. 3251 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3252 APValue &Result, 3253 QualType AllocType = QualType()) { 3254 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3255 AllocType.isNull() ? S->getType() : AllocType); 3256 assert(CAT && "string literal isn't an array"); 3257 QualType CharType = CAT->getElementType(); 3258 assert(CharType->isIntegerType() && "unexpected character type"); 3259 3260 unsigned Elts = CAT->getSize().getZExtValue(); 3261 Result = APValue(APValue::UninitArray(), 3262 std::min(S->getLength(), Elts), Elts); 3263 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3264 CharType->isUnsignedIntegerType()); 3265 if (Result.hasArrayFiller()) 3266 Result.getArrayFiller() = APValue(Value); 3267 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3268 Value = S->getCodeUnit(I); 3269 Result.getArrayInitializedElt(I) = APValue(Value); 3270 } 3271 } 3272 3273 // Expand an array so that it has more than Index filled elements. 3274 static void expandArray(APValue &Array, unsigned Index) { 3275 unsigned Size = Array.getArraySize(); 3276 assert(Index < Size); 3277 3278 // Always at least double the number of elements for which we store a value. 3279 unsigned OldElts = Array.getArrayInitializedElts(); 3280 unsigned NewElts = std::max(Index+1, OldElts * 2); 3281 NewElts = std::min(Size, std::max(NewElts, 8u)); 3282 3283 // Copy the data across. 3284 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3285 for (unsigned I = 0; I != OldElts; ++I) 3286 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3287 for (unsigned I = OldElts; I != NewElts; ++I) 3288 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3289 if (NewValue.hasArrayFiller()) 3290 NewValue.getArrayFiller() = Array.getArrayFiller(); 3291 Array.swap(NewValue); 3292 } 3293 3294 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3295 /// conversion. If it's of class type, we may assume that the copy operation 3296 /// is trivial. Note that this is never true for a union type with fields 3297 /// (because the copy always "reads" the active member) and always true for 3298 /// a non-class type. 3299 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3300 static bool isReadByLvalueToRvalueConversion(QualType T) { 3301 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3302 return !RD || isReadByLvalueToRvalueConversion(RD); 3303 } 3304 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3305 // FIXME: A trivial copy of a union copies the object representation, even if 3306 // the union is empty. 3307 if (RD->isUnion()) 3308 return !RD->field_empty(); 3309 if (RD->isEmpty()) 3310 return false; 3311 3312 for (auto *Field : RD->fields()) 3313 if (!Field->isUnnamedBitfield() && 3314 isReadByLvalueToRvalueConversion(Field->getType())) 3315 return true; 3316 3317 for (auto &BaseSpec : RD->bases()) 3318 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3319 return true; 3320 3321 return false; 3322 } 3323 3324 /// Diagnose an attempt to read from any unreadable field within the specified 3325 /// type, which might be a class type. 3326 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3327 QualType T) { 3328 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3329 if (!RD) 3330 return false; 3331 3332 if (!RD->hasMutableFields()) 3333 return false; 3334 3335 for (auto *Field : RD->fields()) { 3336 // If we're actually going to read this field in some way, then it can't 3337 // be mutable. If we're in a union, then assigning to a mutable field 3338 // (even an empty one) can change the active member, so that's not OK. 3339 // FIXME: Add core issue number for the union case. 3340 if (Field->isMutable() && 3341 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3342 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3343 Info.Note(Field->getLocation(), diag::note_declared_at); 3344 return true; 3345 } 3346 3347 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3348 return true; 3349 } 3350 3351 for (auto &BaseSpec : RD->bases()) 3352 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3353 return true; 3354 3355 // All mutable fields were empty, and thus not actually read. 3356 return false; 3357 } 3358 3359 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3360 APValue::LValueBase Base, 3361 bool MutableSubobject = false) { 3362 // A temporary we created. 3363 if (Base.getCallIndex()) 3364 return true; 3365 3366 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3367 if (!Evaluating) 3368 return false; 3369 3370 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3371 3372 switch (Info.IsEvaluatingDecl) { 3373 case EvalInfo::EvaluatingDeclKind::None: 3374 return false; 3375 3376 case EvalInfo::EvaluatingDeclKind::Ctor: 3377 // The variable whose initializer we're evaluating. 3378 if (BaseD) 3379 return declaresSameEntity(Evaluating, BaseD); 3380 3381 // A temporary lifetime-extended by the variable whose initializer we're 3382 // evaluating. 3383 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3384 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3385 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3386 return false; 3387 3388 case EvalInfo::EvaluatingDeclKind::Dtor: 3389 // C++2a [expr.const]p6: 3390 // [during constant destruction] the lifetime of a and its non-mutable 3391 // subobjects (but not its mutable subobjects) [are] considered to start 3392 // within e. 3393 // 3394 // FIXME: We can meaningfully extend this to cover non-const objects, but 3395 // we will need special handling: we should be able to access only 3396 // subobjects of such objects that are themselves declared const. 3397 if (!BaseD || 3398 !(BaseD->getType().isConstQualified() || 3399 BaseD->getType()->isReferenceType()) || 3400 MutableSubobject) 3401 return false; 3402 return declaresSameEntity(Evaluating, BaseD); 3403 } 3404 3405 llvm_unreachable("unknown evaluating decl kind"); 3406 } 3407 3408 namespace { 3409 /// A handle to a complete object (an object that is not a subobject of 3410 /// another object). 3411 struct CompleteObject { 3412 /// The identity of the object. 3413 APValue::LValueBase Base; 3414 /// The value of the complete object. 3415 APValue *Value; 3416 /// The type of the complete object. 3417 QualType Type; 3418 3419 CompleteObject() : Value(nullptr) {} 3420 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3421 : Base(Base), Value(Value), Type(Type) {} 3422 3423 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3424 // If this isn't a "real" access (eg, if it's just accessing the type 3425 // info), allow it. We assume the type doesn't change dynamically for 3426 // subobjects of constexpr objects (even though we'd hit UB here if it 3427 // did). FIXME: Is this right? 3428 if (!isAnyAccess(AK)) 3429 return true; 3430 3431 // In C++14 onwards, it is permitted to read a mutable member whose 3432 // lifetime began within the evaluation. 3433 // FIXME: Should we also allow this in C++11? 3434 if (!Info.getLangOpts().CPlusPlus14) 3435 return false; 3436 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3437 } 3438 3439 explicit operator bool() const { return !Type.isNull(); } 3440 }; 3441 } // end anonymous namespace 3442 3443 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3444 bool IsMutable = false) { 3445 // C++ [basic.type.qualifier]p1: 3446 // - A const object is an object of type const T or a non-mutable subobject 3447 // of a const object. 3448 if (ObjType.isConstQualified() && !IsMutable) 3449 SubobjType.addConst(); 3450 // - A volatile object is an object of type const T or a subobject of a 3451 // volatile object. 3452 if (ObjType.isVolatileQualified()) 3453 SubobjType.addVolatile(); 3454 return SubobjType; 3455 } 3456 3457 /// Find the designated sub-object of an rvalue. 3458 template<typename SubobjectHandler> 3459 typename SubobjectHandler::result_type 3460 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3461 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3462 if (Sub.Invalid) 3463 // A diagnostic will have already been produced. 3464 return handler.failed(); 3465 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3466 if (Info.getLangOpts().CPlusPlus11) 3467 Info.FFDiag(E, Sub.isOnePastTheEnd() 3468 ? diag::note_constexpr_access_past_end 3469 : diag::note_constexpr_access_unsized_array) 3470 << handler.AccessKind; 3471 else 3472 Info.FFDiag(E); 3473 return handler.failed(); 3474 } 3475 3476 APValue *O = Obj.Value; 3477 QualType ObjType = Obj.Type; 3478 const FieldDecl *LastField = nullptr; 3479 const FieldDecl *VolatileField = nullptr; 3480 3481 // Walk the designator's path to find the subobject. 3482 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3483 // Reading an indeterminate value is undefined, but assigning over one is OK. 3484 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3485 (O->isIndeterminate() && 3486 !isValidIndeterminateAccess(handler.AccessKind))) { 3487 if (!Info.checkingPotentialConstantExpression()) 3488 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3489 << handler.AccessKind << O->isIndeterminate(); 3490 return handler.failed(); 3491 } 3492 3493 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3494 // const and volatile semantics are not applied on an object under 3495 // {con,de}struction. 3496 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3497 ObjType->isRecordType() && 3498 Info.isEvaluatingCtorDtor( 3499 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3500 Sub.Entries.begin() + I)) != 3501 ConstructionPhase::None) { 3502 ObjType = Info.Ctx.getCanonicalType(ObjType); 3503 ObjType.removeLocalConst(); 3504 ObjType.removeLocalVolatile(); 3505 } 3506 3507 // If this is our last pass, check that the final object type is OK. 3508 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3509 // Accesses to volatile objects are prohibited. 3510 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3511 if (Info.getLangOpts().CPlusPlus) { 3512 int DiagKind; 3513 SourceLocation Loc; 3514 const NamedDecl *Decl = nullptr; 3515 if (VolatileField) { 3516 DiagKind = 2; 3517 Loc = VolatileField->getLocation(); 3518 Decl = VolatileField; 3519 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3520 DiagKind = 1; 3521 Loc = VD->getLocation(); 3522 Decl = VD; 3523 } else { 3524 DiagKind = 0; 3525 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3526 Loc = E->getExprLoc(); 3527 } 3528 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3529 << handler.AccessKind << DiagKind << Decl; 3530 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3531 } else { 3532 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3533 } 3534 return handler.failed(); 3535 } 3536 3537 // If we are reading an object of class type, there may still be more 3538 // things we need to check: if there are any mutable subobjects, we 3539 // cannot perform this read. (This only happens when performing a trivial 3540 // copy or assignment.) 3541 if (ObjType->isRecordType() && 3542 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3543 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3544 return handler.failed(); 3545 } 3546 3547 if (I == N) { 3548 if (!handler.found(*O, ObjType)) 3549 return false; 3550 3551 // If we modified a bit-field, truncate it to the right width. 3552 if (isModification(handler.AccessKind) && 3553 LastField && LastField->isBitField() && 3554 !truncateBitfieldValue(Info, E, *O, LastField)) 3555 return false; 3556 3557 return true; 3558 } 3559 3560 LastField = nullptr; 3561 if (ObjType->isArrayType()) { 3562 // Next subobject is an array element. 3563 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3564 assert(CAT && "vla in literal type?"); 3565 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3566 if (CAT->getSize().ule(Index)) { 3567 // Note, it should not be possible to form a pointer with a valid 3568 // designator which points more than one past the end of the array. 3569 if (Info.getLangOpts().CPlusPlus11) 3570 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3571 << handler.AccessKind; 3572 else 3573 Info.FFDiag(E); 3574 return handler.failed(); 3575 } 3576 3577 ObjType = CAT->getElementType(); 3578 3579 if (O->getArrayInitializedElts() > Index) 3580 O = &O->getArrayInitializedElt(Index); 3581 else if (!isRead(handler.AccessKind)) { 3582 expandArray(*O, Index); 3583 O = &O->getArrayInitializedElt(Index); 3584 } else 3585 O = &O->getArrayFiller(); 3586 } else if (ObjType->isAnyComplexType()) { 3587 // Next subobject is a complex number. 3588 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3589 if (Index > 1) { 3590 if (Info.getLangOpts().CPlusPlus11) 3591 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3592 << handler.AccessKind; 3593 else 3594 Info.FFDiag(E); 3595 return handler.failed(); 3596 } 3597 3598 ObjType = getSubobjectType( 3599 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3600 3601 assert(I == N - 1 && "extracting subobject of scalar?"); 3602 if (O->isComplexInt()) { 3603 return handler.found(Index ? O->getComplexIntImag() 3604 : O->getComplexIntReal(), ObjType); 3605 } else { 3606 assert(O->isComplexFloat()); 3607 return handler.found(Index ? O->getComplexFloatImag() 3608 : O->getComplexFloatReal(), ObjType); 3609 } 3610 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3611 if (Field->isMutable() && 3612 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3613 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3614 << handler.AccessKind << Field; 3615 Info.Note(Field->getLocation(), diag::note_declared_at); 3616 return handler.failed(); 3617 } 3618 3619 // Next subobject is a class, struct or union field. 3620 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3621 if (RD->isUnion()) { 3622 const FieldDecl *UnionField = O->getUnionField(); 3623 if (!UnionField || 3624 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3625 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3626 // Placement new onto an inactive union member makes it active. 3627 O->setUnion(Field, APValue()); 3628 } else { 3629 // FIXME: If O->getUnionValue() is absent, report that there's no 3630 // active union member rather than reporting the prior active union 3631 // member. We'll need to fix nullptr_t to not use APValue() as its 3632 // representation first. 3633 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3634 << handler.AccessKind << Field << !UnionField << UnionField; 3635 return handler.failed(); 3636 } 3637 } 3638 O = &O->getUnionValue(); 3639 } else 3640 O = &O->getStructField(Field->getFieldIndex()); 3641 3642 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3643 LastField = Field; 3644 if (Field->getType().isVolatileQualified()) 3645 VolatileField = Field; 3646 } else { 3647 // Next subobject is a base class. 3648 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3649 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3650 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3651 3652 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3653 } 3654 } 3655 } 3656 3657 namespace { 3658 struct ExtractSubobjectHandler { 3659 EvalInfo &Info; 3660 const Expr *E; 3661 APValue &Result; 3662 const AccessKinds AccessKind; 3663 3664 typedef bool result_type; 3665 bool failed() { return false; } 3666 bool found(APValue &Subobj, QualType SubobjType) { 3667 Result = Subobj; 3668 if (AccessKind == AK_ReadObjectRepresentation) 3669 return true; 3670 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3671 } 3672 bool found(APSInt &Value, QualType SubobjType) { 3673 Result = APValue(Value); 3674 return true; 3675 } 3676 bool found(APFloat &Value, QualType SubobjType) { 3677 Result = APValue(Value); 3678 return true; 3679 } 3680 }; 3681 } // end anonymous namespace 3682 3683 /// Extract the designated sub-object of an rvalue. 3684 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3685 const CompleteObject &Obj, 3686 const SubobjectDesignator &Sub, APValue &Result, 3687 AccessKinds AK = AK_Read) { 3688 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3689 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3690 return findSubobject(Info, E, Obj, Sub, Handler); 3691 } 3692 3693 namespace { 3694 struct ModifySubobjectHandler { 3695 EvalInfo &Info; 3696 APValue &NewVal; 3697 const Expr *E; 3698 3699 typedef bool result_type; 3700 static const AccessKinds AccessKind = AK_Assign; 3701 3702 bool checkConst(QualType QT) { 3703 // Assigning to a const object has undefined behavior. 3704 if (QT.isConstQualified()) { 3705 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3706 return false; 3707 } 3708 return true; 3709 } 3710 3711 bool failed() { return false; } 3712 bool found(APValue &Subobj, QualType SubobjType) { 3713 if (!checkConst(SubobjType)) 3714 return false; 3715 // We've been given ownership of NewVal, so just swap it in. 3716 Subobj.swap(NewVal); 3717 return true; 3718 } 3719 bool found(APSInt &Value, QualType SubobjType) { 3720 if (!checkConst(SubobjType)) 3721 return false; 3722 if (!NewVal.isInt()) { 3723 // Maybe trying to write a cast pointer value into a complex? 3724 Info.FFDiag(E); 3725 return false; 3726 } 3727 Value = NewVal.getInt(); 3728 return true; 3729 } 3730 bool found(APFloat &Value, QualType SubobjType) { 3731 if (!checkConst(SubobjType)) 3732 return false; 3733 Value = NewVal.getFloat(); 3734 return true; 3735 } 3736 }; 3737 } // end anonymous namespace 3738 3739 const AccessKinds ModifySubobjectHandler::AccessKind; 3740 3741 /// Update the designated sub-object of an rvalue to the given value. 3742 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3743 const CompleteObject &Obj, 3744 const SubobjectDesignator &Sub, 3745 APValue &NewVal) { 3746 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3747 return findSubobject(Info, E, Obj, Sub, Handler); 3748 } 3749 3750 /// Find the position where two subobject designators diverge, or equivalently 3751 /// the length of the common initial subsequence. 3752 static unsigned FindDesignatorMismatch(QualType ObjType, 3753 const SubobjectDesignator &A, 3754 const SubobjectDesignator &B, 3755 bool &WasArrayIndex) { 3756 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3757 for (/**/; I != N; ++I) { 3758 if (!ObjType.isNull() && 3759 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3760 // Next subobject is an array element. 3761 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3762 WasArrayIndex = true; 3763 return I; 3764 } 3765 if (ObjType->isAnyComplexType()) 3766 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3767 else 3768 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3769 } else { 3770 if (A.Entries[I].getAsBaseOrMember() != 3771 B.Entries[I].getAsBaseOrMember()) { 3772 WasArrayIndex = false; 3773 return I; 3774 } 3775 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3776 // Next subobject is a field. 3777 ObjType = FD->getType(); 3778 else 3779 // Next subobject is a base class. 3780 ObjType = QualType(); 3781 } 3782 } 3783 WasArrayIndex = false; 3784 return I; 3785 } 3786 3787 /// Determine whether the given subobject designators refer to elements of the 3788 /// same array object. 3789 static bool AreElementsOfSameArray(QualType ObjType, 3790 const SubobjectDesignator &A, 3791 const SubobjectDesignator &B) { 3792 if (A.Entries.size() != B.Entries.size()) 3793 return false; 3794 3795 bool IsArray = A.MostDerivedIsArrayElement; 3796 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3797 // A is a subobject of the array element. 3798 return false; 3799 3800 // If A (and B) designates an array element, the last entry will be the array 3801 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3802 // of length 1' case, and the entire path must match. 3803 bool WasArrayIndex; 3804 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3805 return CommonLength >= A.Entries.size() - IsArray; 3806 } 3807 3808 /// Find the complete object to which an LValue refers. 3809 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3810 AccessKinds AK, const LValue &LVal, 3811 QualType LValType) { 3812 if (LVal.InvalidBase) { 3813 Info.FFDiag(E); 3814 return CompleteObject(); 3815 } 3816 3817 if (!LVal.Base) { 3818 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3819 return CompleteObject(); 3820 } 3821 3822 CallStackFrame *Frame = nullptr; 3823 unsigned Depth = 0; 3824 if (LVal.getLValueCallIndex()) { 3825 std::tie(Frame, Depth) = 3826 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3827 if (!Frame) { 3828 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3829 << AK << LVal.Base.is<const ValueDecl*>(); 3830 NoteLValueLocation(Info, LVal.Base); 3831 return CompleteObject(); 3832 } 3833 } 3834 3835 bool IsAccess = isAnyAccess(AK); 3836 3837 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3838 // is not a constant expression (even if the object is non-volatile). We also 3839 // apply this rule to C++98, in order to conform to the expected 'volatile' 3840 // semantics. 3841 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3842 if (Info.getLangOpts().CPlusPlus) 3843 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3844 << AK << LValType; 3845 else 3846 Info.FFDiag(E); 3847 return CompleteObject(); 3848 } 3849 3850 // Compute value storage location and type of base object. 3851 APValue *BaseVal = nullptr; 3852 QualType BaseType = getType(LVal.Base); 3853 3854 if (const ConstantExpr *CE = 3855 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3856 /// Nested immediate invocation have been previously removed so if we found 3857 /// a ConstantExpr it can only be the EvaluatingDecl. 3858 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3859 (void)CE; 3860 BaseVal = Info.EvaluatingDeclValue; 3861 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3862 // Allow reading from a GUID declaration. 3863 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3864 if (isModification(AK)) { 3865 // All the remaining cases do not permit modification of the object. 3866 Info.FFDiag(E, diag::note_constexpr_modify_global); 3867 return CompleteObject(); 3868 } 3869 APValue &V = GD->getAsAPValue(); 3870 if (V.isAbsent()) { 3871 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3872 << GD->getType(); 3873 return CompleteObject(); 3874 } 3875 return CompleteObject(LVal.Base, &V, GD->getType()); 3876 } 3877 3878 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3879 // In C++11, constexpr, non-volatile variables initialized with constant 3880 // expressions are constant expressions too. Inside constexpr functions, 3881 // parameters are constant expressions even if they're non-const. 3882 // In C++1y, objects local to a constant expression (those with a Frame) are 3883 // both readable and writable inside constant expressions. 3884 // In C, such things can also be folded, although they are not ICEs. 3885 const VarDecl *VD = dyn_cast<VarDecl>(D); 3886 if (VD) { 3887 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3888 VD = VDef; 3889 } 3890 if (!VD || VD->isInvalidDecl()) { 3891 Info.FFDiag(E); 3892 return CompleteObject(); 3893 } 3894 3895 // In OpenCL if a variable is in constant address space it is a const value. 3896 bool IsConstant = BaseType.isConstQualified() || 3897 (Info.getLangOpts().OpenCL && 3898 BaseType.getAddressSpace() == LangAS::opencl_constant); 3899 3900 // Unless we're looking at a local variable or argument in a constexpr call, 3901 // the variable we're reading must be const. 3902 if (!Frame) { 3903 if (Info.getLangOpts().CPlusPlus14 && 3904 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3905 // OK, we can read and modify an object if we're in the process of 3906 // evaluating its initializer, because its lifetime began in this 3907 // evaluation. 3908 } else if (isModification(AK)) { 3909 // All the remaining cases do not permit modification of the object. 3910 Info.FFDiag(E, diag::note_constexpr_modify_global); 3911 return CompleteObject(); 3912 } else if (VD->isConstexpr()) { 3913 // OK, we can read this variable. 3914 } else if (BaseType->isIntegralOrEnumerationType()) { 3915 // In OpenCL if a variable is in constant address space it is a const 3916 // value. 3917 if (!IsConstant) { 3918 if (!IsAccess) 3919 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3920 if (Info.getLangOpts().CPlusPlus) { 3921 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3922 Info.Note(VD->getLocation(), diag::note_declared_at); 3923 } else { 3924 Info.FFDiag(E); 3925 } 3926 return CompleteObject(); 3927 } 3928 } else if (!IsAccess) { 3929 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3930 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 3931 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 3932 // This variable might end up being constexpr. Don't diagnose it yet. 3933 } else if (IsConstant) { 3934 // Keep evaluating to see what we can do. In particular, we support 3935 // folding of const floating-point types, in order to make static const 3936 // data members of such types (supported as an extension) more useful. 3937 if (Info.getLangOpts().CPlusPlus) { 3938 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 3939 ? diag::note_constexpr_ltor_non_constexpr 3940 : diag::note_constexpr_ltor_non_integral, 1) 3941 << VD << BaseType; 3942 Info.Note(VD->getLocation(), diag::note_declared_at); 3943 } else { 3944 Info.CCEDiag(E); 3945 } 3946 } else { 3947 // Never allow reading a non-const value. 3948 if (Info.getLangOpts().CPlusPlus) { 3949 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3950 ? diag::note_constexpr_ltor_non_constexpr 3951 : diag::note_constexpr_ltor_non_integral, 1) 3952 << VD << BaseType; 3953 Info.Note(VD->getLocation(), diag::note_declared_at); 3954 } else { 3955 Info.FFDiag(E); 3956 } 3957 return CompleteObject(); 3958 } 3959 } 3960 3961 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3962 return CompleteObject(); 3963 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3964 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3965 if (!Alloc) { 3966 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3967 return CompleteObject(); 3968 } 3969 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3970 LVal.Base.getDynamicAllocType()); 3971 } else { 3972 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3973 3974 if (!Frame) { 3975 if (const MaterializeTemporaryExpr *MTE = 3976 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3977 assert(MTE->getStorageDuration() == SD_Static && 3978 "should have a frame for a non-global materialized temporary"); 3979 3980 // Per C++1y [expr.const]p2: 3981 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3982 // - a [...] glvalue of integral or enumeration type that refers to 3983 // a non-volatile const object [...] 3984 // [...] 3985 // - a [...] glvalue of literal type that refers to a non-volatile 3986 // object whose lifetime began within the evaluation of e. 3987 // 3988 // C++11 misses the 'began within the evaluation of e' check and 3989 // instead allows all temporaries, including things like: 3990 // int &&r = 1; 3991 // int x = ++r; 3992 // constexpr int k = r; 3993 // Therefore we use the C++14 rules in C++11 too. 3994 // 3995 // Note that temporaries whose lifetimes began while evaluating a 3996 // variable's constructor are not usable while evaluating the 3997 // corresponding destructor, not even if they're of const-qualified 3998 // types. 3999 if (!(BaseType.isConstQualified() && 4000 BaseType->isIntegralOrEnumerationType()) && 4001 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4002 if (!IsAccess) 4003 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4004 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4005 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4006 return CompleteObject(); 4007 } 4008 4009 BaseVal = MTE->getOrCreateValue(false); 4010 assert(BaseVal && "got reference to unevaluated temporary"); 4011 } else { 4012 if (!IsAccess) 4013 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4014 APValue Val; 4015 LVal.moveInto(Val); 4016 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4017 << AK 4018 << Val.getAsString(Info.Ctx, 4019 Info.Ctx.getLValueReferenceType(LValType)); 4020 NoteLValueLocation(Info, LVal.Base); 4021 return CompleteObject(); 4022 } 4023 } else { 4024 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4025 assert(BaseVal && "missing value for temporary"); 4026 } 4027 } 4028 4029 // In C++14, we can't safely access any mutable state when we might be 4030 // evaluating after an unmodeled side effect. 4031 // 4032 // FIXME: Not all local state is mutable. Allow local constant subobjects 4033 // to be read here (but take care with 'mutable' fields). 4034 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4035 Info.EvalStatus.HasSideEffects) || 4036 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 4037 return CompleteObject(); 4038 4039 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4040 } 4041 4042 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4043 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4044 /// glvalue referred to by an entity of reference type. 4045 /// 4046 /// \param Info - Information about the ongoing evaluation. 4047 /// \param Conv - The expression for which we are performing the conversion. 4048 /// Used for diagnostics. 4049 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4050 /// case of a non-class type). 4051 /// \param LVal - The glvalue on which we are attempting to perform this action. 4052 /// \param RVal - The produced value will be placed here. 4053 /// \param WantObjectRepresentation - If true, we're looking for the object 4054 /// representation rather than the value, and in particular, 4055 /// there is no requirement that the result be fully initialized. 4056 static bool 4057 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4058 const LValue &LVal, APValue &RVal, 4059 bool WantObjectRepresentation = false) { 4060 if (LVal.Designator.Invalid) 4061 return false; 4062 4063 // Check for special cases where there is no existing APValue to look at. 4064 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4065 4066 AccessKinds AK = 4067 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4068 4069 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4070 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4071 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4072 // initializer until now for such expressions. Such an expression can't be 4073 // an ICE in C, so this only matters for fold. 4074 if (Type.isVolatileQualified()) { 4075 Info.FFDiag(Conv); 4076 return false; 4077 } 4078 APValue Lit; 4079 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4080 return false; 4081 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4082 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4083 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4084 // Special-case character extraction so we don't have to construct an 4085 // APValue for the whole string. 4086 assert(LVal.Designator.Entries.size() <= 1 && 4087 "Can only read characters from string literals"); 4088 if (LVal.Designator.Entries.empty()) { 4089 // Fail for now for LValue to RValue conversion of an array. 4090 // (This shouldn't show up in C/C++, but it could be triggered by a 4091 // weird EvaluateAsRValue call from a tool.) 4092 Info.FFDiag(Conv); 4093 return false; 4094 } 4095 if (LVal.Designator.isOnePastTheEnd()) { 4096 if (Info.getLangOpts().CPlusPlus11) 4097 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4098 else 4099 Info.FFDiag(Conv); 4100 return false; 4101 } 4102 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4103 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4104 return true; 4105 } 4106 } 4107 4108 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4109 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4110 } 4111 4112 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4113 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4114 QualType LValType, APValue &Val) { 4115 if (LVal.Designator.Invalid) 4116 return false; 4117 4118 if (!Info.getLangOpts().CPlusPlus14) { 4119 Info.FFDiag(E); 4120 return false; 4121 } 4122 4123 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4124 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4125 } 4126 4127 namespace { 4128 struct CompoundAssignSubobjectHandler { 4129 EvalInfo &Info; 4130 const CompoundAssignOperator *E; 4131 QualType PromotedLHSType; 4132 BinaryOperatorKind Opcode; 4133 const APValue &RHS; 4134 4135 static const AccessKinds AccessKind = AK_Assign; 4136 4137 typedef bool result_type; 4138 4139 bool checkConst(QualType QT) { 4140 // Assigning to a const object has undefined behavior. 4141 if (QT.isConstQualified()) { 4142 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4143 return false; 4144 } 4145 return true; 4146 } 4147 4148 bool failed() { return false; } 4149 bool found(APValue &Subobj, QualType SubobjType) { 4150 switch (Subobj.getKind()) { 4151 case APValue::Int: 4152 return found(Subobj.getInt(), SubobjType); 4153 case APValue::Float: 4154 return found(Subobj.getFloat(), SubobjType); 4155 case APValue::ComplexInt: 4156 case APValue::ComplexFloat: 4157 // FIXME: Implement complex compound assignment. 4158 Info.FFDiag(E); 4159 return false; 4160 case APValue::LValue: 4161 return foundPointer(Subobj, SubobjType); 4162 case APValue::Vector: 4163 return foundVector(Subobj, SubobjType); 4164 default: 4165 // FIXME: can this happen? 4166 Info.FFDiag(E); 4167 return false; 4168 } 4169 } 4170 4171 bool foundVector(APValue &Value, QualType SubobjType) { 4172 if (!checkConst(SubobjType)) 4173 return false; 4174 4175 if (!SubobjType->isVectorType()) { 4176 Info.FFDiag(E); 4177 return false; 4178 } 4179 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4180 } 4181 4182 bool found(APSInt &Value, QualType SubobjType) { 4183 if (!checkConst(SubobjType)) 4184 return false; 4185 4186 if (!SubobjType->isIntegerType()) { 4187 // We don't support compound assignment on integer-cast-to-pointer 4188 // values. 4189 Info.FFDiag(E); 4190 return false; 4191 } 4192 4193 if (RHS.isInt()) { 4194 APSInt LHS = 4195 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4196 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4197 return false; 4198 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4199 return true; 4200 } else if (RHS.isFloat()) { 4201 APFloat FValue(0.0); 4202 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4203 FValue) && 4204 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4205 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4206 Value); 4207 } 4208 4209 Info.FFDiag(E); 4210 return false; 4211 } 4212 bool found(APFloat &Value, QualType SubobjType) { 4213 return checkConst(SubobjType) && 4214 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4215 Value) && 4216 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4217 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4218 } 4219 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4220 if (!checkConst(SubobjType)) 4221 return false; 4222 4223 QualType PointeeType; 4224 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4225 PointeeType = PT->getPointeeType(); 4226 4227 if (PointeeType.isNull() || !RHS.isInt() || 4228 (Opcode != BO_Add && Opcode != BO_Sub)) { 4229 Info.FFDiag(E); 4230 return false; 4231 } 4232 4233 APSInt Offset = RHS.getInt(); 4234 if (Opcode == BO_Sub) 4235 negateAsSigned(Offset); 4236 4237 LValue LVal; 4238 LVal.setFrom(Info.Ctx, Subobj); 4239 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4240 return false; 4241 LVal.moveInto(Subobj); 4242 return true; 4243 } 4244 }; 4245 } // end anonymous namespace 4246 4247 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4248 4249 /// Perform a compound assignment of LVal <op>= RVal. 4250 static bool handleCompoundAssignment(EvalInfo &Info, 4251 const CompoundAssignOperator *E, 4252 const LValue &LVal, QualType LValType, 4253 QualType PromotedLValType, 4254 BinaryOperatorKind Opcode, 4255 const APValue &RVal) { 4256 if (LVal.Designator.Invalid) 4257 return false; 4258 4259 if (!Info.getLangOpts().CPlusPlus14) { 4260 Info.FFDiag(E); 4261 return false; 4262 } 4263 4264 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4265 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4266 RVal }; 4267 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4268 } 4269 4270 namespace { 4271 struct IncDecSubobjectHandler { 4272 EvalInfo &Info; 4273 const UnaryOperator *E; 4274 AccessKinds AccessKind; 4275 APValue *Old; 4276 4277 typedef bool result_type; 4278 4279 bool checkConst(QualType QT) { 4280 // Assigning to a const object has undefined behavior. 4281 if (QT.isConstQualified()) { 4282 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4283 return false; 4284 } 4285 return true; 4286 } 4287 4288 bool failed() { return false; } 4289 bool found(APValue &Subobj, QualType SubobjType) { 4290 // Stash the old value. Also clear Old, so we don't clobber it later 4291 // if we're post-incrementing a complex. 4292 if (Old) { 4293 *Old = Subobj; 4294 Old = nullptr; 4295 } 4296 4297 switch (Subobj.getKind()) { 4298 case APValue::Int: 4299 return found(Subobj.getInt(), SubobjType); 4300 case APValue::Float: 4301 return found(Subobj.getFloat(), SubobjType); 4302 case APValue::ComplexInt: 4303 return found(Subobj.getComplexIntReal(), 4304 SubobjType->castAs<ComplexType>()->getElementType() 4305 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4306 case APValue::ComplexFloat: 4307 return found(Subobj.getComplexFloatReal(), 4308 SubobjType->castAs<ComplexType>()->getElementType() 4309 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4310 case APValue::LValue: 4311 return foundPointer(Subobj, SubobjType); 4312 default: 4313 // FIXME: can this happen? 4314 Info.FFDiag(E); 4315 return false; 4316 } 4317 } 4318 bool found(APSInt &Value, QualType SubobjType) { 4319 if (!checkConst(SubobjType)) 4320 return false; 4321 4322 if (!SubobjType->isIntegerType()) { 4323 // We don't support increment / decrement on integer-cast-to-pointer 4324 // values. 4325 Info.FFDiag(E); 4326 return false; 4327 } 4328 4329 if (Old) *Old = APValue(Value); 4330 4331 // bool arithmetic promotes to int, and the conversion back to bool 4332 // doesn't reduce mod 2^n, so special-case it. 4333 if (SubobjType->isBooleanType()) { 4334 if (AccessKind == AK_Increment) 4335 Value = 1; 4336 else 4337 Value = !Value; 4338 return true; 4339 } 4340 4341 bool WasNegative = Value.isNegative(); 4342 if (AccessKind == AK_Increment) { 4343 ++Value; 4344 4345 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4346 APSInt ActualValue(Value, /*IsUnsigned*/true); 4347 return HandleOverflow(Info, E, ActualValue, SubobjType); 4348 } 4349 } else { 4350 --Value; 4351 4352 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4353 unsigned BitWidth = Value.getBitWidth(); 4354 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4355 ActualValue.setBit(BitWidth); 4356 return HandleOverflow(Info, E, ActualValue, SubobjType); 4357 } 4358 } 4359 return true; 4360 } 4361 bool found(APFloat &Value, QualType SubobjType) { 4362 if (!checkConst(SubobjType)) 4363 return false; 4364 4365 if (Old) *Old = APValue(Value); 4366 4367 APFloat One(Value.getSemantics(), 1); 4368 if (AccessKind == AK_Increment) 4369 Value.add(One, APFloat::rmNearestTiesToEven); 4370 else 4371 Value.subtract(One, APFloat::rmNearestTiesToEven); 4372 return true; 4373 } 4374 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4375 if (!checkConst(SubobjType)) 4376 return false; 4377 4378 QualType PointeeType; 4379 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4380 PointeeType = PT->getPointeeType(); 4381 else { 4382 Info.FFDiag(E); 4383 return false; 4384 } 4385 4386 LValue LVal; 4387 LVal.setFrom(Info.Ctx, Subobj); 4388 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4389 AccessKind == AK_Increment ? 1 : -1)) 4390 return false; 4391 LVal.moveInto(Subobj); 4392 return true; 4393 } 4394 }; 4395 } // end anonymous namespace 4396 4397 /// Perform an increment or decrement on LVal. 4398 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4399 QualType LValType, bool IsIncrement, APValue *Old) { 4400 if (LVal.Designator.Invalid) 4401 return false; 4402 4403 if (!Info.getLangOpts().CPlusPlus14) { 4404 Info.FFDiag(E); 4405 return false; 4406 } 4407 4408 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4409 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4410 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4411 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4412 } 4413 4414 /// Build an lvalue for the object argument of a member function call. 4415 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4416 LValue &This) { 4417 if (Object->getType()->isPointerType() && Object->isRValue()) 4418 return EvaluatePointer(Object, This, Info); 4419 4420 if (Object->isGLValue()) 4421 return EvaluateLValue(Object, This, Info); 4422 4423 if (Object->getType()->isLiteralType(Info.Ctx)) 4424 return EvaluateTemporary(Object, This, Info); 4425 4426 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4427 return false; 4428 } 4429 4430 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4431 /// lvalue referring to the result. 4432 /// 4433 /// \param Info - Information about the ongoing evaluation. 4434 /// \param LV - An lvalue referring to the base of the member pointer. 4435 /// \param RHS - The member pointer expression. 4436 /// \param IncludeMember - Specifies whether the member itself is included in 4437 /// the resulting LValue subobject designator. This is not possible when 4438 /// creating a bound member function. 4439 /// \return The field or method declaration to which the member pointer refers, 4440 /// or 0 if evaluation fails. 4441 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4442 QualType LVType, 4443 LValue &LV, 4444 const Expr *RHS, 4445 bool IncludeMember = true) { 4446 MemberPtr MemPtr; 4447 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4448 return nullptr; 4449 4450 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4451 // member value, the behavior is undefined. 4452 if (!MemPtr.getDecl()) { 4453 // FIXME: Specific diagnostic. 4454 Info.FFDiag(RHS); 4455 return nullptr; 4456 } 4457 4458 if (MemPtr.isDerivedMember()) { 4459 // This is a member of some derived class. Truncate LV appropriately. 4460 // The end of the derived-to-base path for the base object must match the 4461 // derived-to-base path for the member pointer. 4462 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4463 LV.Designator.Entries.size()) { 4464 Info.FFDiag(RHS); 4465 return nullptr; 4466 } 4467 unsigned PathLengthToMember = 4468 LV.Designator.Entries.size() - MemPtr.Path.size(); 4469 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4470 const CXXRecordDecl *LVDecl = getAsBaseClass( 4471 LV.Designator.Entries[PathLengthToMember + I]); 4472 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4473 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4474 Info.FFDiag(RHS); 4475 return nullptr; 4476 } 4477 } 4478 4479 // Truncate the lvalue to the appropriate derived class. 4480 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4481 PathLengthToMember)) 4482 return nullptr; 4483 } else if (!MemPtr.Path.empty()) { 4484 // Extend the LValue path with the member pointer's path. 4485 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4486 MemPtr.Path.size() + IncludeMember); 4487 4488 // Walk down to the appropriate base class. 4489 if (const PointerType *PT = LVType->getAs<PointerType>()) 4490 LVType = PT->getPointeeType(); 4491 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4492 assert(RD && "member pointer access on non-class-type expression"); 4493 // The first class in the path is that of the lvalue. 4494 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4495 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4496 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4497 return nullptr; 4498 RD = Base; 4499 } 4500 // Finally cast to the class containing the member. 4501 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4502 MemPtr.getContainingRecord())) 4503 return nullptr; 4504 } 4505 4506 // Add the member. Note that we cannot build bound member functions here. 4507 if (IncludeMember) { 4508 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4509 if (!HandleLValueMember(Info, RHS, LV, FD)) 4510 return nullptr; 4511 } else if (const IndirectFieldDecl *IFD = 4512 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4513 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4514 return nullptr; 4515 } else { 4516 llvm_unreachable("can't construct reference to bound member function"); 4517 } 4518 } 4519 4520 return MemPtr.getDecl(); 4521 } 4522 4523 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4524 const BinaryOperator *BO, 4525 LValue &LV, 4526 bool IncludeMember = true) { 4527 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4528 4529 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4530 if (Info.noteFailure()) { 4531 MemberPtr MemPtr; 4532 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4533 } 4534 return nullptr; 4535 } 4536 4537 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4538 BO->getRHS(), IncludeMember); 4539 } 4540 4541 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4542 /// the provided lvalue, which currently refers to the base object. 4543 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4544 LValue &Result) { 4545 SubobjectDesignator &D = Result.Designator; 4546 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4547 return false; 4548 4549 QualType TargetQT = E->getType(); 4550 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4551 TargetQT = PT->getPointeeType(); 4552 4553 // Check this cast lands within the final derived-to-base subobject path. 4554 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4555 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4556 << D.MostDerivedType << TargetQT; 4557 return false; 4558 } 4559 4560 // Check the type of the final cast. We don't need to check the path, 4561 // since a cast can only be formed if the path is unique. 4562 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4563 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4564 const CXXRecordDecl *FinalType; 4565 if (NewEntriesSize == D.MostDerivedPathLength) 4566 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4567 else 4568 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4569 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4570 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4571 << D.MostDerivedType << TargetQT; 4572 return false; 4573 } 4574 4575 // Truncate the lvalue to the appropriate derived class. 4576 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4577 } 4578 4579 /// Get the value to use for a default-initialized object of type T. 4580 /// Return false if it encounters something invalid. 4581 static bool getDefaultInitValue(QualType T, APValue &Result) { 4582 bool Success = true; 4583 if (auto *RD = T->getAsCXXRecordDecl()) { 4584 if (RD->isInvalidDecl()) { 4585 Result = APValue(); 4586 return false; 4587 } 4588 if (RD->isUnion()) { 4589 Result = APValue((const FieldDecl *)nullptr); 4590 return true; 4591 } 4592 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4593 std::distance(RD->field_begin(), RD->field_end())); 4594 4595 unsigned Index = 0; 4596 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4597 End = RD->bases_end(); 4598 I != End; ++I, ++Index) 4599 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4600 4601 for (const auto *I : RD->fields()) { 4602 if (I->isUnnamedBitfield()) 4603 continue; 4604 Success &= getDefaultInitValue(I->getType(), 4605 Result.getStructField(I->getFieldIndex())); 4606 } 4607 return Success; 4608 } 4609 4610 if (auto *AT = 4611 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4612 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4613 if (Result.hasArrayFiller()) 4614 Success &= 4615 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4616 4617 return Success; 4618 } 4619 4620 Result = APValue::IndeterminateValue(); 4621 return true; 4622 } 4623 4624 namespace { 4625 enum EvalStmtResult { 4626 /// Evaluation failed. 4627 ESR_Failed, 4628 /// Hit a 'return' statement. 4629 ESR_Returned, 4630 /// Evaluation succeeded. 4631 ESR_Succeeded, 4632 /// Hit a 'continue' statement. 4633 ESR_Continue, 4634 /// Hit a 'break' statement. 4635 ESR_Break, 4636 /// Still scanning for 'case' or 'default' statement. 4637 ESR_CaseNotFound 4638 }; 4639 } 4640 4641 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4642 // We don't need to evaluate the initializer for a static local. 4643 if (!VD->hasLocalStorage()) 4644 return true; 4645 4646 LValue Result; 4647 APValue &Val = 4648 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4649 4650 const Expr *InitE = VD->getInit(); 4651 if (!InitE) 4652 return getDefaultInitValue(VD->getType(), Val); 4653 4654 if (InitE->isValueDependent()) 4655 return false; 4656 4657 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4658 // Wipe out any partially-computed value, to allow tracking that this 4659 // evaluation failed. 4660 Val = APValue(); 4661 return false; 4662 } 4663 4664 return true; 4665 } 4666 4667 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4668 bool OK = true; 4669 4670 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4671 OK &= EvaluateVarDecl(Info, VD); 4672 4673 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4674 for (auto *BD : DD->bindings()) 4675 if (auto *VD = BD->getHoldingVar()) 4676 OK &= EvaluateDecl(Info, VD); 4677 4678 return OK; 4679 } 4680 4681 4682 /// Evaluate a condition (either a variable declaration or an expression). 4683 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4684 const Expr *Cond, bool &Result) { 4685 FullExpressionRAII Scope(Info); 4686 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4687 return false; 4688 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4689 return false; 4690 return Scope.destroy(); 4691 } 4692 4693 namespace { 4694 /// A location where the result (returned value) of evaluating a 4695 /// statement should be stored. 4696 struct StmtResult { 4697 /// The APValue that should be filled in with the returned value. 4698 APValue &Value; 4699 /// The location containing the result, if any (used to support RVO). 4700 const LValue *Slot; 4701 }; 4702 4703 struct TempVersionRAII { 4704 CallStackFrame &Frame; 4705 4706 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4707 Frame.pushTempVersion(); 4708 } 4709 4710 ~TempVersionRAII() { 4711 Frame.popTempVersion(); 4712 } 4713 }; 4714 4715 } 4716 4717 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4718 const Stmt *S, 4719 const SwitchCase *SC = nullptr); 4720 4721 /// Evaluate the body of a loop, and translate the result as appropriate. 4722 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4723 const Stmt *Body, 4724 const SwitchCase *Case = nullptr) { 4725 BlockScopeRAII Scope(Info); 4726 4727 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4728 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4729 ESR = ESR_Failed; 4730 4731 switch (ESR) { 4732 case ESR_Break: 4733 return ESR_Succeeded; 4734 case ESR_Succeeded: 4735 case ESR_Continue: 4736 return ESR_Continue; 4737 case ESR_Failed: 4738 case ESR_Returned: 4739 case ESR_CaseNotFound: 4740 return ESR; 4741 } 4742 llvm_unreachable("Invalid EvalStmtResult!"); 4743 } 4744 4745 /// Evaluate a switch statement. 4746 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4747 const SwitchStmt *SS) { 4748 BlockScopeRAII Scope(Info); 4749 4750 // Evaluate the switch condition. 4751 APSInt Value; 4752 { 4753 if (const Stmt *Init = SS->getInit()) { 4754 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4755 if (ESR != ESR_Succeeded) { 4756 if (ESR != ESR_Failed && !Scope.destroy()) 4757 ESR = ESR_Failed; 4758 return ESR; 4759 } 4760 } 4761 4762 FullExpressionRAII CondScope(Info); 4763 if (SS->getConditionVariable() && 4764 !EvaluateDecl(Info, SS->getConditionVariable())) 4765 return ESR_Failed; 4766 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4767 return ESR_Failed; 4768 if (!CondScope.destroy()) 4769 return ESR_Failed; 4770 } 4771 4772 // Find the switch case corresponding to the value of the condition. 4773 // FIXME: Cache this lookup. 4774 const SwitchCase *Found = nullptr; 4775 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4776 SC = SC->getNextSwitchCase()) { 4777 if (isa<DefaultStmt>(SC)) { 4778 Found = SC; 4779 continue; 4780 } 4781 4782 const CaseStmt *CS = cast<CaseStmt>(SC); 4783 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4784 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4785 : LHS; 4786 if (LHS <= Value && Value <= RHS) { 4787 Found = SC; 4788 break; 4789 } 4790 } 4791 4792 if (!Found) 4793 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4794 4795 // Search the switch body for the switch case and evaluate it from there. 4796 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4797 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4798 return ESR_Failed; 4799 4800 switch (ESR) { 4801 case ESR_Break: 4802 return ESR_Succeeded; 4803 case ESR_Succeeded: 4804 case ESR_Continue: 4805 case ESR_Failed: 4806 case ESR_Returned: 4807 return ESR; 4808 case ESR_CaseNotFound: 4809 // This can only happen if the switch case is nested within a statement 4810 // expression. We have no intention of supporting that. 4811 Info.FFDiag(Found->getBeginLoc(), 4812 diag::note_constexpr_stmt_expr_unsupported); 4813 return ESR_Failed; 4814 } 4815 llvm_unreachable("Invalid EvalStmtResult!"); 4816 } 4817 4818 // Evaluate a statement. 4819 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4820 const Stmt *S, const SwitchCase *Case) { 4821 if (!Info.nextStep(S)) 4822 return ESR_Failed; 4823 4824 // If we're hunting down a 'case' or 'default' label, recurse through 4825 // substatements until we hit the label. 4826 if (Case) { 4827 switch (S->getStmtClass()) { 4828 case Stmt::CompoundStmtClass: 4829 // FIXME: Precompute which substatement of a compound statement we 4830 // would jump to, and go straight there rather than performing a 4831 // linear scan each time. 4832 case Stmt::LabelStmtClass: 4833 case Stmt::AttributedStmtClass: 4834 case Stmt::DoStmtClass: 4835 break; 4836 4837 case Stmt::CaseStmtClass: 4838 case Stmt::DefaultStmtClass: 4839 if (Case == S) 4840 Case = nullptr; 4841 break; 4842 4843 case Stmt::IfStmtClass: { 4844 // FIXME: Precompute which side of an 'if' we would jump to, and go 4845 // straight there rather than scanning both sides. 4846 const IfStmt *IS = cast<IfStmt>(S); 4847 4848 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4849 // preceded by our switch label. 4850 BlockScopeRAII Scope(Info); 4851 4852 // Step into the init statement in case it brings an (uninitialized) 4853 // variable into scope. 4854 if (const Stmt *Init = IS->getInit()) { 4855 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4856 if (ESR != ESR_CaseNotFound) { 4857 assert(ESR != ESR_Succeeded); 4858 return ESR; 4859 } 4860 } 4861 4862 // Condition variable must be initialized if it exists. 4863 // FIXME: We can skip evaluating the body if there's a condition 4864 // variable, as there can't be any case labels within it. 4865 // (The same is true for 'for' statements.) 4866 4867 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4868 if (ESR == ESR_Failed) 4869 return ESR; 4870 if (ESR != ESR_CaseNotFound) 4871 return Scope.destroy() ? ESR : ESR_Failed; 4872 if (!IS->getElse()) 4873 return ESR_CaseNotFound; 4874 4875 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4876 if (ESR == ESR_Failed) 4877 return ESR; 4878 if (ESR != ESR_CaseNotFound) 4879 return Scope.destroy() ? ESR : ESR_Failed; 4880 return ESR_CaseNotFound; 4881 } 4882 4883 case Stmt::WhileStmtClass: { 4884 EvalStmtResult ESR = 4885 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4886 if (ESR != ESR_Continue) 4887 return ESR; 4888 break; 4889 } 4890 4891 case Stmt::ForStmtClass: { 4892 const ForStmt *FS = cast<ForStmt>(S); 4893 BlockScopeRAII Scope(Info); 4894 4895 // Step into the init statement in case it brings an (uninitialized) 4896 // variable into scope. 4897 if (const Stmt *Init = FS->getInit()) { 4898 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4899 if (ESR != ESR_CaseNotFound) { 4900 assert(ESR != ESR_Succeeded); 4901 return ESR; 4902 } 4903 } 4904 4905 EvalStmtResult ESR = 4906 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4907 if (ESR != ESR_Continue) 4908 return ESR; 4909 if (FS->getInc()) { 4910 FullExpressionRAII IncScope(Info); 4911 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4912 return ESR_Failed; 4913 } 4914 break; 4915 } 4916 4917 case Stmt::DeclStmtClass: { 4918 // Start the lifetime of any uninitialized variables we encounter. They 4919 // might be used by the selected branch of the switch. 4920 const DeclStmt *DS = cast<DeclStmt>(S); 4921 for (const auto *D : DS->decls()) { 4922 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4923 if (VD->hasLocalStorage() && !VD->getInit()) 4924 if (!EvaluateVarDecl(Info, VD)) 4925 return ESR_Failed; 4926 // FIXME: If the variable has initialization that can't be jumped 4927 // over, bail out of any immediately-surrounding compound-statement 4928 // too. There can't be any case labels here. 4929 } 4930 } 4931 return ESR_CaseNotFound; 4932 } 4933 4934 default: 4935 return ESR_CaseNotFound; 4936 } 4937 } 4938 4939 switch (S->getStmtClass()) { 4940 default: 4941 if (const Expr *E = dyn_cast<Expr>(S)) { 4942 // Don't bother evaluating beyond an expression-statement which couldn't 4943 // be evaluated. 4944 // FIXME: Do we need the FullExpressionRAII object here? 4945 // VisitExprWithCleanups should create one when necessary. 4946 FullExpressionRAII Scope(Info); 4947 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4948 return ESR_Failed; 4949 return ESR_Succeeded; 4950 } 4951 4952 Info.FFDiag(S->getBeginLoc()); 4953 return ESR_Failed; 4954 4955 case Stmt::NullStmtClass: 4956 return ESR_Succeeded; 4957 4958 case Stmt::DeclStmtClass: { 4959 const DeclStmt *DS = cast<DeclStmt>(S); 4960 for (const auto *D : DS->decls()) { 4961 // Each declaration initialization is its own full-expression. 4962 FullExpressionRAII Scope(Info); 4963 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4964 return ESR_Failed; 4965 if (!Scope.destroy()) 4966 return ESR_Failed; 4967 } 4968 return ESR_Succeeded; 4969 } 4970 4971 case Stmt::ReturnStmtClass: { 4972 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4973 FullExpressionRAII Scope(Info); 4974 if (RetExpr && 4975 !(Result.Slot 4976 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4977 : Evaluate(Result.Value, Info, RetExpr))) 4978 return ESR_Failed; 4979 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4980 } 4981 4982 case Stmt::CompoundStmtClass: { 4983 BlockScopeRAII Scope(Info); 4984 4985 const CompoundStmt *CS = cast<CompoundStmt>(S); 4986 for (const auto *BI : CS->body()) { 4987 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4988 if (ESR == ESR_Succeeded) 4989 Case = nullptr; 4990 else if (ESR != ESR_CaseNotFound) { 4991 if (ESR != ESR_Failed && !Scope.destroy()) 4992 return ESR_Failed; 4993 return ESR; 4994 } 4995 } 4996 if (Case) 4997 return ESR_CaseNotFound; 4998 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4999 } 5000 5001 case Stmt::IfStmtClass: { 5002 const IfStmt *IS = cast<IfStmt>(S); 5003 5004 // Evaluate the condition, as either a var decl or as an expression. 5005 BlockScopeRAII Scope(Info); 5006 if (const Stmt *Init = IS->getInit()) { 5007 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5008 if (ESR != ESR_Succeeded) { 5009 if (ESR != ESR_Failed && !Scope.destroy()) 5010 return ESR_Failed; 5011 return ESR; 5012 } 5013 } 5014 bool Cond; 5015 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5016 return ESR_Failed; 5017 5018 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5019 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5020 if (ESR != ESR_Succeeded) { 5021 if (ESR != ESR_Failed && !Scope.destroy()) 5022 return ESR_Failed; 5023 return ESR; 5024 } 5025 } 5026 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5027 } 5028 5029 case Stmt::WhileStmtClass: { 5030 const WhileStmt *WS = cast<WhileStmt>(S); 5031 while (true) { 5032 BlockScopeRAII Scope(Info); 5033 bool Continue; 5034 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5035 Continue)) 5036 return ESR_Failed; 5037 if (!Continue) 5038 break; 5039 5040 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5041 if (ESR != ESR_Continue) { 5042 if (ESR != ESR_Failed && !Scope.destroy()) 5043 return ESR_Failed; 5044 return ESR; 5045 } 5046 if (!Scope.destroy()) 5047 return ESR_Failed; 5048 } 5049 return ESR_Succeeded; 5050 } 5051 5052 case Stmt::DoStmtClass: { 5053 const DoStmt *DS = cast<DoStmt>(S); 5054 bool Continue; 5055 do { 5056 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5057 if (ESR != ESR_Continue) 5058 return ESR; 5059 Case = nullptr; 5060 5061 FullExpressionRAII CondScope(Info); 5062 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5063 !CondScope.destroy()) 5064 return ESR_Failed; 5065 } while (Continue); 5066 return ESR_Succeeded; 5067 } 5068 5069 case Stmt::ForStmtClass: { 5070 const ForStmt *FS = cast<ForStmt>(S); 5071 BlockScopeRAII ForScope(Info); 5072 if (FS->getInit()) { 5073 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5074 if (ESR != ESR_Succeeded) { 5075 if (ESR != ESR_Failed && !ForScope.destroy()) 5076 return ESR_Failed; 5077 return ESR; 5078 } 5079 } 5080 while (true) { 5081 BlockScopeRAII IterScope(Info); 5082 bool Continue = true; 5083 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5084 FS->getCond(), Continue)) 5085 return ESR_Failed; 5086 if (!Continue) 5087 break; 5088 5089 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5090 if (ESR != ESR_Continue) { 5091 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5092 return ESR_Failed; 5093 return ESR; 5094 } 5095 5096 if (FS->getInc()) { 5097 FullExpressionRAII IncScope(Info); 5098 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5099 return ESR_Failed; 5100 } 5101 5102 if (!IterScope.destroy()) 5103 return ESR_Failed; 5104 } 5105 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5106 } 5107 5108 case Stmt::CXXForRangeStmtClass: { 5109 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5110 BlockScopeRAII Scope(Info); 5111 5112 // Evaluate the init-statement if present. 5113 if (FS->getInit()) { 5114 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5115 if (ESR != ESR_Succeeded) { 5116 if (ESR != ESR_Failed && !Scope.destroy()) 5117 return ESR_Failed; 5118 return ESR; 5119 } 5120 } 5121 5122 // Initialize the __range variable. 5123 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5124 if (ESR != ESR_Succeeded) { 5125 if (ESR != ESR_Failed && !Scope.destroy()) 5126 return ESR_Failed; 5127 return ESR; 5128 } 5129 5130 // Create the __begin and __end iterators. 5131 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5132 if (ESR != ESR_Succeeded) { 5133 if (ESR != ESR_Failed && !Scope.destroy()) 5134 return ESR_Failed; 5135 return ESR; 5136 } 5137 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5138 if (ESR != ESR_Succeeded) { 5139 if (ESR != ESR_Failed && !Scope.destroy()) 5140 return ESR_Failed; 5141 return ESR; 5142 } 5143 5144 while (true) { 5145 // Condition: __begin != __end. 5146 { 5147 bool Continue = true; 5148 FullExpressionRAII CondExpr(Info); 5149 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5150 return ESR_Failed; 5151 if (!Continue) 5152 break; 5153 } 5154 5155 // User's variable declaration, initialized by *__begin. 5156 BlockScopeRAII InnerScope(Info); 5157 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5158 if (ESR != ESR_Succeeded) { 5159 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5160 return ESR_Failed; 5161 return ESR; 5162 } 5163 5164 // Loop body. 5165 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5166 if (ESR != ESR_Continue) { 5167 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5168 return ESR_Failed; 5169 return ESR; 5170 } 5171 5172 // Increment: ++__begin 5173 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5174 return ESR_Failed; 5175 5176 if (!InnerScope.destroy()) 5177 return ESR_Failed; 5178 } 5179 5180 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5181 } 5182 5183 case Stmt::SwitchStmtClass: 5184 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5185 5186 case Stmt::ContinueStmtClass: 5187 return ESR_Continue; 5188 5189 case Stmt::BreakStmtClass: 5190 return ESR_Break; 5191 5192 case Stmt::LabelStmtClass: 5193 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5194 5195 case Stmt::AttributedStmtClass: 5196 // As a general principle, C++11 attributes can be ignored without 5197 // any semantic impact. 5198 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5199 Case); 5200 5201 case Stmt::CaseStmtClass: 5202 case Stmt::DefaultStmtClass: 5203 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5204 case Stmt::CXXTryStmtClass: 5205 // Evaluate try blocks by evaluating all sub statements. 5206 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5207 } 5208 } 5209 5210 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5211 /// default constructor. If so, we'll fold it whether or not it's marked as 5212 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5213 /// so we need special handling. 5214 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5215 const CXXConstructorDecl *CD, 5216 bool IsValueInitialization) { 5217 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5218 return false; 5219 5220 // Value-initialization does not call a trivial default constructor, so such a 5221 // call is a core constant expression whether or not the constructor is 5222 // constexpr. 5223 if (!CD->isConstexpr() && !IsValueInitialization) { 5224 if (Info.getLangOpts().CPlusPlus11) { 5225 // FIXME: If DiagDecl is an implicitly-declared special member function, 5226 // we should be much more explicit about why it's not constexpr. 5227 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5228 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5229 Info.Note(CD->getLocation(), diag::note_declared_at); 5230 } else { 5231 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5232 } 5233 } 5234 return true; 5235 } 5236 5237 /// CheckConstexprFunction - Check that a function can be called in a constant 5238 /// expression. 5239 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5240 const FunctionDecl *Declaration, 5241 const FunctionDecl *Definition, 5242 const Stmt *Body) { 5243 // Potential constant expressions can contain calls to declared, but not yet 5244 // defined, constexpr functions. 5245 if (Info.checkingPotentialConstantExpression() && !Definition && 5246 Declaration->isConstexpr()) 5247 return false; 5248 5249 // Bail out if the function declaration itself is invalid. We will 5250 // have produced a relevant diagnostic while parsing it, so just 5251 // note the problematic sub-expression. 5252 if (Declaration->isInvalidDecl()) { 5253 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5254 return false; 5255 } 5256 5257 // DR1872: An instantiated virtual constexpr function can't be called in a 5258 // constant expression (prior to C++20). We can still constant-fold such a 5259 // call. 5260 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5261 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5262 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5263 5264 if (Definition && Definition->isInvalidDecl()) { 5265 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5266 return false; 5267 } 5268 5269 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5270 for (const auto *InitExpr : CtorDecl->inits()) { 5271 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5272 return false; 5273 } 5274 } 5275 5276 // Can we evaluate this function call? 5277 if (Definition && Definition->isConstexpr() && Body) 5278 return true; 5279 5280 if (Info.getLangOpts().CPlusPlus11) { 5281 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5282 5283 // If this function is not constexpr because it is an inherited 5284 // non-constexpr constructor, diagnose that directly. 5285 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5286 if (CD && CD->isInheritingConstructor()) { 5287 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5288 if (!Inherited->isConstexpr()) 5289 DiagDecl = CD = Inherited; 5290 } 5291 5292 // FIXME: If DiagDecl is an implicitly-declared special member function 5293 // or an inheriting constructor, we should be much more explicit about why 5294 // it's not constexpr. 5295 if (CD && CD->isInheritingConstructor()) 5296 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5297 << CD->getInheritedConstructor().getConstructor()->getParent(); 5298 else 5299 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5300 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5301 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5302 } else { 5303 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5304 } 5305 return false; 5306 } 5307 5308 namespace { 5309 struct CheckDynamicTypeHandler { 5310 AccessKinds AccessKind; 5311 typedef bool result_type; 5312 bool failed() { return false; } 5313 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5314 bool found(APSInt &Value, QualType SubobjType) { return true; } 5315 bool found(APFloat &Value, QualType SubobjType) { return true; } 5316 }; 5317 } // end anonymous namespace 5318 5319 /// Check that we can access the notional vptr of an object / determine its 5320 /// dynamic type. 5321 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5322 AccessKinds AK, bool Polymorphic) { 5323 if (This.Designator.Invalid) 5324 return false; 5325 5326 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5327 5328 if (!Obj) 5329 return false; 5330 5331 if (!Obj.Value) { 5332 // The object is not usable in constant expressions, so we can't inspect 5333 // its value to see if it's in-lifetime or what the active union members 5334 // are. We can still check for a one-past-the-end lvalue. 5335 if (This.Designator.isOnePastTheEnd() || 5336 This.Designator.isMostDerivedAnUnsizedArray()) { 5337 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5338 ? diag::note_constexpr_access_past_end 5339 : diag::note_constexpr_access_unsized_array) 5340 << AK; 5341 return false; 5342 } else if (Polymorphic) { 5343 // Conservatively refuse to perform a polymorphic operation if we would 5344 // not be able to read a notional 'vptr' value. 5345 APValue Val; 5346 This.moveInto(Val); 5347 QualType StarThisType = 5348 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5349 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5350 << AK << Val.getAsString(Info.Ctx, StarThisType); 5351 return false; 5352 } 5353 return true; 5354 } 5355 5356 CheckDynamicTypeHandler Handler{AK}; 5357 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5358 } 5359 5360 /// Check that the pointee of the 'this' pointer in a member function call is 5361 /// either within its lifetime or in its period of construction or destruction. 5362 static bool 5363 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5364 const LValue &This, 5365 const CXXMethodDecl *NamedMember) { 5366 return checkDynamicType( 5367 Info, E, This, 5368 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5369 } 5370 5371 struct DynamicType { 5372 /// The dynamic class type of the object. 5373 const CXXRecordDecl *Type; 5374 /// The corresponding path length in the lvalue. 5375 unsigned PathLength; 5376 }; 5377 5378 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5379 unsigned PathLength) { 5380 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5381 Designator.Entries.size() && "invalid path length"); 5382 return (PathLength == Designator.MostDerivedPathLength) 5383 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5384 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5385 } 5386 5387 /// Determine the dynamic type of an object. 5388 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5389 LValue &This, AccessKinds AK) { 5390 // If we don't have an lvalue denoting an object of class type, there is no 5391 // meaningful dynamic type. (We consider objects of non-class type to have no 5392 // dynamic type.) 5393 if (!checkDynamicType(Info, E, This, AK, true)) 5394 return None; 5395 5396 // Refuse to compute a dynamic type in the presence of virtual bases. This 5397 // shouldn't happen other than in constant-folding situations, since literal 5398 // types can't have virtual bases. 5399 // 5400 // Note that consumers of DynamicType assume that the type has no virtual 5401 // bases, and will need modifications if this restriction is relaxed. 5402 const CXXRecordDecl *Class = 5403 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5404 if (!Class || Class->getNumVBases()) { 5405 Info.FFDiag(E); 5406 return None; 5407 } 5408 5409 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5410 // binary search here instead. But the overwhelmingly common case is that 5411 // we're not in the middle of a constructor, so it probably doesn't matter 5412 // in practice. 5413 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5414 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5415 PathLength <= Path.size(); ++PathLength) { 5416 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5417 Path.slice(0, PathLength))) { 5418 case ConstructionPhase::Bases: 5419 case ConstructionPhase::DestroyingBases: 5420 // We're constructing or destroying a base class. This is not the dynamic 5421 // type. 5422 break; 5423 5424 case ConstructionPhase::None: 5425 case ConstructionPhase::AfterBases: 5426 case ConstructionPhase::AfterFields: 5427 case ConstructionPhase::Destroying: 5428 // We've finished constructing the base classes and not yet started 5429 // destroying them again, so this is the dynamic type. 5430 return DynamicType{getBaseClassType(This.Designator, PathLength), 5431 PathLength}; 5432 } 5433 } 5434 5435 // CWG issue 1517: we're constructing a base class of the object described by 5436 // 'This', so that object has not yet begun its period of construction and 5437 // any polymorphic operation on it results in undefined behavior. 5438 Info.FFDiag(E); 5439 return None; 5440 } 5441 5442 /// Perform virtual dispatch. 5443 static const CXXMethodDecl *HandleVirtualDispatch( 5444 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5445 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5446 Optional<DynamicType> DynType = ComputeDynamicType( 5447 Info, E, This, 5448 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5449 if (!DynType) 5450 return nullptr; 5451 5452 // Find the final overrider. It must be declared in one of the classes on the 5453 // path from the dynamic type to the static type. 5454 // FIXME: If we ever allow literal types to have virtual base classes, that 5455 // won't be true. 5456 const CXXMethodDecl *Callee = Found; 5457 unsigned PathLength = DynType->PathLength; 5458 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5459 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5460 const CXXMethodDecl *Overrider = 5461 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5462 if (Overrider) { 5463 Callee = Overrider; 5464 break; 5465 } 5466 } 5467 5468 // C++2a [class.abstract]p6: 5469 // the effect of making a virtual call to a pure virtual function [...] is 5470 // undefined 5471 if (Callee->isPure()) { 5472 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5473 Info.Note(Callee->getLocation(), diag::note_declared_at); 5474 return nullptr; 5475 } 5476 5477 // If necessary, walk the rest of the path to determine the sequence of 5478 // covariant adjustment steps to apply. 5479 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5480 Found->getReturnType())) { 5481 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5482 for (unsigned CovariantPathLength = PathLength + 1; 5483 CovariantPathLength != This.Designator.Entries.size(); 5484 ++CovariantPathLength) { 5485 const CXXRecordDecl *NextClass = 5486 getBaseClassType(This.Designator, CovariantPathLength); 5487 const CXXMethodDecl *Next = 5488 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5489 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5490 Next->getReturnType(), CovariantAdjustmentPath.back())) 5491 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5492 } 5493 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5494 CovariantAdjustmentPath.back())) 5495 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5496 } 5497 5498 // Perform 'this' adjustment. 5499 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5500 return nullptr; 5501 5502 return Callee; 5503 } 5504 5505 /// Perform the adjustment from a value returned by a virtual function to 5506 /// a value of the statically expected type, which may be a pointer or 5507 /// reference to a base class of the returned type. 5508 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5509 APValue &Result, 5510 ArrayRef<QualType> Path) { 5511 assert(Result.isLValue() && 5512 "unexpected kind of APValue for covariant return"); 5513 if (Result.isNullPointer()) 5514 return true; 5515 5516 LValue LVal; 5517 LVal.setFrom(Info.Ctx, Result); 5518 5519 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5520 for (unsigned I = 1; I != Path.size(); ++I) { 5521 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5522 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5523 if (OldClass != NewClass && 5524 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5525 return false; 5526 OldClass = NewClass; 5527 } 5528 5529 LVal.moveInto(Result); 5530 return true; 5531 } 5532 5533 /// Determine whether \p Base, which is known to be a direct base class of 5534 /// \p Derived, is a public base class. 5535 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5536 const CXXRecordDecl *Base) { 5537 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5538 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5539 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5540 return BaseSpec.getAccessSpecifier() == AS_public; 5541 } 5542 llvm_unreachable("Base is not a direct base of Derived"); 5543 } 5544 5545 /// Apply the given dynamic cast operation on the provided lvalue. 5546 /// 5547 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5548 /// to find a suitable target subobject. 5549 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5550 LValue &Ptr) { 5551 // We can't do anything with a non-symbolic pointer value. 5552 SubobjectDesignator &D = Ptr.Designator; 5553 if (D.Invalid) 5554 return false; 5555 5556 // C++ [expr.dynamic.cast]p6: 5557 // If v is a null pointer value, the result is a null pointer value. 5558 if (Ptr.isNullPointer() && !E->isGLValue()) 5559 return true; 5560 5561 // For all the other cases, we need the pointer to point to an object within 5562 // its lifetime / period of construction / destruction, and we need to know 5563 // its dynamic type. 5564 Optional<DynamicType> DynType = 5565 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5566 if (!DynType) 5567 return false; 5568 5569 // C++ [expr.dynamic.cast]p7: 5570 // If T is "pointer to cv void", then the result is a pointer to the most 5571 // derived object 5572 if (E->getType()->isVoidPointerType()) 5573 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5574 5575 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5576 assert(C && "dynamic_cast target is not void pointer nor class"); 5577 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5578 5579 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5580 // C++ [expr.dynamic.cast]p9: 5581 if (!E->isGLValue()) { 5582 // The value of a failed cast to pointer type is the null pointer value 5583 // of the required result type. 5584 Ptr.setNull(Info.Ctx, E->getType()); 5585 return true; 5586 } 5587 5588 // A failed cast to reference type throws [...] std::bad_cast. 5589 unsigned DiagKind; 5590 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5591 DynType->Type->isDerivedFrom(C))) 5592 DiagKind = 0; 5593 else if (!Paths || Paths->begin() == Paths->end()) 5594 DiagKind = 1; 5595 else if (Paths->isAmbiguous(CQT)) 5596 DiagKind = 2; 5597 else { 5598 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5599 DiagKind = 3; 5600 } 5601 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5602 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5603 << Info.Ctx.getRecordType(DynType->Type) 5604 << E->getType().getUnqualifiedType(); 5605 return false; 5606 }; 5607 5608 // Runtime check, phase 1: 5609 // Walk from the base subobject towards the derived object looking for the 5610 // target type. 5611 for (int PathLength = Ptr.Designator.Entries.size(); 5612 PathLength >= (int)DynType->PathLength; --PathLength) { 5613 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5614 if (declaresSameEntity(Class, C)) 5615 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5616 // We can only walk across public inheritance edges. 5617 if (PathLength > (int)DynType->PathLength && 5618 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5619 Class)) 5620 return RuntimeCheckFailed(nullptr); 5621 } 5622 5623 // Runtime check, phase 2: 5624 // Search the dynamic type for an unambiguous public base of type C. 5625 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5626 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5627 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5628 Paths.front().Access == AS_public) { 5629 // Downcast to the dynamic type... 5630 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5631 return false; 5632 // ... then upcast to the chosen base class subobject. 5633 for (CXXBasePathElement &Elem : Paths.front()) 5634 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5635 return false; 5636 return true; 5637 } 5638 5639 // Otherwise, the runtime check fails. 5640 return RuntimeCheckFailed(&Paths); 5641 } 5642 5643 namespace { 5644 struct StartLifetimeOfUnionMemberHandler { 5645 EvalInfo &Info; 5646 const Expr *LHSExpr; 5647 const FieldDecl *Field; 5648 bool DuringInit; 5649 bool Failed = false; 5650 static const AccessKinds AccessKind = AK_Assign; 5651 5652 typedef bool result_type; 5653 bool failed() { return Failed; } 5654 bool found(APValue &Subobj, QualType SubobjType) { 5655 // We are supposed to perform no initialization but begin the lifetime of 5656 // the object. We interpret that as meaning to do what default 5657 // initialization of the object would do if all constructors involved were 5658 // trivial: 5659 // * All base, non-variant member, and array element subobjects' lifetimes 5660 // begin 5661 // * No variant members' lifetimes begin 5662 // * All scalar subobjects whose lifetimes begin have indeterminate values 5663 assert(SubobjType->isUnionType()); 5664 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5665 // This union member is already active. If it's also in-lifetime, there's 5666 // nothing to do. 5667 if (Subobj.getUnionValue().hasValue()) 5668 return true; 5669 } else if (DuringInit) { 5670 // We're currently in the process of initializing a different union 5671 // member. If we carried on, that initialization would attempt to 5672 // store to an inactive union member, resulting in undefined behavior. 5673 Info.FFDiag(LHSExpr, 5674 diag::note_constexpr_union_member_change_during_init); 5675 return false; 5676 } 5677 APValue Result; 5678 Failed = !getDefaultInitValue(Field->getType(), Result); 5679 Subobj.setUnion(Field, Result); 5680 return true; 5681 } 5682 bool found(APSInt &Value, QualType SubobjType) { 5683 llvm_unreachable("wrong value kind for union object"); 5684 } 5685 bool found(APFloat &Value, QualType SubobjType) { 5686 llvm_unreachable("wrong value kind for union object"); 5687 } 5688 }; 5689 } // end anonymous namespace 5690 5691 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5692 5693 /// Handle a builtin simple-assignment or a call to a trivial assignment 5694 /// operator whose left-hand side might involve a union member access. If it 5695 /// does, implicitly start the lifetime of any accessed union elements per 5696 /// C++20 [class.union]5. 5697 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5698 const LValue &LHS) { 5699 if (LHS.InvalidBase || LHS.Designator.Invalid) 5700 return false; 5701 5702 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5703 // C++ [class.union]p5: 5704 // define the set S(E) of subexpressions of E as follows: 5705 unsigned PathLength = LHS.Designator.Entries.size(); 5706 for (const Expr *E = LHSExpr; E != nullptr;) { 5707 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5708 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5709 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5710 // Note that we can't implicitly start the lifetime of a reference, 5711 // so we don't need to proceed any further if we reach one. 5712 if (!FD || FD->getType()->isReferenceType()) 5713 break; 5714 5715 // ... and also contains A.B if B names a union member ... 5716 if (FD->getParent()->isUnion()) { 5717 // ... of a non-class, non-array type, or of a class type with a 5718 // trivial default constructor that is not deleted, or an array of 5719 // such types. 5720 auto *RD = 5721 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5722 if (!RD || RD->hasTrivialDefaultConstructor()) 5723 UnionPathLengths.push_back({PathLength - 1, FD}); 5724 } 5725 5726 E = ME->getBase(); 5727 --PathLength; 5728 assert(declaresSameEntity(FD, 5729 LHS.Designator.Entries[PathLength] 5730 .getAsBaseOrMember().getPointer())); 5731 5732 // -- If E is of the form A[B] and is interpreted as a built-in array 5733 // subscripting operator, S(E) is [S(the array operand, if any)]. 5734 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5735 // Step over an ArrayToPointerDecay implicit cast. 5736 auto *Base = ASE->getBase()->IgnoreImplicit(); 5737 if (!Base->getType()->isArrayType()) 5738 break; 5739 5740 E = Base; 5741 --PathLength; 5742 5743 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5744 // Step over a derived-to-base conversion. 5745 E = ICE->getSubExpr(); 5746 if (ICE->getCastKind() == CK_NoOp) 5747 continue; 5748 if (ICE->getCastKind() != CK_DerivedToBase && 5749 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5750 break; 5751 // Walk path backwards as we walk up from the base to the derived class. 5752 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5753 --PathLength; 5754 (void)Elt; 5755 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5756 LHS.Designator.Entries[PathLength] 5757 .getAsBaseOrMember().getPointer())); 5758 } 5759 5760 // -- Otherwise, S(E) is empty. 5761 } else { 5762 break; 5763 } 5764 } 5765 5766 // Common case: no unions' lifetimes are started. 5767 if (UnionPathLengths.empty()) 5768 return true; 5769 5770 // if modification of X [would access an inactive union member], an object 5771 // of the type of X is implicitly created 5772 CompleteObject Obj = 5773 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5774 if (!Obj) 5775 return false; 5776 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5777 llvm::reverse(UnionPathLengths)) { 5778 // Form a designator for the union object. 5779 SubobjectDesignator D = LHS.Designator; 5780 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5781 5782 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5783 ConstructionPhase::AfterBases; 5784 StartLifetimeOfUnionMemberHandler StartLifetime{ 5785 Info, LHSExpr, LengthAndField.second, DuringInit}; 5786 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5787 return false; 5788 } 5789 5790 return true; 5791 } 5792 5793 namespace { 5794 typedef SmallVector<APValue, 8> ArgVector; 5795 } 5796 5797 /// EvaluateArgs - Evaluate the arguments to a function call. 5798 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5799 EvalInfo &Info, const FunctionDecl *Callee) { 5800 bool Success = true; 5801 llvm::SmallBitVector ForbiddenNullArgs; 5802 if (Callee->hasAttr<NonNullAttr>()) { 5803 ForbiddenNullArgs.resize(Args.size()); 5804 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5805 if (!Attr->args_size()) { 5806 ForbiddenNullArgs.set(); 5807 break; 5808 } else 5809 for (auto Idx : Attr->args()) { 5810 unsigned ASTIdx = Idx.getASTIndex(); 5811 if (ASTIdx >= Args.size()) 5812 continue; 5813 ForbiddenNullArgs[ASTIdx] = 1; 5814 } 5815 } 5816 } 5817 // FIXME: This is the wrong evaluation order for an assignment operator 5818 // called via operator syntax. 5819 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5820 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5821 // If we're checking for a potential constant expression, evaluate all 5822 // initializers even if some of them fail. 5823 if (!Info.noteFailure()) 5824 return false; 5825 Success = false; 5826 } else if (!ForbiddenNullArgs.empty() && 5827 ForbiddenNullArgs[Idx] && 5828 ArgValues[Idx].isLValue() && 5829 ArgValues[Idx].isNullPointer()) { 5830 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5831 if (!Info.noteFailure()) 5832 return false; 5833 Success = false; 5834 } 5835 } 5836 return Success; 5837 } 5838 5839 /// Evaluate a function call. 5840 static bool HandleFunctionCall(SourceLocation CallLoc, 5841 const FunctionDecl *Callee, const LValue *This, 5842 ArrayRef<const Expr*> Args, const Stmt *Body, 5843 EvalInfo &Info, APValue &Result, 5844 const LValue *ResultSlot) { 5845 ArgVector ArgValues(Args.size()); 5846 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5847 return false; 5848 5849 if (!Info.CheckCallLimit(CallLoc)) 5850 return false; 5851 5852 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5853 5854 // For a trivial copy or move assignment, perform an APValue copy. This is 5855 // essential for unions, where the operations performed by the assignment 5856 // operator cannot be represented as statements. 5857 // 5858 // Skip this for non-union classes with no fields; in that case, the defaulted 5859 // copy/move does not actually read the object. 5860 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5861 if (MD && MD->isDefaulted() && 5862 (MD->getParent()->isUnion() || 5863 (MD->isTrivial() && 5864 isReadByLvalueToRvalueConversion(MD->getParent())))) { 5865 assert(This && 5866 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5867 LValue RHS; 5868 RHS.setFrom(Info.Ctx, ArgValues[0]); 5869 APValue RHSValue; 5870 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5871 RHSValue, MD->getParent()->isUnion())) 5872 return false; 5873 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 5874 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5875 return false; 5876 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5877 RHSValue)) 5878 return false; 5879 This->moveInto(Result); 5880 return true; 5881 } else if (MD && isLambdaCallOperator(MD)) { 5882 // We're in a lambda; determine the lambda capture field maps unless we're 5883 // just constexpr checking a lambda's call operator. constexpr checking is 5884 // done before the captures have been added to the closure object (unless 5885 // we're inferring constexpr-ness), so we don't have access to them in this 5886 // case. But since we don't need the captures to constexpr check, we can 5887 // just ignore them. 5888 if (!Info.checkingPotentialConstantExpression()) 5889 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5890 Frame.LambdaThisCaptureField); 5891 } 5892 5893 StmtResult Ret = {Result, ResultSlot}; 5894 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5895 if (ESR == ESR_Succeeded) { 5896 if (Callee->getReturnType()->isVoidType()) 5897 return true; 5898 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5899 } 5900 return ESR == ESR_Returned; 5901 } 5902 5903 /// Evaluate a constructor call. 5904 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5905 APValue *ArgValues, 5906 const CXXConstructorDecl *Definition, 5907 EvalInfo &Info, APValue &Result) { 5908 SourceLocation CallLoc = E->getExprLoc(); 5909 if (!Info.CheckCallLimit(CallLoc)) 5910 return false; 5911 5912 const CXXRecordDecl *RD = Definition->getParent(); 5913 if (RD->getNumVBases()) { 5914 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5915 return false; 5916 } 5917 5918 EvalInfo::EvaluatingConstructorRAII EvalObj( 5919 Info, 5920 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5921 RD->getNumBases()); 5922 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5923 5924 // FIXME: Creating an APValue just to hold a nonexistent return value is 5925 // wasteful. 5926 APValue RetVal; 5927 StmtResult Ret = {RetVal, nullptr}; 5928 5929 // If it's a delegating constructor, delegate. 5930 if (Definition->isDelegatingConstructor()) { 5931 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5932 { 5933 FullExpressionRAII InitScope(Info); 5934 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5935 !InitScope.destroy()) 5936 return false; 5937 } 5938 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5939 } 5940 5941 // For a trivial copy or move constructor, perform an APValue copy. This is 5942 // essential for unions (or classes with anonymous union members), where the 5943 // operations performed by the constructor cannot be represented by 5944 // ctor-initializers. 5945 // 5946 // Skip this for empty non-union classes; we should not perform an 5947 // lvalue-to-rvalue conversion on them because their copy constructor does not 5948 // actually read them. 5949 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5950 (Definition->getParent()->isUnion() || 5951 (Definition->isTrivial() && 5952 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 5953 LValue RHS; 5954 RHS.setFrom(Info.Ctx, ArgValues[0]); 5955 return handleLValueToRValueConversion( 5956 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5957 RHS, Result, Definition->getParent()->isUnion()); 5958 } 5959 5960 // Reserve space for the struct members. 5961 if (!Result.hasValue()) { 5962 if (!RD->isUnion()) 5963 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5964 std::distance(RD->field_begin(), RD->field_end())); 5965 else 5966 // A union starts with no active member. 5967 Result = APValue((const FieldDecl*)nullptr); 5968 } 5969 5970 if (RD->isInvalidDecl()) return false; 5971 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5972 5973 // A scope for temporaries lifetime-extended by reference members. 5974 BlockScopeRAII LifetimeExtendedScope(Info); 5975 5976 bool Success = true; 5977 unsigned BasesSeen = 0; 5978 #ifndef NDEBUG 5979 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5980 #endif 5981 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5982 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5983 // We might be initializing the same field again if this is an indirect 5984 // field initialization. 5985 if (FieldIt == RD->field_end() || 5986 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5987 assert(Indirect && "fields out of order?"); 5988 return; 5989 } 5990 5991 // Default-initialize any fields with no explicit initializer. 5992 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5993 assert(FieldIt != RD->field_end() && "missing field?"); 5994 if (!FieldIt->isUnnamedBitfield()) 5995 Success &= getDefaultInitValue( 5996 FieldIt->getType(), 5997 Result.getStructField(FieldIt->getFieldIndex())); 5998 } 5999 ++FieldIt; 6000 }; 6001 for (const auto *I : Definition->inits()) { 6002 LValue Subobject = This; 6003 LValue SubobjectParent = This; 6004 APValue *Value = &Result; 6005 6006 // Determine the subobject to initialize. 6007 FieldDecl *FD = nullptr; 6008 if (I->isBaseInitializer()) { 6009 QualType BaseType(I->getBaseClass(), 0); 6010 #ifndef NDEBUG 6011 // Non-virtual base classes are initialized in the order in the class 6012 // definition. We have already checked for virtual base classes. 6013 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6014 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6015 "base class initializers not in expected order"); 6016 ++BaseIt; 6017 #endif 6018 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6019 BaseType->getAsCXXRecordDecl(), &Layout)) 6020 return false; 6021 Value = &Result.getStructBase(BasesSeen++); 6022 } else if ((FD = I->getMember())) { 6023 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6024 return false; 6025 if (RD->isUnion()) { 6026 Result = APValue(FD); 6027 Value = &Result.getUnionValue(); 6028 } else { 6029 SkipToField(FD, false); 6030 Value = &Result.getStructField(FD->getFieldIndex()); 6031 } 6032 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6033 // Walk the indirect field decl's chain to find the object to initialize, 6034 // and make sure we've initialized every step along it. 6035 auto IndirectFieldChain = IFD->chain(); 6036 for (auto *C : IndirectFieldChain) { 6037 FD = cast<FieldDecl>(C); 6038 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6039 // Switch the union field if it differs. This happens if we had 6040 // preceding zero-initialization, and we're now initializing a union 6041 // subobject other than the first. 6042 // FIXME: In this case, the values of the other subobjects are 6043 // specified, since zero-initialization sets all padding bits to zero. 6044 if (!Value->hasValue() || 6045 (Value->isUnion() && Value->getUnionField() != FD)) { 6046 if (CD->isUnion()) 6047 *Value = APValue(FD); 6048 else 6049 // FIXME: This immediately starts the lifetime of all members of 6050 // an anonymous struct. It would be preferable to strictly start 6051 // member lifetime in initialization order. 6052 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6053 } 6054 // Store Subobject as its parent before updating it for the last element 6055 // in the chain. 6056 if (C == IndirectFieldChain.back()) 6057 SubobjectParent = Subobject; 6058 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6059 return false; 6060 if (CD->isUnion()) 6061 Value = &Value->getUnionValue(); 6062 else { 6063 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6064 SkipToField(FD, true); 6065 Value = &Value->getStructField(FD->getFieldIndex()); 6066 } 6067 } 6068 } else { 6069 llvm_unreachable("unknown base initializer kind"); 6070 } 6071 6072 // Need to override This for implicit field initializers as in this case 6073 // This refers to innermost anonymous struct/union containing initializer, 6074 // not to currently constructed class. 6075 const Expr *Init = I->getInit(); 6076 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6077 isa<CXXDefaultInitExpr>(Init)); 6078 FullExpressionRAII InitScope(Info); 6079 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6080 (FD && FD->isBitField() && 6081 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6082 // If we're checking for a potential constant expression, evaluate all 6083 // initializers even if some of them fail. 6084 if (!Info.noteFailure()) 6085 return false; 6086 Success = false; 6087 } 6088 6089 // This is the point at which the dynamic type of the object becomes this 6090 // class type. 6091 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6092 EvalObj.finishedConstructingBases(); 6093 } 6094 6095 // Default-initialize any remaining fields. 6096 if (!RD->isUnion()) { 6097 for (; FieldIt != RD->field_end(); ++FieldIt) { 6098 if (!FieldIt->isUnnamedBitfield()) 6099 Success &= getDefaultInitValue( 6100 FieldIt->getType(), 6101 Result.getStructField(FieldIt->getFieldIndex())); 6102 } 6103 } 6104 6105 EvalObj.finishedConstructingFields(); 6106 6107 return Success && 6108 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6109 LifetimeExtendedScope.destroy(); 6110 } 6111 6112 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6113 ArrayRef<const Expr*> Args, 6114 const CXXConstructorDecl *Definition, 6115 EvalInfo &Info, APValue &Result) { 6116 ArgVector ArgValues(Args.size()); 6117 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 6118 return false; 6119 6120 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 6121 Info, Result); 6122 } 6123 6124 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6125 const LValue &This, APValue &Value, 6126 QualType T) { 6127 // Objects can only be destroyed while they're within their lifetimes. 6128 // FIXME: We have no representation for whether an object of type nullptr_t 6129 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6130 // as indeterminate instead? 6131 if (Value.isAbsent() && !T->isNullPtrType()) { 6132 APValue Printable; 6133 This.moveInto(Printable); 6134 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6135 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6136 return false; 6137 } 6138 6139 // Invent an expression for location purposes. 6140 // FIXME: We shouldn't need to do this. 6141 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6142 6143 // For arrays, destroy elements right-to-left. 6144 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6145 uint64_t Size = CAT->getSize().getZExtValue(); 6146 QualType ElemT = CAT->getElementType(); 6147 6148 LValue ElemLV = This; 6149 ElemLV.addArray(Info, &LocE, CAT); 6150 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6151 return false; 6152 6153 // Ensure that we have actual array elements available to destroy; the 6154 // destructors might mutate the value, so we can't run them on the array 6155 // filler. 6156 if (Size && Size > Value.getArrayInitializedElts()) 6157 expandArray(Value, Value.getArraySize() - 1); 6158 6159 for (; Size != 0; --Size) { 6160 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6161 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6162 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6163 return false; 6164 } 6165 6166 // End the lifetime of this array now. 6167 Value = APValue(); 6168 return true; 6169 } 6170 6171 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6172 if (!RD) { 6173 if (T.isDestructedType()) { 6174 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6175 return false; 6176 } 6177 6178 Value = APValue(); 6179 return true; 6180 } 6181 6182 if (RD->getNumVBases()) { 6183 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6184 return false; 6185 } 6186 6187 const CXXDestructorDecl *DD = RD->getDestructor(); 6188 if (!DD && !RD->hasTrivialDestructor()) { 6189 Info.FFDiag(CallLoc); 6190 return false; 6191 } 6192 6193 if (!DD || DD->isTrivial() || 6194 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6195 // A trivial destructor just ends the lifetime of the object. Check for 6196 // this case before checking for a body, because we might not bother 6197 // building a body for a trivial destructor. Note that it doesn't matter 6198 // whether the destructor is constexpr in this case; all trivial 6199 // destructors are constexpr. 6200 // 6201 // If an anonymous union would be destroyed, some enclosing destructor must 6202 // have been explicitly defined, and the anonymous union destruction should 6203 // have no effect. 6204 Value = APValue(); 6205 return true; 6206 } 6207 6208 if (!Info.CheckCallLimit(CallLoc)) 6209 return false; 6210 6211 const FunctionDecl *Definition = nullptr; 6212 const Stmt *Body = DD->getBody(Definition); 6213 6214 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6215 return false; 6216 6217 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 6218 6219 // We're now in the period of destruction of this object. 6220 unsigned BasesLeft = RD->getNumBases(); 6221 EvalInfo::EvaluatingDestructorRAII EvalObj( 6222 Info, 6223 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6224 if (!EvalObj.DidInsert) { 6225 // C++2a [class.dtor]p19: 6226 // the behavior is undefined if the destructor is invoked for an object 6227 // whose lifetime has ended 6228 // (Note that formally the lifetime ends when the period of destruction 6229 // begins, even though certain uses of the object remain valid until the 6230 // period of destruction ends.) 6231 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6232 return false; 6233 } 6234 6235 // FIXME: Creating an APValue just to hold a nonexistent return value is 6236 // wasteful. 6237 APValue RetVal; 6238 StmtResult Ret = {RetVal, nullptr}; 6239 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6240 return false; 6241 6242 // A union destructor does not implicitly destroy its members. 6243 if (RD->isUnion()) 6244 return true; 6245 6246 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6247 6248 // We don't have a good way to iterate fields in reverse, so collect all the 6249 // fields first and then walk them backwards. 6250 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6251 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6252 if (FD->isUnnamedBitfield()) 6253 continue; 6254 6255 LValue Subobject = This; 6256 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6257 return false; 6258 6259 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6260 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6261 FD->getType())) 6262 return false; 6263 } 6264 6265 if (BasesLeft != 0) 6266 EvalObj.startedDestroyingBases(); 6267 6268 // Destroy base classes in reverse order. 6269 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6270 --BasesLeft; 6271 6272 QualType BaseType = Base.getType(); 6273 LValue Subobject = This; 6274 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6275 BaseType->getAsCXXRecordDecl(), &Layout)) 6276 return false; 6277 6278 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6279 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6280 BaseType)) 6281 return false; 6282 } 6283 assert(BasesLeft == 0 && "NumBases was wrong?"); 6284 6285 // The period of destruction ends now. The object is gone. 6286 Value = APValue(); 6287 return true; 6288 } 6289 6290 namespace { 6291 struct DestroyObjectHandler { 6292 EvalInfo &Info; 6293 const Expr *E; 6294 const LValue &This; 6295 const AccessKinds AccessKind; 6296 6297 typedef bool result_type; 6298 bool failed() { return false; } 6299 bool found(APValue &Subobj, QualType SubobjType) { 6300 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6301 SubobjType); 6302 } 6303 bool found(APSInt &Value, QualType SubobjType) { 6304 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6305 return false; 6306 } 6307 bool found(APFloat &Value, QualType SubobjType) { 6308 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6309 return false; 6310 } 6311 }; 6312 } 6313 6314 /// Perform a destructor or pseudo-destructor call on the given object, which 6315 /// might in general not be a complete object. 6316 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6317 const LValue &This, QualType ThisType) { 6318 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6319 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6320 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6321 } 6322 6323 /// Destroy and end the lifetime of the given complete object. 6324 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6325 APValue::LValueBase LVBase, APValue &Value, 6326 QualType T) { 6327 // If we've had an unmodeled side-effect, we can't rely on mutable state 6328 // (such as the object we're about to destroy) being correct. 6329 if (Info.EvalStatus.HasSideEffects) 6330 return false; 6331 6332 LValue LV; 6333 LV.set({LVBase}); 6334 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6335 } 6336 6337 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6338 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6339 LValue &Result) { 6340 if (Info.checkingPotentialConstantExpression() || 6341 Info.SpeculativeEvaluationDepth) 6342 return false; 6343 6344 // This is permitted only within a call to std::allocator<T>::allocate. 6345 auto Caller = Info.getStdAllocatorCaller("allocate"); 6346 if (!Caller) { 6347 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6348 ? diag::note_constexpr_new_untyped 6349 : diag::note_constexpr_new); 6350 return false; 6351 } 6352 6353 QualType ElemType = Caller.ElemType; 6354 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6355 Info.FFDiag(E->getExprLoc(), 6356 diag::note_constexpr_new_not_complete_object_type) 6357 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6358 return false; 6359 } 6360 6361 APSInt ByteSize; 6362 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6363 return false; 6364 bool IsNothrow = false; 6365 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6366 EvaluateIgnoredValue(Info, E->getArg(I)); 6367 IsNothrow |= E->getType()->isNothrowT(); 6368 } 6369 6370 CharUnits ElemSize; 6371 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6372 return false; 6373 APInt Size, Remainder; 6374 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6375 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6376 if (Remainder != 0) { 6377 // This likely indicates a bug in the implementation of 'std::allocator'. 6378 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6379 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6380 return false; 6381 } 6382 6383 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6384 if (IsNothrow) { 6385 Result.setNull(Info.Ctx, E->getType()); 6386 return true; 6387 } 6388 6389 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6390 return false; 6391 } 6392 6393 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6394 ArrayType::Normal, 0); 6395 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6396 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6397 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6398 return true; 6399 } 6400 6401 static bool hasVirtualDestructor(QualType T) { 6402 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6403 if (CXXDestructorDecl *DD = RD->getDestructor()) 6404 return DD->isVirtual(); 6405 return false; 6406 } 6407 6408 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6409 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6410 if (CXXDestructorDecl *DD = RD->getDestructor()) 6411 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6412 return nullptr; 6413 } 6414 6415 /// Check that the given object is a suitable pointer to a heap allocation that 6416 /// still exists and is of the right kind for the purpose of a deletion. 6417 /// 6418 /// On success, returns the heap allocation to deallocate. On failure, produces 6419 /// a diagnostic and returns None. 6420 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6421 const LValue &Pointer, 6422 DynAlloc::Kind DeallocKind) { 6423 auto PointerAsString = [&] { 6424 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6425 }; 6426 6427 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6428 if (!DA) { 6429 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6430 << PointerAsString(); 6431 if (Pointer.Base) 6432 NoteLValueLocation(Info, Pointer.Base); 6433 return None; 6434 } 6435 6436 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6437 if (!Alloc) { 6438 Info.FFDiag(E, diag::note_constexpr_double_delete); 6439 return None; 6440 } 6441 6442 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6443 if (DeallocKind != (*Alloc)->getKind()) { 6444 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6445 << DeallocKind << (*Alloc)->getKind() << AllocType; 6446 NoteLValueLocation(Info, Pointer.Base); 6447 return None; 6448 } 6449 6450 bool Subobject = false; 6451 if (DeallocKind == DynAlloc::New) { 6452 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6453 Pointer.Designator.isOnePastTheEnd(); 6454 } else { 6455 Subobject = Pointer.Designator.Entries.size() != 1 || 6456 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6457 } 6458 if (Subobject) { 6459 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6460 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6461 return None; 6462 } 6463 6464 return Alloc; 6465 } 6466 6467 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6468 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6469 if (Info.checkingPotentialConstantExpression() || 6470 Info.SpeculativeEvaluationDepth) 6471 return false; 6472 6473 // This is permitted only within a call to std::allocator<T>::deallocate. 6474 if (!Info.getStdAllocatorCaller("deallocate")) { 6475 Info.FFDiag(E->getExprLoc()); 6476 return true; 6477 } 6478 6479 LValue Pointer; 6480 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6481 return false; 6482 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6483 EvaluateIgnoredValue(Info, E->getArg(I)); 6484 6485 if (Pointer.Designator.Invalid) 6486 return false; 6487 6488 // Deleting a null pointer has no effect. 6489 if (Pointer.isNullPointer()) 6490 return true; 6491 6492 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6493 return false; 6494 6495 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6496 return true; 6497 } 6498 6499 //===----------------------------------------------------------------------===// 6500 // Generic Evaluation 6501 //===----------------------------------------------------------------------===// 6502 namespace { 6503 6504 class BitCastBuffer { 6505 // FIXME: We're going to need bit-level granularity when we support 6506 // bit-fields. 6507 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6508 // we don't support a host or target where that is the case. Still, we should 6509 // use a more generic type in case we ever do. 6510 SmallVector<Optional<unsigned char>, 32> Bytes; 6511 6512 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6513 "Need at least 8 bit unsigned char"); 6514 6515 bool TargetIsLittleEndian; 6516 6517 public: 6518 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6519 : Bytes(Width.getQuantity()), 6520 TargetIsLittleEndian(TargetIsLittleEndian) {} 6521 6522 LLVM_NODISCARD 6523 bool readObject(CharUnits Offset, CharUnits Width, 6524 SmallVectorImpl<unsigned char> &Output) const { 6525 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6526 // If a byte of an integer is uninitialized, then the whole integer is 6527 // uninitalized. 6528 if (!Bytes[I.getQuantity()]) 6529 return false; 6530 Output.push_back(*Bytes[I.getQuantity()]); 6531 } 6532 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6533 std::reverse(Output.begin(), Output.end()); 6534 return true; 6535 } 6536 6537 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6538 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6539 std::reverse(Input.begin(), Input.end()); 6540 6541 size_t Index = 0; 6542 for (unsigned char Byte : Input) { 6543 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6544 Bytes[Offset.getQuantity() + Index] = Byte; 6545 ++Index; 6546 } 6547 } 6548 6549 size_t size() { return Bytes.size(); } 6550 }; 6551 6552 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6553 /// target would represent the value at runtime. 6554 class APValueToBufferConverter { 6555 EvalInfo &Info; 6556 BitCastBuffer Buffer; 6557 const CastExpr *BCE; 6558 6559 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6560 const CastExpr *BCE) 6561 : Info(Info), 6562 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6563 BCE(BCE) {} 6564 6565 bool visit(const APValue &Val, QualType Ty) { 6566 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6567 } 6568 6569 // Write out Val with type Ty into Buffer starting at Offset. 6570 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6571 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6572 6573 // As a special case, nullptr_t has an indeterminate value. 6574 if (Ty->isNullPtrType()) 6575 return true; 6576 6577 // Dig through Src to find the byte at SrcOffset. 6578 switch (Val.getKind()) { 6579 case APValue::Indeterminate: 6580 case APValue::None: 6581 return true; 6582 6583 case APValue::Int: 6584 return visitInt(Val.getInt(), Ty, Offset); 6585 case APValue::Float: 6586 return visitFloat(Val.getFloat(), Ty, Offset); 6587 case APValue::Array: 6588 return visitArray(Val, Ty, Offset); 6589 case APValue::Struct: 6590 return visitRecord(Val, Ty, Offset); 6591 6592 case APValue::ComplexInt: 6593 case APValue::ComplexFloat: 6594 case APValue::Vector: 6595 case APValue::FixedPoint: 6596 // FIXME: We should support these. 6597 6598 case APValue::Union: 6599 case APValue::MemberPointer: 6600 case APValue::AddrLabelDiff: { 6601 Info.FFDiag(BCE->getBeginLoc(), 6602 diag::note_constexpr_bit_cast_unsupported_type) 6603 << Ty; 6604 return false; 6605 } 6606 6607 case APValue::LValue: 6608 llvm_unreachable("LValue subobject in bit_cast?"); 6609 } 6610 llvm_unreachable("Unhandled APValue::ValueKind"); 6611 } 6612 6613 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6614 const RecordDecl *RD = Ty->getAsRecordDecl(); 6615 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6616 6617 // Visit the base classes. 6618 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6619 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6620 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6621 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6622 6623 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6624 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6625 return false; 6626 } 6627 } 6628 6629 // Visit the fields. 6630 unsigned FieldIdx = 0; 6631 for (FieldDecl *FD : RD->fields()) { 6632 if (FD->isBitField()) { 6633 Info.FFDiag(BCE->getBeginLoc(), 6634 diag::note_constexpr_bit_cast_unsupported_bitfield); 6635 return false; 6636 } 6637 6638 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6639 6640 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6641 "only bit-fields can have sub-char alignment"); 6642 CharUnits FieldOffset = 6643 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6644 QualType FieldTy = FD->getType(); 6645 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6646 return false; 6647 ++FieldIdx; 6648 } 6649 6650 return true; 6651 } 6652 6653 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6654 const auto *CAT = 6655 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6656 if (!CAT) 6657 return false; 6658 6659 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6660 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6661 unsigned ArraySize = Val.getArraySize(); 6662 // First, initialize the initialized elements. 6663 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6664 const APValue &SubObj = Val.getArrayInitializedElt(I); 6665 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6666 return false; 6667 } 6668 6669 // Next, initialize the rest of the array using the filler. 6670 if (Val.hasArrayFiller()) { 6671 const APValue &Filler = Val.getArrayFiller(); 6672 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6673 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6674 return false; 6675 } 6676 } 6677 6678 return true; 6679 } 6680 6681 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6682 APSInt AdjustedVal = Val; 6683 unsigned Width = AdjustedVal.getBitWidth(); 6684 if (Ty->isBooleanType()) { 6685 Width = Info.Ctx.getTypeSize(Ty); 6686 AdjustedVal = AdjustedVal.extend(Width); 6687 } 6688 6689 SmallVector<unsigned char, 8> Bytes(Width / 8); 6690 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6691 Buffer.writeObject(Offset, Bytes); 6692 return true; 6693 } 6694 6695 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6696 APSInt AsInt(Val.bitcastToAPInt()); 6697 return visitInt(AsInt, Ty, Offset); 6698 } 6699 6700 public: 6701 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6702 const CastExpr *BCE) { 6703 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6704 APValueToBufferConverter Converter(Info, DstSize, BCE); 6705 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6706 return None; 6707 return Converter.Buffer; 6708 } 6709 }; 6710 6711 /// Write an BitCastBuffer into an APValue. 6712 class BufferToAPValueConverter { 6713 EvalInfo &Info; 6714 const BitCastBuffer &Buffer; 6715 const CastExpr *BCE; 6716 6717 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6718 const CastExpr *BCE) 6719 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6720 6721 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6722 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6723 // Ideally this will be unreachable. 6724 llvm::NoneType unsupportedType(QualType Ty) { 6725 Info.FFDiag(BCE->getBeginLoc(), 6726 diag::note_constexpr_bit_cast_unsupported_type) 6727 << Ty; 6728 return None; 6729 } 6730 6731 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6732 Info.FFDiag(BCE->getBeginLoc(), 6733 diag::note_constexpr_bit_cast_unrepresentable_value) 6734 << Ty << Val.toString(/*Radix=*/10); 6735 return None; 6736 } 6737 6738 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6739 const EnumType *EnumSugar = nullptr) { 6740 if (T->isNullPtrType()) { 6741 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6742 return APValue((Expr *)nullptr, 6743 /*Offset=*/CharUnits::fromQuantity(NullValue), 6744 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6745 } 6746 6747 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6748 6749 // Work around floating point types that contain unused padding bytes. This 6750 // is really just `long double` on x86, which is the only fundamental type 6751 // with padding bytes. 6752 if (T->isRealFloatingType()) { 6753 const llvm::fltSemantics &Semantics = 6754 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6755 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6756 assert(NumBits % 8 == 0); 6757 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6758 if (NumBytes != SizeOf) 6759 SizeOf = NumBytes; 6760 } 6761 6762 SmallVector<uint8_t, 8> Bytes; 6763 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6764 // If this is std::byte or unsigned char, then its okay to store an 6765 // indeterminate value. 6766 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6767 bool IsUChar = 6768 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6769 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6770 if (!IsStdByte && !IsUChar) { 6771 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6772 Info.FFDiag(BCE->getExprLoc(), 6773 diag::note_constexpr_bit_cast_indet_dest) 6774 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6775 return None; 6776 } 6777 6778 return APValue::IndeterminateValue(); 6779 } 6780 6781 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6782 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6783 6784 if (T->isIntegralOrEnumerationType()) { 6785 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6786 6787 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 6788 if (IntWidth != Val.getBitWidth()) { 6789 APSInt Truncated = Val.trunc(IntWidth); 6790 if (Truncated.extend(Val.getBitWidth()) != Val) 6791 return unrepresentableValue(QualType(T, 0), Val); 6792 Val = Truncated; 6793 } 6794 6795 return APValue(Val); 6796 } 6797 6798 if (T->isRealFloatingType()) { 6799 const llvm::fltSemantics &Semantics = 6800 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6801 return APValue(APFloat(Semantics, Val)); 6802 } 6803 6804 return unsupportedType(QualType(T, 0)); 6805 } 6806 6807 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6808 const RecordDecl *RD = RTy->getAsRecordDecl(); 6809 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6810 6811 unsigned NumBases = 0; 6812 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6813 NumBases = CXXRD->getNumBases(); 6814 6815 APValue ResultVal(APValue::UninitStruct(), NumBases, 6816 std::distance(RD->field_begin(), RD->field_end())); 6817 6818 // Visit the base classes. 6819 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6820 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6821 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6822 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6823 if (BaseDecl->isEmpty() || 6824 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6825 continue; 6826 6827 Optional<APValue> SubObj = visitType( 6828 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6829 if (!SubObj) 6830 return None; 6831 ResultVal.getStructBase(I) = *SubObj; 6832 } 6833 } 6834 6835 // Visit the fields. 6836 unsigned FieldIdx = 0; 6837 for (FieldDecl *FD : RD->fields()) { 6838 // FIXME: We don't currently support bit-fields. A lot of the logic for 6839 // this is in CodeGen, so we need to factor it around. 6840 if (FD->isBitField()) { 6841 Info.FFDiag(BCE->getBeginLoc(), 6842 diag::note_constexpr_bit_cast_unsupported_bitfield); 6843 return None; 6844 } 6845 6846 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6847 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6848 6849 CharUnits FieldOffset = 6850 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6851 Offset; 6852 QualType FieldTy = FD->getType(); 6853 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6854 if (!SubObj) 6855 return None; 6856 ResultVal.getStructField(FieldIdx) = *SubObj; 6857 ++FieldIdx; 6858 } 6859 6860 return ResultVal; 6861 } 6862 6863 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6864 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6865 assert(!RepresentationType.isNull() && 6866 "enum forward decl should be caught by Sema"); 6867 const auto *AsBuiltin = 6868 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6869 // Recurse into the underlying type. Treat std::byte transparently as 6870 // unsigned char. 6871 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6872 } 6873 6874 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6875 size_t Size = Ty->getSize().getLimitedValue(); 6876 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6877 6878 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6879 for (size_t I = 0; I != Size; ++I) { 6880 Optional<APValue> ElementValue = 6881 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6882 if (!ElementValue) 6883 return None; 6884 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6885 } 6886 6887 return ArrayValue; 6888 } 6889 6890 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6891 return unsupportedType(QualType(Ty, 0)); 6892 } 6893 6894 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6895 QualType Can = Ty.getCanonicalType(); 6896 6897 switch (Can->getTypeClass()) { 6898 #define TYPE(Class, Base) \ 6899 case Type::Class: \ 6900 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6901 #define ABSTRACT_TYPE(Class, Base) 6902 #define NON_CANONICAL_TYPE(Class, Base) \ 6903 case Type::Class: \ 6904 llvm_unreachable("non-canonical type should be impossible!"); 6905 #define DEPENDENT_TYPE(Class, Base) \ 6906 case Type::Class: \ 6907 llvm_unreachable( \ 6908 "dependent types aren't supported in the constant evaluator!"); 6909 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6910 case Type::Class: \ 6911 llvm_unreachable("either dependent or not canonical!"); 6912 #include "clang/AST/TypeNodes.inc" 6913 } 6914 llvm_unreachable("Unhandled Type::TypeClass"); 6915 } 6916 6917 public: 6918 // Pull out a full value of type DstType. 6919 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6920 const CastExpr *BCE) { 6921 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6922 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6923 } 6924 }; 6925 6926 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6927 QualType Ty, EvalInfo *Info, 6928 const ASTContext &Ctx, 6929 bool CheckingDest) { 6930 Ty = Ty.getCanonicalType(); 6931 6932 auto diag = [&](int Reason) { 6933 if (Info) 6934 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6935 << CheckingDest << (Reason == 4) << Reason; 6936 return false; 6937 }; 6938 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6939 if (Info) 6940 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6941 << NoteTy << Construct << Ty; 6942 return false; 6943 }; 6944 6945 if (Ty->isUnionType()) 6946 return diag(0); 6947 if (Ty->isPointerType()) 6948 return diag(1); 6949 if (Ty->isMemberPointerType()) 6950 return diag(2); 6951 if (Ty.isVolatileQualified()) 6952 return diag(3); 6953 6954 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6955 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6956 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6957 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6958 CheckingDest)) 6959 return note(1, BS.getType(), BS.getBeginLoc()); 6960 } 6961 for (FieldDecl *FD : Record->fields()) { 6962 if (FD->getType()->isReferenceType()) 6963 return diag(4); 6964 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6965 CheckingDest)) 6966 return note(0, FD->getType(), FD->getBeginLoc()); 6967 } 6968 } 6969 6970 if (Ty->isArrayType() && 6971 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6972 Info, Ctx, CheckingDest)) 6973 return false; 6974 6975 return true; 6976 } 6977 6978 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6979 const ASTContext &Ctx, 6980 const CastExpr *BCE) { 6981 bool DestOK = checkBitCastConstexprEligibilityType( 6982 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6983 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6984 BCE->getBeginLoc(), 6985 BCE->getSubExpr()->getType(), Info, Ctx, false); 6986 return SourceOK; 6987 } 6988 6989 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6990 APValue &SourceValue, 6991 const CastExpr *BCE) { 6992 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6993 "no host or target supports non 8-bit chars"); 6994 assert(SourceValue.isLValue() && 6995 "LValueToRValueBitcast requires an lvalue operand!"); 6996 6997 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6998 return false; 6999 7000 LValue SourceLValue; 7001 APValue SourceRValue; 7002 SourceLValue.setFrom(Info.Ctx, SourceValue); 7003 if (!handleLValueToRValueConversion( 7004 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7005 SourceRValue, /*WantObjectRepresentation=*/true)) 7006 return false; 7007 7008 // Read out SourceValue into a char buffer. 7009 Optional<BitCastBuffer> Buffer = 7010 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7011 if (!Buffer) 7012 return false; 7013 7014 // Write out the buffer into a new APValue. 7015 Optional<APValue> MaybeDestValue = 7016 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7017 if (!MaybeDestValue) 7018 return false; 7019 7020 DestValue = std::move(*MaybeDestValue); 7021 return true; 7022 } 7023 7024 template <class Derived> 7025 class ExprEvaluatorBase 7026 : public ConstStmtVisitor<Derived, bool> { 7027 private: 7028 Derived &getDerived() { return static_cast<Derived&>(*this); } 7029 bool DerivedSuccess(const APValue &V, const Expr *E) { 7030 return getDerived().Success(V, E); 7031 } 7032 bool DerivedZeroInitialization(const Expr *E) { 7033 return getDerived().ZeroInitialization(E); 7034 } 7035 7036 // Check whether a conditional operator with a non-constant condition is a 7037 // potential constant expression. If neither arm is a potential constant 7038 // expression, then the conditional operator is not either. 7039 template<typename ConditionalOperator> 7040 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7041 assert(Info.checkingPotentialConstantExpression()); 7042 7043 // Speculatively evaluate both arms. 7044 SmallVector<PartialDiagnosticAt, 8> Diag; 7045 { 7046 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7047 StmtVisitorTy::Visit(E->getFalseExpr()); 7048 if (Diag.empty()) 7049 return; 7050 } 7051 7052 { 7053 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7054 Diag.clear(); 7055 StmtVisitorTy::Visit(E->getTrueExpr()); 7056 if (Diag.empty()) 7057 return; 7058 } 7059 7060 Error(E, diag::note_constexpr_conditional_never_const); 7061 } 7062 7063 7064 template<typename ConditionalOperator> 7065 bool HandleConditionalOperator(const ConditionalOperator *E) { 7066 bool BoolResult; 7067 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7068 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7069 CheckPotentialConstantConditional(E); 7070 return false; 7071 } 7072 if (Info.noteFailure()) { 7073 StmtVisitorTy::Visit(E->getTrueExpr()); 7074 StmtVisitorTy::Visit(E->getFalseExpr()); 7075 } 7076 return false; 7077 } 7078 7079 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7080 return StmtVisitorTy::Visit(EvalExpr); 7081 } 7082 7083 protected: 7084 EvalInfo &Info; 7085 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7086 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7087 7088 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7089 return Info.CCEDiag(E, D); 7090 } 7091 7092 bool ZeroInitialization(const Expr *E) { return Error(E); } 7093 7094 public: 7095 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7096 7097 EvalInfo &getEvalInfo() { return Info; } 7098 7099 /// Report an evaluation error. This should only be called when an error is 7100 /// first discovered. When propagating an error, just return false. 7101 bool Error(const Expr *E, diag::kind D) { 7102 Info.FFDiag(E, D); 7103 return false; 7104 } 7105 bool Error(const Expr *E) { 7106 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7107 } 7108 7109 bool VisitStmt(const Stmt *) { 7110 llvm_unreachable("Expression evaluator should not be called on stmts"); 7111 } 7112 bool VisitExpr(const Expr *E) { 7113 return Error(E); 7114 } 7115 7116 bool VisitConstantExpr(const ConstantExpr *E) { 7117 if (E->hasAPValueResult()) 7118 return DerivedSuccess(E->getAPValueResult(), E); 7119 7120 return StmtVisitorTy::Visit(E->getSubExpr()); 7121 } 7122 7123 bool VisitParenExpr(const ParenExpr *E) 7124 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7125 bool VisitUnaryExtension(const UnaryOperator *E) 7126 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7127 bool VisitUnaryPlus(const UnaryOperator *E) 7128 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7129 bool VisitChooseExpr(const ChooseExpr *E) 7130 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7131 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7132 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7133 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7134 { return StmtVisitorTy::Visit(E->getReplacement()); } 7135 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7136 TempVersionRAII RAII(*Info.CurrentCall); 7137 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7138 return StmtVisitorTy::Visit(E->getExpr()); 7139 } 7140 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7141 TempVersionRAII RAII(*Info.CurrentCall); 7142 // The initializer may not have been parsed yet, or might be erroneous. 7143 if (!E->getExpr()) 7144 return Error(E); 7145 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7146 return StmtVisitorTy::Visit(E->getExpr()); 7147 } 7148 7149 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7150 FullExpressionRAII Scope(Info); 7151 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7152 } 7153 7154 // Temporaries are registered when created, so we don't care about 7155 // CXXBindTemporaryExpr. 7156 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7157 return StmtVisitorTy::Visit(E->getSubExpr()); 7158 } 7159 7160 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7161 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7162 return static_cast<Derived*>(this)->VisitCastExpr(E); 7163 } 7164 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7165 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7166 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7167 return static_cast<Derived*>(this)->VisitCastExpr(E); 7168 } 7169 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7170 return static_cast<Derived*>(this)->VisitCastExpr(E); 7171 } 7172 7173 bool VisitBinaryOperator(const BinaryOperator *E) { 7174 switch (E->getOpcode()) { 7175 default: 7176 return Error(E); 7177 7178 case BO_Comma: 7179 VisitIgnoredValue(E->getLHS()); 7180 return StmtVisitorTy::Visit(E->getRHS()); 7181 7182 case BO_PtrMemD: 7183 case BO_PtrMemI: { 7184 LValue Obj; 7185 if (!HandleMemberPointerAccess(Info, E, Obj)) 7186 return false; 7187 APValue Result; 7188 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7189 return false; 7190 return DerivedSuccess(Result, E); 7191 } 7192 } 7193 } 7194 7195 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7196 return StmtVisitorTy::Visit(E->getSemanticForm()); 7197 } 7198 7199 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7200 // Evaluate and cache the common expression. We treat it as a temporary, 7201 // even though it's not quite the same thing. 7202 LValue CommonLV; 7203 if (!Evaluate(Info.CurrentCall->createTemporary( 7204 E->getOpaqueValue(), 7205 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 7206 CommonLV), 7207 Info, E->getCommon())) 7208 return false; 7209 7210 return HandleConditionalOperator(E); 7211 } 7212 7213 bool VisitConditionalOperator(const ConditionalOperator *E) { 7214 bool IsBcpCall = false; 7215 // If the condition (ignoring parens) is a __builtin_constant_p call, 7216 // the result is a constant expression if it can be folded without 7217 // side-effects. This is an important GNU extension. See GCC PR38377 7218 // for discussion. 7219 if (const CallExpr *CallCE = 7220 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7221 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7222 IsBcpCall = true; 7223 7224 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7225 // constant expression; we can't check whether it's potentially foldable. 7226 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7227 // it would return 'false' in this mode. 7228 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7229 return false; 7230 7231 FoldConstant Fold(Info, IsBcpCall); 7232 if (!HandleConditionalOperator(E)) { 7233 Fold.keepDiagnostics(); 7234 return false; 7235 } 7236 7237 return true; 7238 } 7239 7240 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7241 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7242 return DerivedSuccess(*Value, E); 7243 7244 const Expr *Source = E->getSourceExpr(); 7245 if (!Source) 7246 return Error(E); 7247 if (Source == E) { // sanity checking. 7248 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7249 return Error(E); 7250 } 7251 return StmtVisitorTy::Visit(Source); 7252 } 7253 7254 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7255 for (const Expr *SemE : E->semantics()) { 7256 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7257 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7258 // result expression: there could be two different LValues that would 7259 // refer to the same object in that case, and we can't model that. 7260 if (SemE == E->getResultExpr()) 7261 return Error(E); 7262 7263 // Unique OVEs get evaluated if and when we encounter them when 7264 // emitting the rest of the semantic form, rather than eagerly. 7265 if (OVE->isUnique()) 7266 continue; 7267 7268 LValue LV; 7269 if (!Evaluate(Info.CurrentCall->createTemporary( 7270 OVE, getStorageType(Info.Ctx, OVE), false, LV), 7271 Info, OVE->getSourceExpr())) 7272 return false; 7273 } else if (SemE == E->getResultExpr()) { 7274 if (!StmtVisitorTy::Visit(SemE)) 7275 return false; 7276 } else { 7277 if (!EvaluateIgnoredValue(Info, SemE)) 7278 return false; 7279 } 7280 } 7281 return true; 7282 } 7283 7284 bool VisitCallExpr(const CallExpr *E) { 7285 APValue Result; 7286 if (!handleCallExpr(E, Result, nullptr)) 7287 return false; 7288 return DerivedSuccess(Result, E); 7289 } 7290 7291 bool handleCallExpr(const CallExpr *E, APValue &Result, 7292 const LValue *ResultSlot) { 7293 const Expr *Callee = E->getCallee()->IgnoreParens(); 7294 QualType CalleeType = Callee->getType(); 7295 7296 const FunctionDecl *FD = nullptr; 7297 LValue *This = nullptr, ThisVal; 7298 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7299 bool HasQualifier = false; 7300 7301 // Extract function decl and 'this' pointer from the callee. 7302 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7303 const CXXMethodDecl *Member = nullptr; 7304 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7305 // Explicit bound member calls, such as x.f() or p->g(); 7306 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7307 return false; 7308 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7309 if (!Member) 7310 return Error(Callee); 7311 This = &ThisVal; 7312 HasQualifier = ME->hasQualifier(); 7313 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7314 // Indirect bound member calls ('.*' or '->*'). 7315 const ValueDecl *D = 7316 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7317 if (!D) 7318 return false; 7319 Member = dyn_cast<CXXMethodDecl>(D); 7320 if (!Member) 7321 return Error(Callee); 7322 This = &ThisVal; 7323 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7324 if (!Info.getLangOpts().CPlusPlus20) 7325 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7326 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7327 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7328 } else 7329 return Error(Callee); 7330 FD = Member; 7331 } else if (CalleeType->isFunctionPointerType()) { 7332 LValue Call; 7333 if (!EvaluatePointer(Callee, Call, Info)) 7334 return false; 7335 7336 if (!Call.getLValueOffset().isZero()) 7337 return Error(Callee); 7338 FD = dyn_cast_or_null<FunctionDecl>( 7339 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 7340 if (!FD) 7341 return Error(Callee); 7342 // Don't call function pointers which have been cast to some other type. 7343 // Per DR (no number yet), the caller and callee can differ in noexcept. 7344 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7345 CalleeType->getPointeeType(), FD->getType())) { 7346 return Error(E); 7347 } 7348 7349 // Overloaded operator calls to member functions are represented as normal 7350 // calls with '*this' as the first argument. 7351 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7352 if (MD && !MD->isStatic()) { 7353 // FIXME: When selecting an implicit conversion for an overloaded 7354 // operator delete, we sometimes try to evaluate calls to conversion 7355 // operators without a 'this' parameter! 7356 if (Args.empty()) 7357 return Error(E); 7358 7359 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7360 return false; 7361 This = &ThisVal; 7362 Args = Args.slice(1); 7363 } else if (MD && MD->isLambdaStaticInvoker()) { 7364 // Map the static invoker for the lambda back to the call operator. 7365 // Conveniently, we don't have to slice out the 'this' argument (as is 7366 // being done for the non-static case), since a static member function 7367 // doesn't have an implicit argument passed in. 7368 const CXXRecordDecl *ClosureClass = MD->getParent(); 7369 assert( 7370 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7371 "Number of captures must be zero for conversion to function-ptr"); 7372 7373 const CXXMethodDecl *LambdaCallOp = 7374 ClosureClass->getLambdaCallOperator(); 7375 7376 // Set 'FD', the function that will be called below, to the call 7377 // operator. If the closure object represents a generic lambda, find 7378 // the corresponding specialization of the call operator. 7379 7380 if (ClosureClass->isGenericLambda()) { 7381 assert(MD->isFunctionTemplateSpecialization() && 7382 "A generic lambda's static-invoker function must be a " 7383 "template specialization"); 7384 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7385 FunctionTemplateDecl *CallOpTemplate = 7386 LambdaCallOp->getDescribedFunctionTemplate(); 7387 void *InsertPos = nullptr; 7388 FunctionDecl *CorrespondingCallOpSpecialization = 7389 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7390 assert(CorrespondingCallOpSpecialization && 7391 "We must always have a function call operator specialization " 7392 "that corresponds to our static invoker specialization"); 7393 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7394 } else 7395 FD = LambdaCallOp; 7396 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7397 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7398 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7399 LValue Ptr; 7400 if (!HandleOperatorNewCall(Info, E, Ptr)) 7401 return false; 7402 Ptr.moveInto(Result); 7403 return true; 7404 } else { 7405 return HandleOperatorDeleteCall(Info, E); 7406 } 7407 } 7408 } else 7409 return Error(E); 7410 7411 SmallVector<QualType, 4> CovariantAdjustmentPath; 7412 if (This) { 7413 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7414 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7415 // Perform virtual dispatch, if necessary. 7416 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7417 CovariantAdjustmentPath); 7418 if (!FD) 7419 return false; 7420 } else { 7421 // Check that the 'this' pointer points to an object of the right type. 7422 // FIXME: If this is an assignment operator call, we may need to change 7423 // the active union member before we check this. 7424 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7425 return false; 7426 } 7427 } 7428 7429 // Destructor calls are different enough that they have their own codepath. 7430 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7431 assert(This && "no 'this' pointer for destructor call"); 7432 return HandleDestruction(Info, E, *This, 7433 Info.Ctx.getRecordType(DD->getParent())); 7434 } 7435 7436 const FunctionDecl *Definition = nullptr; 7437 Stmt *Body = FD->getBody(Definition); 7438 7439 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7440 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 7441 Result, ResultSlot)) 7442 return false; 7443 7444 if (!CovariantAdjustmentPath.empty() && 7445 !HandleCovariantReturnAdjustment(Info, E, Result, 7446 CovariantAdjustmentPath)) 7447 return false; 7448 7449 return true; 7450 } 7451 7452 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7453 return StmtVisitorTy::Visit(E->getInitializer()); 7454 } 7455 bool VisitInitListExpr(const InitListExpr *E) { 7456 if (E->getNumInits() == 0) 7457 return DerivedZeroInitialization(E); 7458 if (E->getNumInits() == 1) 7459 return StmtVisitorTy::Visit(E->getInit(0)); 7460 return Error(E); 7461 } 7462 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7463 return DerivedZeroInitialization(E); 7464 } 7465 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7466 return DerivedZeroInitialization(E); 7467 } 7468 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7469 return DerivedZeroInitialization(E); 7470 } 7471 7472 /// A member expression where the object is a prvalue is itself a prvalue. 7473 bool VisitMemberExpr(const MemberExpr *E) { 7474 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7475 "missing temporary materialization conversion"); 7476 assert(!E->isArrow() && "missing call to bound member function?"); 7477 7478 APValue Val; 7479 if (!Evaluate(Val, Info, E->getBase())) 7480 return false; 7481 7482 QualType BaseTy = E->getBase()->getType(); 7483 7484 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7485 if (!FD) return Error(E); 7486 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7487 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7488 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7489 7490 // Note: there is no lvalue base here. But this case should only ever 7491 // happen in C or in C++98, where we cannot be evaluating a constexpr 7492 // constructor, which is the only case the base matters. 7493 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7494 SubobjectDesignator Designator(BaseTy); 7495 Designator.addDeclUnchecked(FD); 7496 7497 APValue Result; 7498 return extractSubobject(Info, E, Obj, Designator, Result) && 7499 DerivedSuccess(Result, E); 7500 } 7501 7502 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7503 APValue Val; 7504 if (!Evaluate(Val, Info, E->getBase())) 7505 return false; 7506 7507 if (Val.isVector()) { 7508 SmallVector<uint32_t, 4> Indices; 7509 E->getEncodedElementAccess(Indices); 7510 if (Indices.size() == 1) { 7511 // Return scalar. 7512 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7513 } else { 7514 // Construct new APValue vector. 7515 SmallVector<APValue, 4> Elts; 7516 for (unsigned I = 0; I < Indices.size(); ++I) { 7517 Elts.push_back(Val.getVectorElt(Indices[I])); 7518 } 7519 APValue VecResult(Elts.data(), Indices.size()); 7520 return DerivedSuccess(VecResult, E); 7521 } 7522 } 7523 7524 return false; 7525 } 7526 7527 bool VisitCastExpr(const CastExpr *E) { 7528 switch (E->getCastKind()) { 7529 default: 7530 break; 7531 7532 case CK_AtomicToNonAtomic: { 7533 APValue AtomicVal; 7534 // This does not need to be done in place even for class/array types: 7535 // atomic-to-non-atomic conversion implies copying the object 7536 // representation. 7537 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7538 return false; 7539 return DerivedSuccess(AtomicVal, E); 7540 } 7541 7542 case CK_NoOp: 7543 case CK_UserDefinedConversion: 7544 return StmtVisitorTy::Visit(E->getSubExpr()); 7545 7546 case CK_LValueToRValue: { 7547 LValue LVal; 7548 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7549 return false; 7550 APValue RVal; 7551 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7552 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7553 LVal, RVal)) 7554 return false; 7555 return DerivedSuccess(RVal, E); 7556 } 7557 case CK_LValueToRValueBitCast: { 7558 APValue DestValue, SourceValue; 7559 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7560 return false; 7561 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7562 return false; 7563 return DerivedSuccess(DestValue, E); 7564 } 7565 7566 case CK_AddressSpaceConversion: { 7567 APValue Value; 7568 if (!Evaluate(Value, Info, E->getSubExpr())) 7569 return false; 7570 return DerivedSuccess(Value, E); 7571 } 7572 } 7573 7574 return Error(E); 7575 } 7576 7577 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7578 return VisitUnaryPostIncDec(UO); 7579 } 7580 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7581 return VisitUnaryPostIncDec(UO); 7582 } 7583 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7584 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7585 return Error(UO); 7586 7587 LValue LVal; 7588 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7589 return false; 7590 APValue RVal; 7591 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7592 UO->isIncrementOp(), &RVal)) 7593 return false; 7594 return DerivedSuccess(RVal, UO); 7595 } 7596 7597 bool VisitStmtExpr(const StmtExpr *E) { 7598 // We will have checked the full-expressions inside the statement expression 7599 // when they were completed, and don't need to check them again now. 7600 if (Info.checkingForUndefinedBehavior()) 7601 return Error(E); 7602 7603 const CompoundStmt *CS = E->getSubStmt(); 7604 if (CS->body_empty()) 7605 return true; 7606 7607 BlockScopeRAII Scope(Info); 7608 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7609 BE = CS->body_end(); 7610 /**/; ++BI) { 7611 if (BI + 1 == BE) { 7612 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7613 if (!FinalExpr) { 7614 Info.FFDiag((*BI)->getBeginLoc(), 7615 diag::note_constexpr_stmt_expr_unsupported); 7616 return false; 7617 } 7618 return this->Visit(FinalExpr) && Scope.destroy(); 7619 } 7620 7621 APValue ReturnValue; 7622 StmtResult Result = { ReturnValue, nullptr }; 7623 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7624 if (ESR != ESR_Succeeded) { 7625 // FIXME: If the statement-expression terminated due to 'return', 7626 // 'break', or 'continue', it would be nice to propagate that to 7627 // the outer statement evaluation rather than bailing out. 7628 if (ESR != ESR_Failed) 7629 Info.FFDiag((*BI)->getBeginLoc(), 7630 diag::note_constexpr_stmt_expr_unsupported); 7631 return false; 7632 } 7633 } 7634 7635 llvm_unreachable("Return from function from the loop above."); 7636 } 7637 7638 /// Visit a value which is evaluated, but whose value is ignored. 7639 void VisitIgnoredValue(const Expr *E) { 7640 EvaluateIgnoredValue(Info, E); 7641 } 7642 7643 /// Potentially visit a MemberExpr's base expression. 7644 void VisitIgnoredBaseExpression(const Expr *E) { 7645 // While MSVC doesn't evaluate the base expression, it does diagnose the 7646 // presence of side-effecting behavior. 7647 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7648 return; 7649 VisitIgnoredValue(E); 7650 } 7651 }; 7652 7653 } // namespace 7654 7655 //===----------------------------------------------------------------------===// 7656 // Common base class for lvalue and temporary evaluation. 7657 //===----------------------------------------------------------------------===// 7658 namespace { 7659 template<class Derived> 7660 class LValueExprEvaluatorBase 7661 : public ExprEvaluatorBase<Derived> { 7662 protected: 7663 LValue &Result; 7664 bool InvalidBaseOK; 7665 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7666 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7667 7668 bool Success(APValue::LValueBase B) { 7669 Result.set(B); 7670 return true; 7671 } 7672 7673 bool evaluatePointer(const Expr *E, LValue &Result) { 7674 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7675 } 7676 7677 public: 7678 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7679 : ExprEvaluatorBaseTy(Info), Result(Result), 7680 InvalidBaseOK(InvalidBaseOK) {} 7681 7682 bool Success(const APValue &V, const Expr *E) { 7683 Result.setFrom(this->Info.Ctx, V); 7684 return true; 7685 } 7686 7687 bool VisitMemberExpr(const MemberExpr *E) { 7688 // Handle non-static data members. 7689 QualType BaseTy; 7690 bool EvalOK; 7691 if (E->isArrow()) { 7692 EvalOK = evaluatePointer(E->getBase(), Result); 7693 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7694 } else if (E->getBase()->isRValue()) { 7695 assert(E->getBase()->getType()->isRecordType()); 7696 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7697 BaseTy = E->getBase()->getType(); 7698 } else { 7699 EvalOK = this->Visit(E->getBase()); 7700 BaseTy = E->getBase()->getType(); 7701 } 7702 if (!EvalOK) { 7703 if (!InvalidBaseOK) 7704 return false; 7705 Result.setInvalid(E); 7706 return true; 7707 } 7708 7709 const ValueDecl *MD = E->getMemberDecl(); 7710 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7711 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7712 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7713 (void)BaseTy; 7714 if (!HandleLValueMember(this->Info, E, Result, FD)) 7715 return false; 7716 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7717 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7718 return false; 7719 } else 7720 return this->Error(E); 7721 7722 if (MD->getType()->isReferenceType()) { 7723 APValue RefValue; 7724 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7725 RefValue)) 7726 return false; 7727 return Success(RefValue, E); 7728 } 7729 return true; 7730 } 7731 7732 bool VisitBinaryOperator(const BinaryOperator *E) { 7733 switch (E->getOpcode()) { 7734 default: 7735 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7736 7737 case BO_PtrMemD: 7738 case BO_PtrMemI: 7739 return HandleMemberPointerAccess(this->Info, E, Result); 7740 } 7741 } 7742 7743 bool VisitCastExpr(const CastExpr *E) { 7744 switch (E->getCastKind()) { 7745 default: 7746 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7747 7748 case CK_DerivedToBase: 7749 case CK_UncheckedDerivedToBase: 7750 if (!this->Visit(E->getSubExpr())) 7751 return false; 7752 7753 // Now figure out the necessary offset to add to the base LV to get from 7754 // the derived class to the base class. 7755 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7756 Result); 7757 } 7758 } 7759 }; 7760 } 7761 7762 //===----------------------------------------------------------------------===// 7763 // LValue Evaluation 7764 // 7765 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7766 // function designators (in C), decl references to void objects (in C), and 7767 // temporaries (if building with -Wno-address-of-temporary). 7768 // 7769 // LValue evaluation produces values comprising a base expression of one of the 7770 // following types: 7771 // - Declarations 7772 // * VarDecl 7773 // * FunctionDecl 7774 // - Literals 7775 // * CompoundLiteralExpr in C (and in global scope in C++) 7776 // * StringLiteral 7777 // * PredefinedExpr 7778 // * ObjCStringLiteralExpr 7779 // * ObjCEncodeExpr 7780 // * AddrLabelExpr 7781 // * BlockExpr 7782 // * CallExpr for a MakeStringConstant builtin 7783 // - typeid(T) expressions, as TypeInfoLValues 7784 // - Locals and temporaries 7785 // * MaterializeTemporaryExpr 7786 // * Any Expr, with a CallIndex indicating the function in which the temporary 7787 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7788 // from the AST (FIXME). 7789 // * A MaterializeTemporaryExpr that has static storage duration, with no 7790 // CallIndex, for a lifetime-extended temporary. 7791 // * The ConstantExpr that is currently being evaluated during evaluation of an 7792 // immediate invocation. 7793 // plus an offset in bytes. 7794 //===----------------------------------------------------------------------===// 7795 namespace { 7796 class LValueExprEvaluator 7797 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7798 public: 7799 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7800 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7801 7802 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7803 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7804 7805 bool VisitDeclRefExpr(const DeclRefExpr *E); 7806 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7807 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7808 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7809 bool VisitMemberExpr(const MemberExpr *E); 7810 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7811 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7812 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7813 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7814 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7815 bool VisitUnaryDeref(const UnaryOperator *E); 7816 bool VisitUnaryReal(const UnaryOperator *E); 7817 bool VisitUnaryImag(const UnaryOperator *E); 7818 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7819 return VisitUnaryPreIncDec(UO); 7820 } 7821 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7822 return VisitUnaryPreIncDec(UO); 7823 } 7824 bool VisitBinAssign(const BinaryOperator *BO); 7825 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7826 7827 bool VisitCastExpr(const CastExpr *E) { 7828 switch (E->getCastKind()) { 7829 default: 7830 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7831 7832 case CK_LValueBitCast: 7833 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7834 if (!Visit(E->getSubExpr())) 7835 return false; 7836 Result.Designator.setInvalid(); 7837 return true; 7838 7839 case CK_BaseToDerived: 7840 if (!Visit(E->getSubExpr())) 7841 return false; 7842 return HandleBaseToDerivedCast(Info, E, Result); 7843 7844 case CK_Dynamic: 7845 if (!Visit(E->getSubExpr())) 7846 return false; 7847 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7848 } 7849 } 7850 }; 7851 } // end anonymous namespace 7852 7853 /// Evaluate an expression as an lvalue. This can be legitimately called on 7854 /// expressions which are not glvalues, in three cases: 7855 /// * function designators in C, and 7856 /// * "extern void" objects 7857 /// * @selector() expressions in Objective-C 7858 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7859 bool InvalidBaseOK) { 7860 assert(E->isGLValue() || E->getType()->isFunctionType() || 7861 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7862 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7863 } 7864 7865 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7866 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7867 return Success(FD); 7868 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7869 return VisitVarDecl(E, VD); 7870 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7871 return Visit(BD->getBinding()); 7872 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 7873 return Success(GD); 7874 return Error(E); 7875 } 7876 7877 7878 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7879 7880 // If we are within a lambda's call operator, check whether the 'VD' referred 7881 // to within 'E' actually represents a lambda-capture that maps to a 7882 // data-member/field within the closure object, and if so, evaluate to the 7883 // field or what the field refers to. 7884 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7885 isa<DeclRefExpr>(E) && 7886 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7887 // We don't always have a complete capture-map when checking or inferring if 7888 // the function call operator meets the requirements of a constexpr function 7889 // - but we don't need to evaluate the captures to determine constexprness 7890 // (dcl.constexpr C++17). 7891 if (Info.checkingPotentialConstantExpression()) 7892 return false; 7893 7894 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7895 // Start with 'Result' referring to the complete closure object... 7896 Result = *Info.CurrentCall->This; 7897 // ... then update it to refer to the field of the closure object 7898 // that represents the capture. 7899 if (!HandleLValueMember(Info, E, Result, FD)) 7900 return false; 7901 // And if the field is of reference type, update 'Result' to refer to what 7902 // the field refers to. 7903 if (FD->getType()->isReferenceType()) { 7904 APValue RVal; 7905 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7906 RVal)) 7907 return false; 7908 Result.setFrom(Info.Ctx, RVal); 7909 } 7910 return true; 7911 } 7912 } 7913 CallStackFrame *Frame = nullptr; 7914 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7915 // Only if a local variable was declared in the function currently being 7916 // evaluated, do we expect to be able to find its value in the current 7917 // frame. (Otherwise it was likely declared in an enclosing context and 7918 // could either have a valid evaluatable value (for e.g. a constexpr 7919 // variable) or be ill-formed (and trigger an appropriate evaluation 7920 // diagnostic)). 7921 if (Info.CurrentCall->Callee && 7922 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7923 Frame = Info.CurrentCall; 7924 } 7925 } 7926 7927 if (!VD->getType()->isReferenceType()) { 7928 if (Frame) { 7929 Result.set({VD, Frame->Index, 7930 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7931 return true; 7932 } 7933 return Success(VD); 7934 } 7935 7936 APValue *V; 7937 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7938 return false; 7939 if (!V->hasValue()) { 7940 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7941 // adjust the diagnostic to say that. 7942 if (!Info.checkingPotentialConstantExpression()) 7943 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7944 return false; 7945 } 7946 return Success(*V, E); 7947 } 7948 7949 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7950 const MaterializeTemporaryExpr *E) { 7951 // Walk through the expression to find the materialized temporary itself. 7952 SmallVector<const Expr *, 2> CommaLHSs; 7953 SmallVector<SubobjectAdjustment, 2> Adjustments; 7954 const Expr *Inner = 7955 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7956 7957 // If we passed any comma operators, evaluate their LHSs. 7958 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7959 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7960 return false; 7961 7962 // A materialized temporary with static storage duration can appear within the 7963 // result of a constant expression evaluation, so we need to preserve its 7964 // value for use outside this evaluation. 7965 APValue *Value; 7966 if (E->getStorageDuration() == SD_Static) { 7967 Value = E->getOrCreateValue(true); 7968 *Value = APValue(); 7969 Result.set(E); 7970 } else { 7971 Value = &Info.CurrentCall->createTemporary( 7972 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7973 } 7974 7975 QualType Type = Inner->getType(); 7976 7977 // Materialize the temporary itself. 7978 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7979 *Value = APValue(); 7980 return false; 7981 } 7982 7983 // Adjust our lvalue to refer to the desired subobject. 7984 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7985 --I; 7986 switch (Adjustments[I].Kind) { 7987 case SubobjectAdjustment::DerivedToBaseAdjustment: 7988 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7989 Type, Result)) 7990 return false; 7991 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7992 break; 7993 7994 case SubobjectAdjustment::FieldAdjustment: 7995 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7996 return false; 7997 Type = Adjustments[I].Field->getType(); 7998 break; 7999 8000 case SubobjectAdjustment::MemberPointerAdjustment: 8001 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8002 Adjustments[I].Ptr.RHS)) 8003 return false; 8004 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8005 break; 8006 } 8007 } 8008 8009 return true; 8010 } 8011 8012 bool 8013 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8014 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8015 "lvalue compound literal in c++?"); 8016 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8017 // only see this when folding in C, so there's no standard to follow here. 8018 return Success(E); 8019 } 8020 8021 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8022 TypeInfoLValue TypeInfo; 8023 8024 if (!E->isPotentiallyEvaluated()) { 8025 if (E->isTypeOperand()) 8026 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8027 else 8028 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8029 } else { 8030 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8031 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8032 << E->getExprOperand()->getType() 8033 << E->getExprOperand()->getSourceRange(); 8034 } 8035 8036 if (!Visit(E->getExprOperand())) 8037 return false; 8038 8039 Optional<DynamicType> DynType = 8040 ComputeDynamicType(Info, E, Result, AK_TypeId); 8041 if (!DynType) 8042 return false; 8043 8044 TypeInfo = 8045 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8046 } 8047 8048 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8049 } 8050 8051 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8052 return Success(E->getGuidDecl()); 8053 } 8054 8055 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8056 // Handle static data members. 8057 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8058 VisitIgnoredBaseExpression(E->getBase()); 8059 return VisitVarDecl(E, VD); 8060 } 8061 8062 // Handle static member functions. 8063 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8064 if (MD->isStatic()) { 8065 VisitIgnoredBaseExpression(E->getBase()); 8066 return Success(MD); 8067 } 8068 } 8069 8070 // Handle non-static data members. 8071 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8072 } 8073 8074 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8075 // FIXME: Deal with vectors as array subscript bases. 8076 if (E->getBase()->getType()->isVectorType()) 8077 return Error(E); 8078 8079 bool Success = true; 8080 if (!evaluatePointer(E->getBase(), Result)) { 8081 if (!Info.noteFailure()) 8082 return false; 8083 Success = false; 8084 } 8085 8086 APSInt Index; 8087 if (!EvaluateInteger(E->getIdx(), Index, Info)) 8088 return false; 8089 8090 return Success && 8091 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8092 } 8093 8094 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8095 return evaluatePointer(E->getSubExpr(), Result); 8096 } 8097 8098 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8099 if (!Visit(E->getSubExpr())) 8100 return false; 8101 // __real is a no-op on scalar lvalues. 8102 if (E->getSubExpr()->getType()->isAnyComplexType()) 8103 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8104 return true; 8105 } 8106 8107 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8108 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8109 "lvalue __imag__ on scalar?"); 8110 if (!Visit(E->getSubExpr())) 8111 return false; 8112 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8113 return true; 8114 } 8115 8116 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8117 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8118 return Error(UO); 8119 8120 if (!this->Visit(UO->getSubExpr())) 8121 return false; 8122 8123 return handleIncDec( 8124 this->Info, UO, Result, UO->getSubExpr()->getType(), 8125 UO->isIncrementOp(), nullptr); 8126 } 8127 8128 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8129 const CompoundAssignOperator *CAO) { 8130 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8131 return Error(CAO); 8132 8133 APValue RHS; 8134 8135 // The overall lvalue result is the result of evaluating the LHS. 8136 if (!this->Visit(CAO->getLHS())) { 8137 if (Info.noteFailure()) 8138 Evaluate(RHS, this->Info, CAO->getRHS()); 8139 return false; 8140 } 8141 8142 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 8143 return false; 8144 8145 return handleCompoundAssignment( 8146 this->Info, CAO, 8147 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8148 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8149 } 8150 8151 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8152 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8153 return Error(E); 8154 8155 APValue NewVal; 8156 8157 if (!this->Visit(E->getLHS())) { 8158 if (Info.noteFailure()) 8159 Evaluate(NewVal, this->Info, E->getRHS()); 8160 return false; 8161 } 8162 8163 if (!Evaluate(NewVal, this->Info, E->getRHS())) 8164 return false; 8165 8166 if (Info.getLangOpts().CPlusPlus20 && 8167 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8168 return false; 8169 8170 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8171 NewVal); 8172 } 8173 8174 //===----------------------------------------------------------------------===// 8175 // Pointer Evaluation 8176 //===----------------------------------------------------------------------===// 8177 8178 /// Attempts to compute the number of bytes available at the pointer 8179 /// returned by a function with the alloc_size attribute. Returns true if we 8180 /// were successful. Places an unsigned number into `Result`. 8181 /// 8182 /// This expects the given CallExpr to be a call to a function with an 8183 /// alloc_size attribute. 8184 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8185 const CallExpr *Call, 8186 llvm::APInt &Result) { 8187 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8188 8189 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8190 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8191 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8192 if (Call->getNumArgs() <= SizeArgNo) 8193 return false; 8194 8195 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8196 Expr::EvalResult ExprResult; 8197 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8198 return false; 8199 Into = ExprResult.Val.getInt(); 8200 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8201 return false; 8202 Into = Into.zextOrSelf(BitsInSizeT); 8203 return true; 8204 }; 8205 8206 APSInt SizeOfElem; 8207 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8208 return false; 8209 8210 if (!AllocSize->getNumElemsParam().isValid()) { 8211 Result = std::move(SizeOfElem); 8212 return true; 8213 } 8214 8215 APSInt NumberOfElems; 8216 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8217 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8218 return false; 8219 8220 bool Overflow; 8221 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8222 if (Overflow) 8223 return false; 8224 8225 Result = std::move(BytesAvailable); 8226 return true; 8227 } 8228 8229 /// Convenience function. LVal's base must be a call to an alloc_size 8230 /// function. 8231 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8232 const LValue &LVal, 8233 llvm::APInt &Result) { 8234 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8235 "Can't get the size of a non alloc_size function"); 8236 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8237 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8238 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8239 } 8240 8241 /// Attempts to evaluate the given LValueBase as the result of a call to 8242 /// a function with the alloc_size attribute. If it was possible to do so, this 8243 /// function will return true, make Result's Base point to said function call, 8244 /// and mark Result's Base as invalid. 8245 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8246 LValue &Result) { 8247 if (Base.isNull()) 8248 return false; 8249 8250 // Because we do no form of static analysis, we only support const variables. 8251 // 8252 // Additionally, we can't support parameters, nor can we support static 8253 // variables (in the latter case, use-before-assign isn't UB; in the former, 8254 // we have no clue what they'll be assigned to). 8255 const auto *VD = 8256 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8257 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8258 return false; 8259 8260 const Expr *Init = VD->getAnyInitializer(); 8261 if (!Init) 8262 return false; 8263 8264 const Expr *E = Init->IgnoreParens(); 8265 if (!tryUnwrapAllocSizeCall(E)) 8266 return false; 8267 8268 // Store E instead of E unwrapped so that the type of the LValue's base is 8269 // what the user wanted. 8270 Result.setInvalid(E); 8271 8272 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8273 Result.addUnsizedArray(Info, E, Pointee); 8274 return true; 8275 } 8276 8277 namespace { 8278 class PointerExprEvaluator 8279 : public ExprEvaluatorBase<PointerExprEvaluator> { 8280 LValue &Result; 8281 bool InvalidBaseOK; 8282 8283 bool Success(const Expr *E) { 8284 Result.set(E); 8285 return true; 8286 } 8287 8288 bool evaluateLValue(const Expr *E, LValue &Result) { 8289 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8290 } 8291 8292 bool evaluatePointer(const Expr *E, LValue &Result) { 8293 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8294 } 8295 8296 bool visitNonBuiltinCallExpr(const CallExpr *E); 8297 public: 8298 8299 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8300 : ExprEvaluatorBaseTy(info), Result(Result), 8301 InvalidBaseOK(InvalidBaseOK) {} 8302 8303 bool Success(const APValue &V, const Expr *E) { 8304 Result.setFrom(Info.Ctx, V); 8305 return true; 8306 } 8307 bool ZeroInitialization(const Expr *E) { 8308 Result.setNull(Info.Ctx, E->getType()); 8309 return true; 8310 } 8311 8312 bool VisitBinaryOperator(const BinaryOperator *E); 8313 bool VisitCastExpr(const CastExpr* E); 8314 bool VisitUnaryAddrOf(const UnaryOperator *E); 8315 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8316 { return Success(E); } 8317 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8318 if (E->isExpressibleAsConstantInitializer()) 8319 return Success(E); 8320 if (Info.noteFailure()) 8321 EvaluateIgnoredValue(Info, E->getSubExpr()); 8322 return Error(E); 8323 } 8324 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8325 { return Success(E); } 8326 bool VisitCallExpr(const CallExpr *E); 8327 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8328 bool VisitBlockExpr(const BlockExpr *E) { 8329 if (!E->getBlockDecl()->hasCaptures()) 8330 return Success(E); 8331 return Error(E); 8332 } 8333 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8334 // Can't look at 'this' when checking a potential constant expression. 8335 if (Info.checkingPotentialConstantExpression()) 8336 return false; 8337 if (!Info.CurrentCall->This) { 8338 if (Info.getLangOpts().CPlusPlus11) 8339 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8340 else 8341 Info.FFDiag(E); 8342 return false; 8343 } 8344 Result = *Info.CurrentCall->This; 8345 // If we are inside a lambda's call operator, the 'this' expression refers 8346 // to the enclosing '*this' object (either by value or reference) which is 8347 // either copied into the closure object's field that represents the '*this' 8348 // or refers to '*this'. 8349 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8350 // Ensure we actually have captured 'this'. (an error will have 8351 // been previously reported if not). 8352 if (!Info.CurrentCall->LambdaThisCaptureField) 8353 return false; 8354 8355 // Update 'Result' to refer to the data member/field of the closure object 8356 // that represents the '*this' capture. 8357 if (!HandleLValueMember(Info, E, Result, 8358 Info.CurrentCall->LambdaThisCaptureField)) 8359 return false; 8360 // If we captured '*this' by reference, replace the field with its referent. 8361 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8362 ->isPointerType()) { 8363 APValue RVal; 8364 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8365 RVal)) 8366 return false; 8367 8368 Result.setFrom(Info.Ctx, RVal); 8369 } 8370 } 8371 return true; 8372 } 8373 8374 bool VisitCXXNewExpr(const CXXNewExpr *E); 8375 8376 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8377 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8378 APValue LValResult = E->EvaluateInContext( 8379 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8380 Result.setFrom(Info.Ctx, LValResult); 8381 return true; 8382 } 8383 8384 // FIXME: Missing: @protocol, @selector 8385 }; 8386 } // end anonymous namespace 8387 8388 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8389 bool InvalidBaseOK) { 8390 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8391 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8392 } 8393 8394 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8395 if (E->getOpcode() != BO_Add && 8396 E->getOpcode() != BO_Sub) 8397 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8398 8399 const Expr *PExp = E->getLHS(); 8400 const Expr *IExp = E->getRHS(); 8401 if (IExp->getType()->isPointerType()) 8402 std::swap(PExp, IExp); 8403 8404 bool EvalPtrOK = evaluatePointer(PExp, Result); 8405 if (!EvalPtrOK && !Info.noteFailure()) 8406 return false; 8407 8408 llvm::APSInt Offset; 8409 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8410 return false; 8411 8412 if (E->getOpcode() == BO_Sub) 8413 negateAsSigned(Offset); 8414 8415 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8416 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8417 } 8418 8419 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8420 return evaluateLValue(E->getSubExpr(), Result); 8421 } 8422 8423 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8424 const Expr *SubExpr = E->getSubExpr(); 8425 8426 switch (E->getCastKind()) { 8427 default: 8428 break; 8429 case CK_BitCast: 8430 case CK_CPointerToObjCPointerCast: 8431 case CK_BlockPointerToObjCPointerCast: 8432 case CK_AnyPointerToBlockPointerCast: 8433 case CK_AddressSpaceConversion: 8434 if (!Visit(SubExpr)) 8435 return false; 8436 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8437 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8438 // also static_casts, but we disallow them as a resolution to DR1312. 8439 if (!E->getType()->isVoidPointerType()) { 8440 if (!Result.InvalidBase && !Result.Designator.Invalid && 8441 !Result.IsNullPtr && 8442 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8443 E->getType()->getPointeeType()) && 8444 Info.getStdAllocatorCaller("allocate")) { 8445 // Inside a call to std::allocator::allocate and friends, we permit 8446 // casting from void* back to cv1 T* for a pointer that points to a 8447 // cv2 T. 8448 } else { 8449 Result.Designator.setInvalid(); 8450 if (SubExpr->getType()->isVoidPointerType()) 8451 CCEDiag(E, diag::note_constexpr_invalid_cast) 8452 << 3 << SubExpr->getType(); 8453 else 8454 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8455 } 8456 } 8457 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8458 ZeroInitialization(E); 8459 return true; 8460 8461 case CK_DerivedToBase: 8462 case CK_UncheckedDerivedToBase: 8463 if (!evaluatePointer(E->getSubExpr(), Result)) 8464 return false; 8465 if (!Result.Base && Result.Offset.isZero()) 8466 return true; 8467 8468 // Now figure out the necessary offset to add to the base LV to get from 8469 // the derived class to the base class. 8470 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8471 castAs<PointerType>()->getPointeeType(), 8472 Result); 8473 8474 case CK_BaseToDerived: 8475 if (!Visit(E->getSubExpr())) 8476 return false; 8477 if (!Result.Base && Result.Offset.isZero()) 8478 return true; 8479 return HandleBaseToDerivedCast(Info, E, Result); 8480 8481 case CK_Dynamic: 8482 if (!Visit(E->getSubExpr())) 8483 return false; 8484 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8485 8486 case CK_NullToPointer: 8487 VisitIgnoredValue(E->getSubExpr()); 8488 return ZeroInitialization(E); 8489 8490 case CK_IntegralToPointer: { 8491 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8492 8493 APValue Value; 8494 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8495 break; 8496 8497 if (Value.isInt()) { 8498 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8499 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8500 Result.Base = (Expr*)nullptr; 8501 Result.InvalidBase = false; 8502 Result.Offset = CharUnits::fromQuantity(N); 8503 Result.Designator.setInvalid(); 8504 Result.IsNullPtr = false; 8505 return true; 8506 } else { 8507 // Cast is of an lvalue, no need to change value. 8508 Result.setFrom(Info.Ctx, Value); 8509 return true; 8510 } 8511 } 8512 8513 case CK_ArrayToPointerDecay: { 8514 if (SubExpr->isGLValue()) { 8515 if (!evaluateLValue(SubExpr, Result)) 8516 return false; 8517 } else { 8518 APValue &Value = Info.CurrentCall->createTemporary( 8519 SubExpr, SubExpr->getType(), false, Result); 8520 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8521 return false; 8522 } 8523 // The result is a pointer to the first element of the array. 8524 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8525 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8526 Result.addArray(Info, E, CAT); 8527 else 8528 Result.addUnsizedArray(Info, E, AT->getElementType()); 8529 return true; 8530 } 8531 8532 case CK_FunctionToPointerDecay: 8533 return evaluateLValue(SubExpr, Result); 8534 8535 case CK_LValueToRValue: { 8536 LValue LVal; 8537 if (!evaluateLValue(E->getSubExpr(), LVal)) 8538 return false; 8539 8540 APValue RVal; 8541 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8542 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8543 LVal, RVal)) 8544 return InvalidBaseOK && 8545 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8546 return Success(RVal, E); 8547 } 8548 } 8549 8550 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8551 } 8552 8553 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8554 UnaryExprOrTypeTrait ExprKind) { 8555 // C++ [expr.alignof]p3: 8556 // When alignof is applied to a reference type, the result is the 8557 // alignment of the referenced type. 8558 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8559 T = Ref->getPointeeType(); 8560 8561 if (T.getQualifiers().hasUnaligned()) 8562 return CharUnits::One(); 8563 8564 const bool AlignOfReturnsPreferred = 8565 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8566 8567 // __alignof is defined to return the preferred alignment. 8568 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8569 // as well. 8570 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8571 return Info.Ctx.toCharUnitsFromBits( 8572 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8573 // alignof and _Alignof are defined to return the ABI alignment. 8574 else if (ExprKind == UETT_AlignOf) 8575 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8576 else 8577 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8578 } 8579 8580 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8581 UnaryExprOrTypeTrait ExprKind) { 8582 E = E->IgnoreParens(); 8583 8584 // The kinds of expressions that we have special-case logic here for 8585 // should be kept up to date with the special checks for those 8586 // expressions in Sema. 8587 8588 // alignof decl is always accepted, even if it doesn't make sense: we default 8589 // to 1 in those cases. 8590 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8591 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8592 /*RefAsPointee*/true); 8593 8594 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8595 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8596 /*RefAsPointee*/true); 8597 8598 return GetAlignOfType(Info, E->getType(), ExprKind); 8599 } 8600 8601 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8602 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8603 return Info.Ctx.getDeclAlign(VD); 8604 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8605 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8606 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8607 } 8608 8609 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8610 /// __builtin_is_aligned and __builtin_assume_aligned. 8611 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8612 EvalInfo &Info, APSInt &Alignment) { 8613 if (!EvaluateInteger(E, Alignment, Info)) 8614 return false; 8615 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8616 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8617 return false; 8618 } 8619 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8620 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8621 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8622 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8623 << MaxValue << ForType << Alignment; 8624 return false; 8625 } 8626 // Ensure both alignment and source value have the same bit width so that we 8627 // don't assert when computing the resulting value. 8628 APSInt ExtAlignment = 8629 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8630 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8631 "Alignment should not be changed by ext/trunc"); 8632 Alignment = ExtAlignment; 8633 assert(Alignment.getBitWidth() == SrcWidth); 8634 return true; 8635 } 8636 8637 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8638 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8639 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8640 return true; 8641 8642 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8643 return false; 8644 8645 Result.setInvalid(E); 8646 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8647 Result.addUnsizedArray(Info, E, PointeeTy); 8648 return true; 8649 } 8650 8651 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8652 if (IsStringLiteralCall(E)) 8653 return Success(E); 8654 8655 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8656 return VisitBuiltinCallExpr(E, BuiltinOp); 8657 8658 return visitNonBuiltinCallExpr(E); 8659 } 8660 8661 // Determine if T is a character type for which we guarantee that 8662 // sizeof(T) == 1. 8663 static bool isOneByteCharacterType(QualType T) { 8664 return T->isCharType() || T->isChar8Type(); 8665 } 8666 8667 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8668 unsigned BuiltinOp) { 8669 switch (BuiltinOp) { 8670 case Builtin::BI__builtin_addressof: 8671 return evaluateLValue(E->getArg(0), Result); 8672 case Builtin::BI__builtin_assume_aligned: { 8673 // We need to be very careful here because: if the pointer does not have the 8674 // asserted alignment, then the behavior is undefined, and undefined 8675 // behavior is non-constant. 8676 if (!evaluatePointer(E->getArg(0), Result)) 8677 return false; 8678 8679 LValue OffsetResult(Result); 8680 APSInt Alignment; 8681 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8682 Alignment)) 8683 return false; 8684 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8685 8686 if (E->getNumArgs() > 2) { 8687 APSInt Offset; 8688 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8689 return false; 8690 8691 int64_t AdditionalOffset = -Offset.getZExtValue(); 8692 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8693 } 8694 8695 // If there is a base object, then it must have the correct alignment. 8696 if (OffsetResult.Base) { 8697 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8698 8699 if (BaseAlignment < Align) { 8700 Result.Designator.setInvalid(); 8701 // FIXME: Add support to Diagnostic for long / long long. 8702 CCEDiag(E->getArg(0), 8703 diag::note_constexpr_baa_insufficient_alignment) << 0 8704 << (unsigned)BaseAlignment.getQuantity() 8705 << (unsigned)Align.getQuantity(); 8706 return false; 8707 } 8708 } 8709 8710 // The offset must also have the correct alignment. 8711 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8712 Result.Designator.setInvalid(); 8713 8714 (OffsetResult.Base 8715 ? CCEDiag(E->getArg(0), 8716 diag::note_constexpr_baa_insufficient_alignment) << 1 8717 : CCEDiag(E->getArg(0), 8718 diag::note_constexpr_baa_value_insufficient_alignment)) 8719 << (int)OffsetResult.Offset.getQuantity() 8720 << (unsigned)Align.getQuantity(); 8721 return false; 8722 } 8723 8724 return true; 8725 } 8726 case Builtin::BI__builtin_align_up: 8727 case Builtin::BI__builtin_align_down: { 8728 if (!evaluatePointer(E->getArg(0), Result)) 8729 return false; 8730 APSInt Alignment; 8731 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8732 Alignment)) 8733 return false; 8734 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8735 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8736 // For align_up/align_down, we can return the same value if the alignment 8737 // is known to be greater or equal to the requested value. 8738 if (PtrAlign.getQuantity() >= Alignment) 8739 return true; 8740 8741 // The alignment could be greater than the minimum at run-time, so we cannot 8742 // infer much about the resulting pointer value. One case is possible: 8743 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8744 // can infer the correct index if the requested alignment is smaller than 8745 // the base alignment so we can perform the computation on the offset. 8746 if (BaseAlignment.getQuantity() >= Alignment) { 8747 assert(Alignment.getBitWidth() <= 64 && 8748 "Cannot handle > 64-bit address-space"); 8749 uint64_t Alignment64 = Alignment.getZExtValue(); 8750 CharUnits NewOffset = CharUnits::fromQuantity( 8751 BuiltinOp == Builtin::BI__builtin_align_down 8752 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8753 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8754 Result.adjustOffset(NewOffset - Result.Offset); 8755 // TODO: diagnose out-of-bounds values/only allow for arrays? 8756 return true; 8757 } 8758 // Otherwise, we cannot constant-evaluate the result. 8759 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8760 << Alignment; 8761 return false; 8762 } 8763 case Builtin::BI__builtin_operator_new: 8764 return HandleOperatorNewCall(Info, E, Result); 8765 case Builtin::BI__builtin_launder: 8766 return evaluatePointer(E->getArg(0), Result); 8767 case Builtin::BIstrchr: 8768 case Builtin::BIwcschr: 8769 case Builtin::BImemchr: 8770 case Builtin::BIwmemchr: 8771 if (Info.getLangOpts().CPlusPlus11) 8772 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8773 << /*isConstexpr*/0 << /*isConstructor*/0 8774 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8775 else 8776 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8777 LLVM_FALLTHROUGH; 8778 case Builtin::BI__builtin_strchr: 8779 case Builtin::BI__builtin_wcschr: 8780 case Builtin::BI__builtin_memchr: 8781 case Builtin::BI__builtin_char_memchr: 8782 case Builtin::BI__builtin_wmemchr: { 8783 if (!Visit(E->getArg(0))) 8784 return false; 8785 APSInt Desired; 8786 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8787 return false; 8788 uint64_t MaxLength = uint64_t(-1); 8789 if (BuiltinOp != Builtin::BIstrchr && 8790 BuiltinOp != Builtin::BIwcschr && 8791 BuiltinOp != Builtin::BI__builtin_strchr && 8792 BuiltinOp != Builtin::BI__builtin_wcschr) { 8793 APSInt N; 8794 if (!EvaluateInteger(E->getArg(2), N, Info)) 8795 return false; 8796 MaxLength = N.getExtValue(); 8797 } 8798 // We cannot find the value if there are no candidates to match against. 8799 if (MaxLength == 0u) 8800 return ZeroInitialization(E); 8801 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8802 Result.Designator.Invalid) 8803 return false; 8804 QualType CharTy = Result.Designator.getType(Info.Ctx); 8805 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8806 BuiltinOp == Builtin::BI__builtin_memchr; 8807 assert(IsRawByte || 8808 Info.Ctx.hasSameUnqualifiedType( 8809 CharTy, E->getArg(0)->getType()->getPointeeType())); 8810 // Pointers to const void may point to objects of incomplete type. 8811 if (IsRawByte && CharTy->isIncompleteType()) { 8812 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8813 return false; 8814 } 8815 // Give up on byte-oriented matching against multibyte elements. 8816 // FIXME: We can compare the bytes in the correct order. 8817 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 8818 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 8819 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 8820 << CharTy; 8821 return false; 8822 } 8823 // Figure out what value we're actually looking for (after converting to 8824 // the corresponding unsigned type if necessary). 8825 uint64_t DesiredVal; 8826 bool StopAtNull = false; 8827 switch (BuiltinOp) { 8828 case Builtin::BIstrchr: 8829 case Builtin::BI__builtin_strchr: 8830 // strchr compares directly to the passed integer, and therefore 8831 // always fails if given an int that is not a char. 8832 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8833 E->getArg(1)->getType(), 8834 Desired), 8835 Desired)) 8836 return ZeroInitialization(E); 8837 StopAtNull = true; 8838 LLVM_FALLTHROUGH; 8839 case Builtin::BImemchr: 8840 case Builtin::BI__builtin_memchr: 8841 case Builtin::BI__builtin_char_memchr: 8842 // memchr compares by converting both sides to unsigned char. That's also 8843 // correct for strchr if we get this far (to cope with plain char being 8844 // unsigned in the strchr case). 8845 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8846 break; 8847 8848 case Builtin::BIwcschr: 8849 case Builtin::BI__builtin_wcschr: 8850 StopAtNull = true; 8851 LLVM_FALLTHROUGH; 8852 case Builtin::BIwmemchr: 8853 case Builtin::BI__builtin_wmemchr: 8854 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8855 DesiredVal = Desired.getZExtValue(); 8856 break; 8857 } 8858 8859 for (; MaxLength; --MaxLength) { 8860 APValue Char; 8861 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8862 !Char.isInt()) 8863 return false; 8864 if (Char.getInt().getZExtValue() == DesiredVal) 8865 return true; 8866 if (StopAtNull && !Char.getInt()) 8867 break; 8868 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8869 return false; 8870 } 8871 // Not found: return nullptr. 8872 return ZeroInitialization(E); 8873 } 8874 8875 case Builtin::BImemcpy: 8876 case Builtin::BImemmove: 8877 case Builtin::BIwmemcpy: 8878 case Builtin::BIwmemmove: 8879 if (Info.getLangOpts().CPlusPlus11) 8880 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8881 << /*isConstexpr*/0 << /*isConstructor*/0 8882 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8883 else 8884 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8885 LLVM_FALLTHROUGH; 8886 case Builtin::BI__builtin_memcpy: 8887 case Builtin::BI__builtin_memmove: 8888 case Builtin::BI__builtin_wmemcpy: 8889 case Builtin::BI__builtin_wmemmove: { 8890 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8891 BuiltinOp == Builtin::BIwmemmove || 8892 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8893 BuiltinOp == Builtin::BI__builtin_wmemmove; 8894 bool Move = BuiltinOp == Builtin::BImemmove || 8895 BuiltinOp == Builtin::BIwmemmove || 8896 BuiltinOp == Builtin::BI__builtin_memmove || 8897 BuiltinOp == Builtin::BI__builtin_wmemmove; 8898 8899 // The result of mem* is the first argument. 8900 if (!Visit(E->getArg(0))) 8901 return false; 8902 LValue Dest = Result; 8903 8904 LValue Src; 8905 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8906 return false; 8907 8908 APSInt N; 8909 if (!EvaluateInteger(E->getArg(2), N, Info)) 8910 return false; 8911 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8912 8913 // If the size is zero, we treat this as always being a valid no-op. 8914 // (Even if one of the src and dest pointers is null.) 8915 if (!N) 8916 return true; 8917 8918 // Otherwise, if either of the operands is null, we can't proceed. Don't 8919 // try to determine the type of the copied objects, because there aren't 8920 // any. 8921 if (!Src.Base || !Dest.Base) { 8922 APValue Val; 8923 (!Src.Base ? Src : Dest).moveInto(Val); 8924 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8925 << Move << WChar << !!Src.Base 8926 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8927 return false; 8928 } 8929 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8930 return false; 8931 8932 // We require that Src and Dest are both pointers to arrays of 8933 // trivially-copyable type. (For the wide version, the designator will be 8934 // invalid if the designated object is not a wchar_t.) 8935 QualType T = Dest.Designator.getType(Info.Ctx); 8936 QualType SrcT = Src.Designator.getType(Info.Ctx); 8937 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8938 // FIXME: Consider using our bit_cast implementation to support this. 8939 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8940 return false; 8941 } 8942 if (T->isIncompleteType()) { 8943 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8944 return false; 8945 } 8946 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8947 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8948 return false; 8949 } 8950 8951 // Figure out how many T's we're copying. 8952 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8953 if (!WChar) { 8954 uint64_t Remainder; 8955 llvm::APInt OrigN = N; 8956 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8957 if (Remainder) { 8958 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8959 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8960 << (unsigned)TSize; 8961 return false; 8962 } 8963 } 8964 8965 // Check that the copying will remain within the arrays, just so that we 8966 // can give a more meaningful diagnostic. This implicitly also checks that 8967 // N fits into 64 bits. 8968 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8969 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8970 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8971 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8972 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8973 << N.toString(10, /*Signed*/false); 8974 return false; 8975 } 8976 uint64_t NElems = N.getZExtValue(); 8977 uint64_t NBytes = NElems * TSize; 8978 8979 // Check for overlap. 8980 int Direction = 1; 8981 if (HasSameBase(Src, Dest)) { 8982 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8983 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8984 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8985 // Dest is inside the source region. 8986 if (!Move) { 8987 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8988 return false; 8989 } 8990 // For memmove and friends, copy backwards. 8991 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8992 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8993 return false; 8994 Direction = -1; 8995 } else if (!Move && SrcOffset >= DestOffset && 8996 SrcOffset - DestOffset < NBytes) { 8997 // Src is inside the destination region for memcpy: invalid. 8998 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8999 return false; 9000 } 9001 } 9002 9003 while (true) { 9004 APValue Val; 9005 // FIXME: Set WantObjectRepresentation to true if we're copying a 9006 // char-like type? 9007 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9008 !handleAssignment(Info, E, Dest, T, Val)) 9009 return false; 9010 // Do not iterate past the last element; if we're copying backwards, that 9011 // might take us off the start of the array. 9012 if (--NElems == 0) 9013 return true; 9014 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9015 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9016 return false; 9017 } 9018 } 9019 9020 default: 9021 break; 9022 } 9023 9024 return visitNonBuiltinCallExpr(E); 9025 } 9026 9027 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9028 APValue &Result, const InitListExpr *ILE, 9029 QualType AllocType); 9030 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9031 APValue &Result, 9032 const CXXConstructExpr *CCE, 9033 QualType AllocType); 9034 9035 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9036 if (!Info.getLangOpts().CPlusPlus20) 9037 Info.CCEDiag(E, diag::note_constexpr_new); 9038 9039 // We cannot speculatively evaluate a delete expression. 9040 if (Info.SpeculativeEvaluationDepth) 9041 return false; 9042 9043 FunctionDecl *OperatorNew = E->getOperatorNew(); 9044 9045 bool IsNothrow = false; 9046 bool IsPlacement = false; 9047 if (OperatorNew->isReservedGlobalPlacementOperator() && 9048 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9049 // FIXME Support array placement new. 9050 assert(E->getNumPlacementArgs() == 1); 9051 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9052 return false; 9053 if (Result.Designator.Invalid) 9054 return false; 9055 IsPlacement = true; 9056 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9057 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9058 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9059 return false; 9060 } else if (E->getNumPlacementArgs()) { 9061 // The only new-placement list we support is of the form (std::nothrow). 9062 // 9063 // FIXME: There is no restriction on this, but it's not clear that any 9064 // other form makes any sense. We get here for cases such as: 9065 // 9066 // new (std::align_val_t{N}) X(int) 9067 // 9068 // (which should presumably be valid only if N is a multiple of 9069 // alignof(int), and in any case can't be deallocated unless N is 9070 // alignof(X) and X has new-extended alignment). 9071 if (E->getNumPlacementArgs() != 1 || 9072 !E->getPlacementArg(0)->getType()->isNothrowT()) 9073 return Error(E, diag::note_constexpr_new_placement); 9074 9075 LValue Nothrow; 9076 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9077 return false; 9078 IsNothrow = true; 9079 } 9080 9081 const Expr *Init = E->getInitializer(); 9082 const InitListExpr *ResizedArrayILE = nullptr; 9083 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9084 bool ValueInit = false; 9085 9086 QualType AllocType = E->getAllocatedType(); 9087 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9088 const Expr *Stripped = *ArraySize; 9089 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9090 Stripped = ICE->getSubExpr()) 9091 if (ICE->getCastKind() != CK_NoOp && 9092 ICE->getCastKind() != CK_IntegralCast) 9093 break; 9094 9095 llvm::APSInt ArrayBound; 9096 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9097 return false; 9098 9099 // C++ [expr.new]p9: 9100 // The expression is erroneous if: 9101 // -- [...] its value before converting to size_t [or] applying the 9102 // second standard conversion sequence is less than zero 9103 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9104 if (IsNothrow) 9105 return ZeroInitialization(E); 9106 9107 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9108 << ArrayBound << (*ArraySize)->getSourceRange(); 9109 return false; 9110 } 9111 9112 // -- its value is such that the size of the allocated object would 9113 // exceed the implementation-defined limit 9114 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9115 ArrayBound) > 9116 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9117 if (IsNothrow) 9118 return ZeroInitialization(E); 9119 9120 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9121 << ArrayBound << (*ArraySize)->getSourceRange(); 9122 return false; 9123 } 9124 9125 // -- the new-initializer is a braced-init-list and the number of 9126 // array elements for which initializers are provided [...] 9127 // exceeds the number of elements to initialize 9128 if (!Init) { 9129 // No initialization is performed. 9130 } else if (isa<CXXScalarValueInitExpr>(Init) || 9131 isa<ImplicitValueInitExpr>(Init)) { 9132 ValueInit = true; 9133 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9134 ResizedArrayCCE = CCE; 9135 } else { 9136 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9137 assert(CAT && "unexpected type for array initializer"); 9138 9139 unsigned Bits = 9140 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9141 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9142 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9143 if (InitBound.ugt(AllocBound)) { 9144 if (IsNothrow) 9145 return ZeroInitialization(E); 9146 9147 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9148 << AllocBound.toString(10, /*Signed=*/false) 9149 << InitBound.toString(10, /*Signed=*/false) 9150 << (*ArraySize)->getSourceRange(); 9151 return false; 9152 } 9153 9154 // If the sizes differ, we must have an initializer list, and we need 9155 // special handling for this case when we initialize. 9156 if (InitBound != AllocBound) 9157 ResizedArrayILE = cast<InitListExpr>(Init); 9158 } 9159 9160 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9161 ArrayType::Normal, 0); 9162 } else { 9163 assert(!AllocType->isArrayType() && 9164 "array allocation with non-array new"); 9165 } 9166 9167 APValue *Val; 9168 if (IsPlacement) { 9169 AccessKinds AK = AK_Construct; 9170 struct FindObjectHandler { 9171 EvalInfo &Info; 9172 const Expr *E; 9173 QualType AllocType; 9174 const AccessKinds AccessKind; 9175 APValue *Value; 9176 9177 typedef bool result_type; 9178 bool failed() { return false; } 9179 bool found(APValue &Subobj, QualType SubobjType) { 9180 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9181 // old name of the object to be used to name the new object. 9182 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9183 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9184 SubobjType << AllocType; 9185 return false; 9186 } 9187 Value = &Subobj; 9188 return true; 9189 } 9190 bool found(APSInt &Value, QualType SubobjType) { 9191 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9192 return false; 9193 } 9194 bool found(APFloat &Value, QualType SubobjType) { 9195 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9196 return false; 9197 } 9198 } Handler = {Info, E, AllocType, AK, nullptr}; 9199 9200 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9201 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9202 return false; 9203 9204 Val = Handler.Value; 9205 9206 // [basic.life]p1: 9207 // The lifetime of an object o of type T ends when [...] the storage 9208 // which the object occupies is [...] reused by an object that is not 9209 // nested within o (6.6.2). 9210 *Val = APValue(); 9211 } else { 9212 // Perform the allocation and obtain a pointer to the resulting object. 9213 Val = Info.createHeapAlloc(E, AllocType, Result); 9214 if (!Val) 9215 return false; 9216 } 9217 9218 if (ValueInit) { 9219 ImplicitValueInitExpr VIE(AllocType); 9220 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9221 return false; 9222 } else if (ResizedArrayILE) { 9223 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9224 AllocType)) 9225 return false; 9226 } else if (ResizedArrayCCE) { 9227 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9228 AllocType)) 9229 return false; 9230 } else if (Init) { 9231 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9232 return false; 9233 } else if (!getDefaultInitValue(AllocType, *Val)) { 9234 return false; 9235 } 9236 9237 // Array new returns a pointer to the first element, not a pointer to the 9238 // array. 9239 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9240 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9241 9242 return true; 9243 } 9244 //===----------------------------------------------------------------------===// 9245 // Member Pointer Evaluation 9246 //===----------------------------------------------------------------------===// 9247 9248 namespace { 9249 class MemberPointerExprEvaluator 9250 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9251 MemberPtr &Result; 9252 9253 bool Success(const ValueDecl *D) { 9254 Result = MemberPtr(D); 9255 return true; 9256 } 9257 public: 9258 9259 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9260 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9261 9262 bool Success(const APValue &V, const Expr *E) { 9263 Result.setFrom(V); 9264 return true; 9265 } 9266 bool ZeroInitialization(const Expr *E) { 9267 return Success((const ValueDecl*)nullptr); 9268 } 9269 9270 bool VisitCastExpr(const CastExpr *E); 9271 bool VisitUnaryAddrOf(const UnaryOperator *E); 9272 }; 9273 } // end anonymous namespace 9274 9275 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9276 EvalInfo &Info) { 9277 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9278 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9279 } 9280 9281 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9282 switch (E->getCastKind()) { 9283 default: 9284 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9285 9286 case CK_NullToMemberPointer: 9287 VisitIgnoredValue(E->getSubExpr()); 9288 return ZeroInitialization(E); 9289 9290 case CK_BaseToDerivedMemberPointer: { 9291 if (!Visit(E->getSubExpr())) 9292 return false; 9293 if (E->path_empty()) 9294 return true; 9295 // Base-to-derived member pointer casts store the path in derived-to-base 9296 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9297 // the wrong end of the derived->base arc, so stagger the path by one class. 9298 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9299 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9300 PathI != PathE; ++PathI) { 9301 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9302 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9303 if (!Result.castToDerived(Derived)) 9304 return Error(E); 9305 } 9306 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9307 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9308 return Error(E); 9309 return true; 9310 } 9311 9312 case CK_DerivedToBaseMemberPointer: 9313 if (!Visit(E->getSubExpr())) 9314 return false; 9315 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9316 PathE = E->path_end(); PathI != PathE; ++PathI) { 9317 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9318 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9319 if (!Result.castToBase(Base)) 9320 return Error(E); 9321 } 9322 return true; 9323 } 9324 } 9325 9326 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9327 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9328 // member can be formed. 9329 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9330 } 9331 9332 //===----------------------------------------------------------------------===// 9333 // Record Evaluation 9334 //===----------------------------------------------------------------------===// 9335 9336 namespace { 9337 class RecordExprEvaluator 9338 : public ExprEvaluatorBase<RecordExprEvaluator> { 9339 const LValue &This; 9340 APValue &Result; 9341 public: 9342 9343 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9344 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9345 9346 bool Success(const APValue &V, const Expr *E) { 9347 Result = V; 9348 return true; 9349 } 9350 bool ZeroInitialization(const Expr *E) { 9351 return ZeroInitialization(E, E->getType()); 9352 } 9353 bool ZeroInitialization(const Expr *E, QualType T); 9354 9355 bool VisitCallExpr(const CallExpr *E) { 9356 return handleCallExpr(E, Result, &This); 9357 } 9358 bool VisitCastExpr(const CastExpr *E); 9359 bool VisitInitListExpr(const InitListExpr *E); 9360 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9361 return VisitCXXConstructExpr(E, E->getType()); 9362 } 9363 bool VisitLambdaExpr(const LambdaExpr *E); 9364 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9365 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9366 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9367 bool VisitBinCmp(const BinaryOperator *E); 9368 }; 9369 } 9370 9371 /// Perform zero-initialization on an object of non-union class type. 9372 /// C++11 [dcl.init]p5: 9373 /// To zero-initialize an object or reference of type T means: 9374 /// [...] 9375 /// -- if T is a (possibly cv-qualified) non-union class type, 9376 /// each non-static data member and each base-class subobject is 9377 /// zero-initialized 9378 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9379 const RecordDecl *RD, 9380 const LValue &This, APValue &Result) { 9381 assert(!RD->isUnion() && "Expected non-union class type"); 9382 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9383 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9384 std::distance(RD->field_begin(), RD->field_end())); 9385 9386 if (RD->isInvalidDecl()) return false; 9387 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9388 9389 if (CD) { 9390 unsigned Index = 0; 9391 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9392 End = CD->bases_end(); I != End; ++I, ++Index) { 9393 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9394 LValue Subobject = This; 9395 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9396 return false; 9397 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9398 Result.getStructBase(Index))) 9399 return false; 9400 } 9401 } 9402 9403 for (const auto *I : RD->fields()) { 9404 // -- if T is a reference type, no initialization is performed. 9405 if (I->getType()->isReferenceType()) 9406 continue; 9407 9408 LValue Subobject = This; 9409 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9410 return false; 9411 9412 ImplicitValueInitExpr VIE(I->getType()); 9413 if (!EvaluateInPlace( 9414 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9415 return false; 9416 } 9417 9418 return true; 9419 } 9420 9421 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9422 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9423 if (RD->isInvalidDecl()) return false; 9424 if (RD->isUnion()) { 9425 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9426 // object's first non-static named data member is zero-initialized 9427 RecordDecl::field_iterator I = RD->field_begin(); 9428 if (I == RD->field_end()) { 9429 Result = APValue((const FieldDecl*)nullptr); 9430 return true; 9431 } 9432 9433 LValue Subobject = This; 9434 if (!HandleLValueMember(Info, E, Subobject, *I)) 9435 return false; 9436 Result = APValue(*I); 9437 ImplicitValueInitExpr VIE(I->getType()); 9438 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9439 } 9440 9441 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9442 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9443 return false; 9444 } 9445 9446 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9447 } 9448 9449 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9450 switch (E->getCastKind()) { 9451 default: 9452 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9453 9454 case CK_ConstructorConversion: 9455 return Visit(E->getSubExpr()); 9456 9457 case CK_DerivedToBase: 9458 case CK_UncheckedDerivedToBase: { 9459 APValue DerivedObject; 9460 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9461 return false; 9462 if (!DerivedObject.isStruct()) 9463 return Error(E->getSubExpr()); 9464 9465 // Derived-to-base rvalue conversion: just slice off the derived part. 9466 APValue *Value = &DerivedObject; 9467 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9468 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9469 PathE = E->path_end(); PathI != PathE; ++PathI) { 9470 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9471 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9472 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9473 RD = Base; 9474 } 9475 Result = *Value; 9476 return true; 9477 } 9478 } 9479 } 9480 9481 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9482 if (E->isTransparent()) 9483 return Visit(E->getInit(0)); 9484 9485 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9486 if (RD->isInvalidDecl()) return false; 9487 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9488 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9489 9490 EvalInfo::EvaluatingConstructorRAII EvalObj( 9491 Info, 9492 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9493 CXXRD && CXXRD->getNumBases()); 9494 9495 if (RD->isUnion()) { 9496 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9497 Result = APValue(Field); 9498 if (!Field) 9499 return true; 9500 9501 // If the initializer list for a union does not contain any elements, the 9502 // first element of the union is value-initialized. 9503 // FIXME: The element should be initialized from an initializer list. 9504 // Is this difference ever observable for initializer lists which 9505 // we don't build? 9506 ImplicitValueInitExpr VIE(Field->getType()); 9507 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9508 9509 LValue Subobject = This; 9510 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9511 return false; 9512 9513 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9514 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9515 isa<CXXDefaultInitExpr>(InitExpr)); 9516 9517 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9518 } 9519 9520 if (!Result.hasValue()) 9521 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9522 std::distance(RD->field_begin(), RD->field_end())); 9523 unsigned ElementNo = 0; 9524 bool Success = true; 9525 9526 // Initialize base classes. 9527 if (CXXRD && CXXRD->getNumBases()) { 9528 for (const auto &Base : CXXRD->bases()) { 9529 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9530 const Expr *Init = E->getInit(ElementNo); 9531 9532 LValue Subobject = This; 9533 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9534 return false; 9535 9536 APValue &FieldVal = Result.getStructBase(ElementNo); 9537 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9538 if (!Info.noteFailure()) 9539 return false; 9540 Success = false; 9541 } 9542 ++ElementNo; 9543 } 9544 9545 EvalObj.finishedConstructingBases(); 9546 } 9547 9548 // Initialize members. 9549 for (const auto *Field : RD->fields()) { 9550 // Anonymous bit-fields are not considered members of the class for 9551 // purposes of aggregate initialization. 9552 if (Field->isUnnamedBitfield()) 9553 continue; 9554 9555 LValue Subobject = This; 9556 9557 bool HaveInit = ElementNo < E->getNumInits(); 9558 9559 // FIXME: Diagnostics here should point to the end of the initializer 9560 // list, not the start. 9561 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9562 Subobject, Field, &Layout)) 9563 return false; 9564 9565 // Perform an implicit value-initialization for members beyond the end of 9566 // the initializer list. 9567 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9568 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9569 9570 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9571 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9572 isa<CXXDefaultInitExpr>(Init)); 9573 9574 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9575 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9576 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9577 FieldVal, Field))) { 9578 if (!Info.noteFailure()) 9579 return false; 9580 Success = false; 9581 } 9582 } 9583 9584 EvalObj.finishedConstructingFields(); 9585 9586 return Success; 9587 } 9588 9589 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9590 QualType T) { 9591 // Note that E's type is not necessarily the type of our class here; we might 9592 // be initializing an array element instead. 9593 const CXXConstructorDecl *FD = E->getConstructor(); 9594 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9595 9596 bool ZeroInit = E->requiresZeroInitialization(); 9597 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9598 // If we've already performed zero-initialization, we're already done. 9599 if (Result.hasValue()) 9600 return true; 9601 9602 if (ZeroInit) 9603 return ZeroInitialization(E, T); 9604 9605 return getDefaultInitValue(T, Result); 9606 } 9607 9608 const FunctionDecl *Definition = nullptr; 9609 auto Body = FD->getBody(Definition); 9610 9611 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9612 return false; 9613 9614 // Avoid materializing a temporary for an elidable copy/move constructor. 9615 if (E->isElidable() && !ZeroInit) 9616 if (const MaterializeTemporaryExpr *ME 9617 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9618 return Visit(ME->getSubExpr()); 9619 9620 if (ZeroInit && !ZeroInitialization(E, T)) 9621 return false; 9622 9623 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9624 return HandleConstructorCall(E, This, Args, 9625 cast<CXXConstructorDecl>(Definition), Info, 9626 Result); 9627 } 9628 9629 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9630 const CXXInheritedCtorInitExpr *E) { 9631 if (!Info.CurrentCall) { 9632 assert(Info.checkingPotentialConstantExpression()); 9633 return false; 9634 } 9635 9636 const CXXConstructorDecl *FD = E->getConstructor(); 9637 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9638 return false; 9639 9640 const FunctionDecl *Definition = nullptr; 9641 auto Body = FD->getBody(Definition); 9642 9643 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9644 return false; 9645 9646 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9647 cast<CXXConstructorDecl>(Definition), Info, 9648 Result); 9649 } 9650 9651 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9652 const CXXStdInitializerListExpr *E) { 9653 const ConstantArrayType *ArrayType = 9654 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9655 9656 LValue Array; 9657 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9658 return false; 9659 9660 // Get a pointer to the first element of the array. 9661 Array.addArray(Info, E, ArrayType); 9662 9663 auto InvalidType = [&] { 9664 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9665 << E->getType(); 9666 return false; 9667 }; 9668 9669 // FIXME: Perform the checks on the field types in SemaInit. 9670 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9671 RecordDecl::field_iterator Field = Record->field_begin(); 9672 if (Field == Record->field_end()) 9673 return InvalidType(); 9674 9675 // Start pointer. 9676 if (!Field->getType()->isPointerType() || 9677 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9678 ArrayType->getElementType())) 9679 return InvalidType(); 9680 9681 // FIXME: What if the initializer_list type has base classes, etc? 9682 Result = APValue(APValue::UninitStruct(), 0, 2); 9683 Array.moveInto(Result.getStructField(0)); 9684 9685 if (++Field == Record->field_end()) 9686 return InvalidType(); 9687 9688 if (Field->getType()->isPointerType() && 9689 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9690 ArrayType->getElementType())) { 9691 // End pointer. 9692 if (!HandleLValueArrayAdjustment(Info, E, Array, 9693 ArrayType->getElementType(), 9694 ArrayType->getSize().getZExtValue())) 9695 return false; 9696 Array.moveInto(Result.getStructField(1)); 9697 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9698 // Length. 9699 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9700 else 9701 return InvalidType(); 9702 9703 if (++Field != Record->field_end()) 9704 return InvalidType(); 9705 9706 return true; 9707 } 9708 9709 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9710 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9711 if (ClosureClass->isInvalidDecl()) 9712 return false; 9713 9714 const size_t NumFields = 9715 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9716 9717 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9718 E->capture_init_end()) && 9719 "The number of lambda capture initializers should equal the number of " 9720 "fields within the closure type"); 9721 9722 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9723 // Iterate through all the lambda's closure object's fields and initialize 9724 // them. 9725 auto *CaptureInitIt = E->capture_init_begin(); 9726 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9727 bool Success = true; 9728 for (const auto *Field : ClosureClass->fields()) { 9729 assert(CaptureInitIt != E->capture_init_end()); 9730 // Get the initializer for this field 9731 Expr *const CurFieldInit = *CaptureInitIt++; 9732 9733 // If there is no initializer, either this is a VLA or an error has 9734 // occurred. 9735 if (!CurFieldInit) 9736 return Error(E); 9737 9738 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9739 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9740 if (!Info.keepEvaluatingAfterFailure()) 9741 return false; 9742 Success = false; 9743 } 9744 ++CaptureIt; 9745 } 9746 return Success; 9747 } 9748 9749 static bool EvaluateRecord(const Expr *E, const LValue &This, 9750 APValue &Result, EvalInfo &Info) { 9751 assert(E->isRValue() && E->getType()->isRecordType() && 9752 "can't evaluate expression as a record rvalue"); 9753 return RecordExprEvaluator(Info, This, Result).Visit(E); 9754 } 9755 9756 //===----------------------------------------------------------------------===// 9757 // Temporary Evaluation 9758 // 9759 // Temporaries are represented in the AST as rvalues, but generally behave like 9760 // lvalues. The full-object of which the temporary is a subobject is implicitly 9761 // materialized so that a reference can bind to it. 9762 //===----------------------------------------------------------------------===// 9763 namespace { 9764 class TemporaryExprEvaluator 9765 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9766 public: 9767 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9768 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9769 9770 /// Visit an expression which constructs the value of this temporary. 9771 bool VisitConstructExpr(const Expr *E) { 9772 APValue &Value = 9773 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9774 return EvaluateInPlace(Value, Info, Result, E); 9775 } 9776 9777 bool VisitCastExpr(const CastExpr *E) { 9778 switch (E->getCastKind()) { 9779 default: 9780 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9781 9782 case CK_ConstructorConversion: 9783 return VisitConstructExpr(E->getSubExpr()); 9784 } 9785 } 9786 bool VisitInitListExpr(const InitListExpr *E) { 9787 return VisitConstructExpr(E); 9788 } 9789 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9790 return VisitConstructExpr(E); 9791 } 9792 bool VisitCallExpr(const CallExpr *E) { 9793 return VisitConstructExpr(E); 9794 } 9795 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9796 return VisitConstructExpr(E); 9797 } 9798 bool VisitLambdaExpr(const LambdaExpr *E) { 9799 return VisitConstructExpr(E); 9800 } 9801 }; 9802 } // end anonymous namespace 9803 9804 /// Evaluate an expression of record type as a temporary. 9805 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9806 assert(E->isRValue() && E->getType()->isRecordType()); 9807 return TemporaryExprEvaluator(Info, Result).Visit(E); 9808 } 9809 9810 //===----------------------------------------------------------------------===// 9811 // Vector Evaluation 9812 //===----------------------------------------------------------------------===// 9813 9814 namespace { 9815 class VectorExprEvaluator 9816 : public ExprEvaluatorBase<VectorExprEvaluator> { 9817 APValue &Result; 9818 public: 9819 9820 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9821 : ExprEvaluatorBaseTy(info), Result(Result) {} 9822 9823 bool Success(ArrayRef<APValue> V, const Expr *E) { 9824 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9825 // FIXME: remove this APValue copy. 9826 Result = APValue(V.data(), V.size()); 9827 return true; 9828 } 9829 bool Success(const APValue &V, const Expr *E) { 9830 assert(V.isVector()); 9831 Result = V; 9832 return true; 9833 } 9834 bool ZeroInitialization(const Expr *E); 9835 9836 bool VisitUnaryReal(const UnaryOperator *E) 9837 { return Visit(E->getSubExpr()); } 9838 bool VisitCastExpr(const CastExpr* E); 9839 bool VisitInitListExpr(const InitListExpr *E); 9840 bool VisitUnaryImag(const UnaryOperator *E); 9841 bool VisitBinaryOperator(const BinaryOperator *E); 9842 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 9843 // conditional select), shufflevector, ExtVectorElementExpr 9844 }; 9845 } // end anonymous namespace 9846 9847 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9848 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9849 return VectorExprEvaluator(Info, Result).Visit(E); 9850 } 9851 9852 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9853 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9854 unsigned NElts = VTy->getNumElements(); 9855 9856 const Expr *SE = E->getSubExpr(); 9857 QualType SETy = SE->getType(); 9858 9859 switch (E->getCastKind()) { 9860 case CK_VectorSplat: { 9861 APValue Val = APValue(); 9862 if (SETy->isIntegerType()) { 9863 APSInt IntResult; 9864 if (!EvaluateInteger(SE, IntResult, Info)) 9865 return false; 9866 Val = APValue(std::move(IntResult)); 9867 } else if (SETy->isRealFloatingType()) { 9868 APFloat FloatResult(0.0); 9869 if (!EvaluateFloat(SE, FloatResult, Info)) 9870 return false; 9871 Val = APValue(std::move(FloatResult)); 9872 } else { 9873 return Error(E); 9874 } 9875 9876 // Splat and create vector APValue. 9877 SmallVector<APValue, 4> Elts(NElts, Val); 9878 return Success(Elts, E); 9879 } 9880 case CK_BitCast: { 9881 // Evaluate the operand into an APInt we can extract from. 9882 llvm::APInt SValInt; 9883 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9884 return false; 9885 // Extract the elements 9886 QualType EltTy = VTy->getElementType(); 9887 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9888 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9889 SmallVector<APValue, 4> Elts; 9890 if (EltTy->isRealFloatingType()) { 9891 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9892 unsigned FloatEltSize = EltSize; 9893 if (&Sem == &APFloat::x87DoubleExtended()) 9894 FloatEltSize = 80; 9895 for (unsigned i = 0; i < NElts; i++) { 9896 llvm::APInt Elt; 9897 if (BigEndian) 9898 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9899 else 9900 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9901 Elts.push_back(APValue(APFloat(Sem, Elt))); 9902 } 9903 } else if (EltTy->isIntegerType()) { 9904 for (unsigned i = 0; i < NElts; i++) { 9905 llvm::APInt Elt; 9906 if (BigEndian) 9907 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9908 else 9909 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9910 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9911 } 9912 } else { 9913 return Error(E); 9914 } 9915 return Success(Elts, E); 9916 } 9917 default: 9918 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9919 } 9920 } 9921 9922 bool 9923 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9924 const VectorType *VT = E->getType()->castAs<VectorType>(); 9925 unsigned NumInits = E->getNumInits(); 9926 unsigned NumElements = VT->getNumElements(); 9927 9928 QualType EltTy = VT->getElementType(); 9929 SmallVector<APValue, 4> Elements; 9930 9931 // The number of initializers can be less than the number of 9932 // vector elements. For OpenCL, this can be due to nested vector 9933 // initialization. For GCC compatibility, missing trailing elements 9934 // should be initialized with zeroes. 9935 unsigned CountInits = 0, CountElts = 0; 9936 while (CountElts < NumElements) { 9937 // Handle nested vector initialization. 9938 if (CountInits < NumInits 9939 && E->getInit(CountInits)->getType()->isVectorType()) { 9940 APValue v; 9941 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9942 return Error(E); 9943 unsigned vlen = v.getVectorLength(); 9944 for (unsigned j = 0; j < vlen; j++) 9945 Elements.push_back(v.getVectorElt(j)); 9946 CountElts += vlen; 9947 } else if (EltTy->isIntegerType()) { 9948 llvm::APSInt sInt(32); 9949 if (CountInits < NumInits) { 9950 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9951 return false; 9952 } else // trailing integer zero. 9953 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9954 Elements.push_back(APValue(sInt)); 9955 CountElts++; 9956 } else { 9957 llvm::APFloat f(0.0); 9958 if (CountInits < NumInits) { 9959 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9960 return false; 9961 } else // trailing float zero. 9962 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9963 Elements.push_back(APValue(f)); 9964 CountElts++; 9965 } 9966 CountInits++; 9967 } 9968 return Success(Elements, E); 9969 } 9970 9971 bool 9972 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9973 const auto *VT = E->getType()->castAs<VectorType>(); 9974 QualType EltTy = VT->getElementType(); 9975 APValue ZeroElement; 9976 if (EltTy->isIntegerType()) 9977 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9978 else 9979 ZeroElement = 9980 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9981 9982 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9983 return Success(Elements, E); 9984 } 9985 9986 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9987 VisitIgnoredValue(E->getSubExpr()); 9988 return ZeroInitialization(E); 9989 } 9990 9991 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9992 BinaryOperatorKind Op = E->getOpcode(); 9993 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 9994 "Operation not supported on vector types"); 9995 9996 if (Op == BO_Comma) 9997 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9998 9999 Expr *LHS = E->getLHS(); 10000 Expr *RHS = E->getRHS(); 10001 10002 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10003 "Must both be vector types"); 10004 // Checking JUST the types are the same would be fine, except shifts don't 10005 // need to have their types be the same (since you always shift by an int). 10006 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10007 E->getType()->getAs<VectorType>()->getNumElements() && 10008 RHS->getType()->getAs<VectorType>()->getNumElements() == 10009 E->getType()->getAs<VectorType>()->getNumElements() && 10010 "All operands must be the same size."); 10011 10012 APValue LHSValue; 10013 APValue RHSValue; 10014 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10015 if (!LHSOK && !Info.noteFailure()) 10016 return false; 10017 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10018 return false; 10019 10020 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10021 return false; 10022 10023 return Success(LHSValue, E); 10024 } 10025 10026 //===----------------------------------------------------------------------===// 10027 // Array Evaluation 10028 //===----------------------------------------------------------------------===// 10029 10030 namespace { 10031 class ArrayExprEvaluator 10032 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10033 const LValue &This; 10034 APValue &Result; 10035 public: 10036 10037 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10038 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10039 10040 bool Success(const APValue &V, const Expr *E) { 10041 assert(V.isArray() && "expected array"); 10042 Result = V; 10043 return true; 10044 } 10045 10046 bool ZeroInitialization(const Expr *E) { 10047 const ConstantArrayType *CAT = 10048 Info.Ctx.getAsConstantArrayType(E->getType()); 10049 if (!CAT) { 10050 if (E->getType()->isIncompleteArrayType()) { 10051 // We can be asked to zero-initialize a flexible array member; this 10052 // is represented as an ImplicitValueInitExpr of incomplete array 10053 // type. In this case, the array has zero elements. 10054 Result = APValue(APValue::UninitArray(), 0, 0); 10055 return true; 10056 } 10057 // FIXME: We could handle VLAs here. 10058 return Error(E); 10059 } 10060 10061 Result = APValue(APValue::UninitArray(), 0, 10062 CAT->getSize().getZExtValue()); 10063 if (!Result.hasArrayFiller()) return true; 10064 10065 // Zero-initialize all elements. 10066 LValue Subobject = This; 10067 Subobject.addArray(Info, E, CAT); 10068 ImplicitValueInitExpr VIE(CAT->getElementType()); 10069 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10070 } 10071 10072 bool VisitCallExpr(const CallExpr *E) { 10073 return handleCallExpr(E, Result, &This); 10074 } 10075 bool VisitInitListExpr(const InitListExpr *E, 10076 QualType AllocType = QualType()); 10077 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10078 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10079 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10080 const LValue &Subobject, 10081 APValue *Value, QualType Type); 10082 bool VisitStringLiteral(const StringLiteral *E, 10083 QualType AllocType = QualType()) { 10084 expandStringLiteral(Info, E, Result, AllocType); 10085 return true; 10086 } 10087 }; 10088 } // end anonymous namespace 10089 10090 static bool EvaluateArray(const Expr *E, const LValue &This, 10091 APValue &Result, EvalInfo &Info) { 10092 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10093 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10094 } 10095 10096 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10097 APValue &Result, const InitListExpr *ILE, 10098 QualType AllocType) { 10099 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10100 "not an array rvalue"); 10101 return ArrayExprEvaluator(Info, This, Result) 10102 .VisitInitListExpr(ILE, AllocType); 10103 } 10104 10105 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10106 APValue &Result, 10107 const CXXConstructExpr *CCE, 10108 QualType AllocType) { 10109 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10110 "not an array rvalue"); 10111 return ArrayExprEvaluator(Info, This, Result) 10112 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10113 } 10114 10115 // Return true iff the given array filler may depend on the element index. 10116 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10117 // For now, just allow non-class value-initialization and initialization 10118 // lists comprised of them. 10119 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10120 return false; 10121 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10122 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10123 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10124 return true; 10125 } 10126 return false; 10127 } 10128 return true; 10129 } 10130 10131 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10132 QualType AllocType) { 10133 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10134 AllocType.isNull() ? E->getType() : AllocType); 10135 if (!CAT) 10136 return Error(E); 10137 10138 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10139 // an appropriately-typed string literal enclosed in braces. 10140 if (E->isStringLiteralInit()) { 10141 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10142 // FIXME: Support ObjCEncodeExpr here once we support it in 10143 // ArrayExprEvaluator generally. 10144 if (!SL) 10145 return Error(E); 10146 return VisitStringLiteral(SL, AllocType); 10147 } 10148 10149 bool Success = true; 10150 10151 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10152 "zero-initialized array shouldn't have any initialized elts"); 10153 APValue Filler; 10154 if (Result.isArray() && Result.hasArrayFiller()) 10155 Filler = Result.getArrayFiller(); 10156 10157 unsigned NumEltsToInit = E->getNumInits(); 10158 unsigned NumElts = CAT->getSize().getZExtValue(); 10159 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10160 10161 // If the initializer might depend on the array index, run it for each 10162 // array element. 10163 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10164 NumEltsToInit = NumElts; 10165 10166 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10167 << NumEltsToInit << ".\n"); 10168 10169 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10170 10171 // If the array was previously zero-initialized, preserve the 10172 // zero-initialized values. 10173 if (Filler.hasValue()) { 10174 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10175 Result.getArrayInitializedElt(I) = Filler; 10176 if (Result.hasArrayFiller()) 10177 Result.getArrayFiller() = Filler; 10178 } 10179 10180 LValue Subobject = This; 10181 Subobject.addArray(Info, E, CAT); 10182 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10183 const Expr *Init = 10184 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10185 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10186 Info, Subobject, Init) || 10187 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10188 CAT->getElementType(), 1)) { 10189 if (!Info.noteFailure()) 10190 return false; 10191 Success = false; 10192 } 10193 } 10194 10195 if (!Result.hasArrayFiller()) 10196 return Success; 10197 10198 // If we get here, we have a trivial filler, which we can just evaluate 10199 // once and splat over the rest of the array elements. 10200 assert(FillerExpr && "no array filler for incomplete init list"); 10201 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10202 FillerExpr) && Success; 10203 } 10204 10205 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10206 LValue CommonLV; 10207 if (E->getCommonExpr() && 10208 !Evaluate(Info.CurrentCall->createTemporary( 10209 E->getCommonExpr(), 10210 getStorageType(Info.Ctx, E->getCommonExpr()), false, 10211 CommonLV), 10212 Info, E->getCommonExpr()->getSourceExpr())) 10213 return false; 10214 10215 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10216 10217 uint64_t Elements = CAT->getSize().getZExtValue(); 10218 Result = APValue(APValue::UninitArray(), Elements, Elements); 10219 10220 LValue Subobject = This; 10221 Subobject.addArray(Info, E, CAT); 10222 10223 bool Success = true; 10224 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10225 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10226 Info, Subobject, E->getSubExpr()) || 10227 !HandleLValueArrayAdjustment(Info, E, Subobject, 10228 CAT->getElementType(), 1)) { 10229 if (!Info.noteFailure()) 10230 return false; 10231 Success = false; 10232 } 10233 } 10234 10235 return Success; 10236 } 10237 10238 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10239 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10240 } 10241 10242 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10243 const LValue &Subobject, 10244 APValue *Value, 10245 QualType Type) { 10246 bool HadZeroInit = Value->hasValue(); 10247 10248 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10249 unsigned N = CAT->getSize().getZExtValue(); 10250 10251 // Preserve the array filler if we had prior zero-initialization. 10252 APValue Filler = 10253 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10254 : APValue(); 10255 10256 *Value = APValue(APValue::UninitArray(), N, N); 10257 10258 if (HadZeroInit) 10259 for (unsigned I = 0; I != N; ++I) 10260 Value->getArrayInitializedElt(I) = Filler; 10261 10262 // Initialize the elements. 10263 LValue ArrayElt = Subobject; 10264 ArrayElt.addArray(Info, E, CAT); 10265 for (unsigned I = 0; I != N; ++I) 10266 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10267 CAT->getElementType()) || 10268 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10269 CAT->getElementType(), 1)) 10270 return false; 10271 10272 return true; 10273 } 10274 10275 if (!Type->isRecordType()) 10276 return Error(E); 10277 10278 return RecordExprEvaluator(Info, Subobject, *Value) 10279 .VisitCXXConstructExpr(E, Type); 10280 } 10281 10282 //===----------------------------------------------------------------------===// 10283 // Integer Evaluation 10284 // 10285 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10286 // types and back in constant folding. Integer values are thus represented 10287 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10288 //===----------------------------------------------------------------------===// 10289 10290 namespace { 10291 class IntExprEvaluator 10292 : public ExprEvaluatorBase<IntExprEvaluator> { 10293 APValue &Result; 10294 public: 10295 IntExprEvaluator(EvalInfo &info, APValue &result) 10296 : ExprEvaluatorBaseTy(info), Result(result) {} 10297 10298 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10299 assert(E->getType()->isIntegralOrEnumerationType() && 10300 "Invalid evaluation result."); 10301 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10302 "Invalid evaluation result."); 10303 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10304 "Invalid evaluation result."); 10305 Result = APValue(SI); 10306 return true; 10307 } 10308 bool Success(const llvm::APSInt &SI, const Expr *E) { 10309 return Success(SI, E, Result); 10310 } 10311 10312 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10313 assert(E->getType()->isIntegralOrEnumerationType() && 10314 "Invalid evaluation result."); 10315 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10316 "Invalid evaluation result."); 10317 Result = APValue(APSInt(I)); 10318 Result.getInt().setIsUnsigned( 10319 E->getType()->isUnsignedIntegerOrEnumerationType()); 10320 return true; 10321 } 10322 bool Success(const llvm::APInt &I, const Expr *E) { 10323 return Success(I, E, Result); 10324 } 10325 10326 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10327 assert(E->getType()->isIntegralOrEnumerationType() && 10328 "Invalid evaluation result."); 10329 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10330 return true; 10331 } 10332 bool Success(uint64_t Value, const Expr *E) { 10333 return Success(Value, E, Result); 10334 } 10335 10336 bool Success(CharUnits Size, const Expr *E) { 10337 return Success(Size.getQuantity(), E); 10338 } 10339 10340 bool Success(const APValue &V, const Expr *E) { 10341 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10342 Result = V; 10343 return true; 10344 } 10345 return Success(V.getInt(), E); 10346 } 10347 10348 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10349 10350 //===--------------------------------------------------------------------===// 10351 // Visitor Methods 10352 //===--------------------------------------------------------------------===// 10353 10354 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10355 return Success(E->getValue(), E); 10356 } 10357 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10358 return Success(E->getValue(), E); 10359 } 10360 10361 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10362 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10363 if (CheckReferencedDecl(E, E->getDecl())) 10364 return true; 10365 10366 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10367 } 10368 bool VisitMemberExpr(const MemberExpr *E) { 10369 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10370 VisitIgnoredBaseExpression(E->getBase()); 10371 return true; 10372 } 10373 10374 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10375 } 10376 10377 bool VisitCallExpr(const CallExpr *E); 10378 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10379 bool VisitBinaryOperator(const BinaryOperator *E); 10380 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10381 bool VisitUnaryOperator(const UnaryOperator *E); 10382 10383 bool VisitCastExpr(const CastExpr* E); 10384 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10385 10386 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10387 return Success(E->getValue(), E); 10388 } 10389 10390 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10391 return Success(E->getValue(), E); 10392 } 10393 10394 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10395 if (Info.ArrayInitIndex == uint64_t(-1)) { 10396 // We were asked to evaluate this subexpression independent of the 10397 // enclosing ArrayInitLoopExpr. We can't do that. 10398 Info.FFDiag(E); 10399 return false; 10400 } 10401 return Success(Info.ArrayInitIndex, E); 10402 } 10403 10404 // Note, GNU defines __null as an integer, not a pointer. 10405 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10406 return ZeroInitialization(E); 10407 } 10408 10409 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10410 return Success(E->getValue(), E); 10411 } 10412 10413 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10414 return Success(E->getValue(), E); 10415 } 10416 10417 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10418 return Success(E->getValue(), E); 10419 } 10420 10421 bool VisitUnaryReal(const UnaryOperator *E); 10422 bool VisitUnaryImag(const UnaryOperator *E); 10423 10424 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10425 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10426 bool VisitSourceLocExpr(const SourceLocExpr *E); 10427 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10428 bool VisitRequiresExpr(const RequiresExpr *E); 10429 // FIXME: Missing: array subscript of vector, member of vector 10430 }; 10431 10432 class FixedPointExprEvaluator 10433 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10434 APValue &Result; 10435 10436 public: 10437 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10438 : ExprEvaluatorBaseTy(info), Result(result) {} 10439 10440 bool Success(const llvm::APInt &I, const Expr *E) { 10441 return Success( 10442 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10443 } 10444 10445 bool Success(uint64_t Value, const Expr *E) { 10446 return Success( 10447 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10448 } 10449 10450 bool Success(const APValue &V, const Expr *E) { 10451 return Success(V.getFixedPoint(), E); 10452 } 10453 10454 bool Success(const APFixedPoint &V, const Expr *E) { 10455 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10456 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10457 "Invalid evaluation result."); 10458 Result = APValue(V); 10459 return true; 10460 } 10461 10462 //===--------------------------------------------------------------------===// 10463 // Visitor Methods 10464 //===--------------------------------------------------------------------===// 10465 10466 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10467 return Success(E->getValue(), E); 10468 } 10469 10470 bool VisitCastExpr(const CastExpr *E); 10471 bool VisitUnaryOperator(const UnaryOperator *E); 10472 bool VisitBinaryOperator(const BinaryOperator *E); 10473 }; 10474 } // end anonymous namespace 10475 10476 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10477 /// produce either the integer value or a pointer. 10478 /// 10479 /// GCC has a heinous extension which folds casts between pointer types and 10480 /// pointer-sized integral types. We support this by allowing the evaluation of 10481 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10482 /// Some simple arithmetic on such values is supported (they are treated much 10483 /// like char*). 10484 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10485 EvalInfo &Info) { 10486 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10487 return IntExprEvaluator(Info, Result).Visit(E); 10488 } 10489 10490 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10491 APValue Val; 10492 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10493 return false; 10494 if (!Val.isInt()) { 10495 // FIXME: It would be better to produce the diagnostic for casting 10496 // a pointer to an integer. 10497 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10498 return false; 10499 } 10500 Result = Val.getInt(); 10501 return true; 10502 } 10503 10504 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10505 APValue Evaluated = E->EvaluateInContext( 10506 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10507 return Success(Evaluated, E); 10508 } 10509 10510 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10511 EvalInfo &Info) { 10512 if (E->getType()->isFixedPointType()) { 10513 APValue Val; 10514 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10515 return false; 10516 if (!Val.isFixedPoint()) 10517 return false; 10518 10519 Result = Val.getFixedPoint(); 10520 return true; 10521 } 10522 return false; 10523 } 10524 10525 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10526 EvalInfo &Info) { 10527 if (E->getType()->isIntegerType()) { 10528 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10529 APSInt Val; 10530 if (!EvaluateInteger(E, Val, Info)) 10531 return false; 10532 Result = APFixedPoint(Val, FXSema); 10533 return true; 10534 } else if (E->getType()->isFixedPointType()) { 10535 return EvaluateFixedPoint(E, Result, Info); 10536 } 10537 return false; 10538 } 10539 10540 /// Check whether the given declaration can be directly converted to an integral 10541 /// rvalue. If not, no diagnostic is produced; there are other things we can 10542 /// try. 10543 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10544 // Enums are integer constant exprs. 10545 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10546 // Check for signedness/width mismatches between E type and ECD value. 10547 bool SameSign = (ECD->getInitVal().isSigned() 10548 == E->getType()->isSignedIntegerOrEnumerationType()); 10549 bool SameWidth = (ECD->getInitVal().getBitWidth() 10550 == Info.Ctx.getIntWidth(E->getType())); 10551 if (SameSign && SameWidth) 10552 return Success(ECD->getInitVal(), E); 10553 else { 10554 // Get rid of mismatch (otherwise Success assertions will fail) 10555 // by computing a new value matching the type of E. 10556 llvm::APSInt Val = ECD->getInitVal(); 10557 if (!SameSign) 10558 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10559 if (!SameWidth) 10560 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10561 return Success(Val, E); 10562 } 10563 } 10564 return false; 10565 } 10566 10567 /// Values returned by __builtin_classify_type, chosen to match the values 10568 /// produced by GCC's builtin. 10569 enum class GCCTypeClass { 10570 None = -1, 10571 Void = 0, 10572 Integer = 1, 10573 // GCC reserves 2 for character types, but instead classifies them as 10574 // integers. 10575 Enum = 3, 10576 Bool = 4, 10577 Pointer = 5, 10578 // GCC reserves 6 for references, but appears to never use it (because 10579 // expressions never have reference type, presumably). 10580 PointerToDataMember = 7, 10581 RealFloat = 8, 10582 Complex = 9, 10583 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10584 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10585 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10586 // uses 12 for that purpose, same as for a class or struct. Maybe it 10587 // internally implements a pointer to member as a struct? Who knows. 10588 PointerToMemberFunction = 12, // Not a bug, see above. 10589 ClassOrStruct = 12, 10590 Union = 13, 10591 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10592 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10593 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10594 // literals. 10595 }; 10596 10597 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10598 /// as GCC. 10599 static GCCTypeClass 10600 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10601 assert(!T->isDependentType() && "unexpected dependent type"); 10602 10603 QualType CanTy = T.getCanonicalType(); 10604 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10605 10606 switch (CanTy->getTypeClass()) { 10607 #define TYPE(ID, BASE) 10608 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10609 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10610 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10611 #include "clang/AST/TypeNodes.inc" 10612 case Type::Auto: 10613 case Type::DeducedTemplateSpecialization: 10614 llvm_unreachable("unexpected non-canonical or dependent type"); 10615 10616 case Type::Builtin: 10617 switch (BT->getKind()) { 10618 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10619 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10620 case BuiltinType::ID: return GCCTypeClass::Integer; 10621 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10622 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10623 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10624 case BuiltinType::ID: break; 10625 #include "clang/AST/BuiltinTypes.def" 10626 case BuiltinType::Void: 10627 return GCCTypeClass::Void; 10628 10629 case BuiltinType::Bool: 10630 return GCCTypeClass::Bool; 10631 10632 case BuiltinType::Char_U: 10633 case BuiltinType::UChar: 10634 case BuiltinType::WChar_U: 10635 case BuiltinType::Char8: 10636 case BuiltinType::Char16: 10637 case BuiltinType::Char32: 10638 case BuiltinType::UShort: 10639 case BuiltinType::UInt: 10640 case BuiltinType::ULong: 10641 case BuiltinType::ULongLong: 10642 case BuiltinType::UInt128: 10643 return GCCTypeClass::Integer; 10644 10645 case BuiltinType::UShortAccum: 10646 case BuiltinType::UAccum: 10647 case BuiltinType::ULongAccum: 10648 case BuiltinType::UShortFract: 10649 case BuiltinType::UFract: 10650 case BuiltinType::ULongFract: 10651 case BuiltinType::SatUShortAccum: 10652 case BuiltinType::SatUAccum: 10653 case BuiltinType::SatULongAccum: 10654 case BuiltinType::SatUShortFract: 10655 case BuiltinType::SatUFract: 10656 case BuiltinType::SatULongFract: 10657 return GCCTypeClass::None; 10658 10659 case BuiltinType::NullPtr: 10660 10661 case BuiltinType::ObjCId: 10662 case BuiltinType::ObjCClass: 10663 case BuiltinType::ObjCSel: 10664 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10665 case BuiltinType::Id: 10666 #include "clang/Basic/OpenCLImageTypes.def" 10667 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10668 case BuiltinType::Id: 10669 #include "clang/Basic/OpenCLExtensionTypes.def" 10670 case BuiltinType::OCLSampler: 10671 case BuiltinType::OCLEvent: 10672 case BuiltinType::OCLClkEvent: 10673 case BuiltinType::OCLQueue: 10674 case BuiltinType::OCLReserveID: 10675 #define SVE_TYPE(Name, Id, SingletonId) \ 10676 case BuiltinType::Id: 10677 #include "clang/Basic/AArch64SVEACLETypes.def" 10678 return GCCTypeClass::None; 10679 10680 case BuiltinType::Dependent: 10681 llvm_unreachable("unexpected dependent type"); 10682 }; 10683 llvm_unreachable("unexpected placeholder type"); 10684 10685 case Type::Enum: 10686 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10687 10688 case Type::Pointer: 10689 case Type::ConstantArray: 10690 case Type::VariableArray: 10691 case Type::IncompleteArray: 10692 case Type::FunctionNoProto: 10693 case Type::FunctionProto: 10694 return GCCTypeClass::Pointer; 10695 10696 case Type::MemberPointer: 10697 return CanTy->isMemberDataPointerType() 10698 ? GCCTypeClass::PointerToDataMember 10699 : GCCTypeClass::PointerToMemberFunction; 10700 10701 case Type::Complex: 10702 return GCCTypeClass::Complex; 10703 10704 case Type::Record: 10705 return CanTy->isUnionType() ? GCCTypeClass::Union 10706 : GCCTypeClass::ClassOrStruct; 10707 10708 case Type::Atomic: 10709 // GCC classifies _Atomic T the same as T. 10710 return EvaluateBuiltinClassifyType( 10711 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10712 10713 case Type::BlockPointer: 10714 case Type::Vector: 10715 case Type::ExtVector: 10716 case Type::ConstantMatrix: 10717 case Type::ObjCObject: 10718 case Type::ObjCInterface: 10719 case Type::ObjCObjectPointer: 10720 case Type::Pipe: 10721 case Type::ExtInt: 10722 // GCC classifies vectors as None. We follow its lead and classify all 10723 // other types that don't fit into the regular classification the same way. 10724 return GCCTypeClass::None; 10725 10726 case Type::LValueReference: 10727 case Type::RValueReference: 10728 llvm_unreachable("invalid type for expression"); 10729 } 10730 10731 llvm_unreachable("unexpected type class"); 10732 } 10733 10734 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10735 /// as GCC. 10736 static GCCTypeClass 10737 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10738 // If no argument was supplied, default to None. This isn't 10739 // ideal, however it is what gcc does. 10740 if (E->getNumArgs() == 0) 10741 return GCCTypeClass::None; 10742 10743 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10744 // being an ICE, but still folds it to a constant using the type of the first 10745 // argument. 10746 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10747 } 10748 10749 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10750 /// __builtin_constant_p when applied to the given pointer. 10751 /// 10752 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10753 /// or it points to the first character of a string literal. 10754 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10755 APValue::LValueBase Base = LV.getLValueBase(); 10756 if (Base.isNull()) { 10757 // A null base is acceptable. 10758 return true; 10759 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10760 if (!isa<StringLiteral>(E)) 10761 return false; 10762 return LV.getLValueOffset().isZero(); 10763 } else if (Base.is<TypeInfoLValue>()) { 10764 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10765 // evaluate to true. 10766 return true; 10767 } else { 10768 // Any other base is not constant enough for GCC. 10769 return false; 10770 } 10771 } 10772 10773 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10774 /// GCC as we can manage. 10775 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10776 // This evaluation is not permitted to have side-effects, so evaluate it in 10777 // a speculative evaluation context. 10778 SpeculativeEvaluationRAII SpeculativeEval(Info); 10779 10780 // Constant-folding is always enabled for the operand of __builtin_constant_p 10781 // (even when the enclosing evaluation context otherwise requires a strict 10782 // language-specific constant expression). 10783 FoldConstant Fold(Info, true); 10784 10785 QualType ArgType = Arg->getType(); 10786 10787 // __builtin_constant_p always has one operand. The rules which gcc follows 10788 // are not precisely documented, but are as follows: 10789 // 10790 // - If the operand is of integral, floating, complex or enumeration type, 10791 // and can be folded to a known value of that type, it returns 1. 10792 // - If the operand can be folded to a pointer to the first character 10793 // of a string literal (or such a pointer cast to an integral type) 10794 // or to a null pointer or an integer cast to a pointer, it returns 1. 10795 // 10796 // Otherwise, it returns 0. 10797 // 10798 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10799 // its support for this did not work prior to GCC 9 and is not yet well 10800 // understood. 10801 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10802 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10803 ArgType->isNullPtrType()) { 10804 APValue V; 10805 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 10806 Fold.keepDiagnostics(); 10807 return false; 10808 } 10809 10810 // For a pointer (possibly cast to integer), there are special rules. 10811 if (V.getKind() == APValue::LValue) 10812 return EvaluateBuiltinConstantPForLValue(V); 10813 10814 // Otherwise, any constant value is good enough. 10815 return V.hasValue(); 10816 } 10817 10818 // Anything else isn't considered to be sufficiently constant. 10819 return false; 10820 } 10821 10822 /// Retrieves the "underlying object type" of the given expression, 10823 /// as used by __builtin_object_size. 10824 static QualType getObjectType(APValue::LValueBase B) { 10825 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10826 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10827 return VD->getType(); 10828 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10829 if (isa<CompoundLiteralExpr>(E)) 10830 return E->getType(); 10831 } else if (B.is<TypeInfoLValue>()) { 10832 return B.getTypeInfoType(); 10833 } else if (B.is<DynamicAllocLValue>()) { 10834 return B.getDynamicAllocType(); 10835 } 10836 10837 return QualType(); 10838 } 10839 10840 /// A more selective version of E->IgnoreParenCasts for 10841 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10842 /// to change the type of E. 10843 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10844 /// 10845 /// Always returns an RValue with a pointer representation. 10846 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10847 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10848 10849 auto *NoParens = E->IgnoreParens(); 10850 auto *Cast = dyn_cast<CastExpr>(NoParens); 10851 if (Cast == nullptr) 10852 return NoParens; 10853 10854 // We only conservatively allow a few kinds of casts, because this code is 10855 // inherently a simple solution that seeks to support the common case. 10856 auto CastKind = Cast->getCastKind(); 10857 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10858 CastKind != CK_AddressSpaceConversion) 10859 return NoParens; 10860 10861 auto *SubExpr = Cast->getSubExpr(); 10862 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10863 return NoParens; 10864 return ignorePointerCastsAndParens(SubExpr); 10865 } 10866 10867 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10868 /// record layout. e.g. 10869 /// struct { struct { int a, b; } fst, snd; } obj; 10870 /// obj.fst // no 10871 /// obj.snd // yes 10872 /// obj.fst.a // no 10873 /// obj.fst.b // no 10874 /// obj.snd.a // no 10875 /// obj.snd.b // yes 10876 /// 10877 /// Please note: this function is specialized for how __builtin_object_size 10878 /// views "objects". 10879 /// 10880 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10881 /// correct result, it will always return true. 10882 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10883 assert(!LVal.Designator.Invalid); 10884 10885 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10886 const RecordDecl *Parent = FD->getParent(); 10887 Invalid = Parent->isInvalidDecl(); 10888 if (Invalid || Parent->isUnion()) 10889 return true; 10890 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10891 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10892 }; 10893 10894 auto &Base = LVal.getLValueBase(); 10895 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10896 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10897 bool Invalid; 10898 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10899 return Invalid; 10900 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10901 for (auto *FD : IFD->chain()) { 10902 bool Invalid; 10903 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10904 return Invalid; 10905 } 10906 } 10907 } 10908 10909 unsigned I = 0; 10910 QualType BaseType = getType(Base); 10911 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10912 // If we don't know the array bound, conservatively assume we're looking at 10913 // the final array element. 10914 ++I; 10915 if (BaseType->isIncompleteArrayType()) 10916 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10917 else 10918 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10919 } 10920 10921 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10922 const auto &Entry = LVal.Designator.Entries[I]; 10923 if (BaseType->isArrayType()) { 10924 // Because __builtin_object_size treats arrays as objects, we can ignore 10925 // the index iff this is the last array in the Designator. 10926 if (I + 1 == E) 10927 return true; 10928 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10929 uint64_t Index = Entry.getAsArrayIndex(); 10930 if (Index + 1 != CAT->getSize()) 10931 return false; 10932 BaseType = CAT->getElementType(); 10933 } else if (BaseType->isAnyComplexType()) { 10934 const auto *CT = BaseType->castAs<ComplexType>(); 10935 uint64_t Index = Entry.getAsArrayIndex(); 10936 if (Index != 1) 10937 return false; 10938 BaseType = CT->getElementType(); 10939 } else if (auto *FD = getAsField(Entry)) { 10940 bool Invalid; 10941 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10942 return Invalid; 10943 BaseType = FD->getType(); 10944 } else { 10945 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10946 return false; 10947 } 10948 } 10949 return true; 10950 } 10951 10952 /// Tests to see if the LValue has a user-specified designator (that isn't 10953 /// necessarily valid). Note that this always returns 'true' if the LValue has 10954 /// an unsized array as its first designator entry, because there's currently no 10955 /// way to tell if the user typed *foo or foo[0]. 10956 static bool refersToCompleteObject(const LValue &LVal) { 10957 if (LVal.Designator.Invalid) 10958 return false; 10959 10960 if (!LVal.Designator.Entries.empty()) 10961 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10962 10963 if (!LVal.InvalidBase) 10964 return true; 10965 10966 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10967 // the LValueBase. 10968 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10969 return !E || !isa<MemberExpr>(E); 10970 } 10971 10972 /// Attempts to detect a user writing into a piece of memory that's impossible 10973 /// to figure out the size of by just using types. 10974 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10975 const SubobjectDesignator &Designator = LVal.Designator; 10976 // Notes: 10977 // - Users can only write off of the end when we have an invalid base. Invalid 10978 // bases imply we don't know where the memory came from. 10979 // - We used to be a bit more aggressive here; we'd only be conservative if 10980 // the array at the end was flexible, or if it had 0 or 1 elements. This 10981 // broke some common standard library extensions (PR30346), but was 10982 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10983 // with some sort of list. OTOH, it seems that GCC is always 10984 // conservative with the last element in structs (if it's an array), so our 10985 // current behavior is more compatible than an explicit list approach would 10986 // be. 10987 return LVal.InvalidBase && 10988 Designator.Entries.size() == Designator.MostDerivedPathLength && 10989 Designator.MostDerivedIsArrayElement && 10990 isDesignatorAtObjectEnd(Ctx, LVal); 10991 } 10992 10993 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10994 /// Fails if the conversion would cause loss of precision. 10995 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10996 CharUnits &Result) { 10997 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10998 if (Int.ugt(CharUnitsMax)) 10999 return false; 11000 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11001 return true; 11002 } 11003 11004 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11005 /// determine how many bytes exist from the beginning of the object to either 11006 /// the end of the current subobject, or the end of the object itself, depending 11007 /// on what the LValue looks like + the value of Type. 11008 /// 11009 /// If this returns false, the value of Result is undefined. 11010 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11011 unsigned Type, const LValue &LVal, 11012 CharUnits &EndOffset) { 11013 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11014 11015 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11016 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11017 return false; 11018 return HandleSizeof(Info, ExprLoc, Ty, Result); 11019 }; 11020 11021 // We want to evaluate the size of the entire object. This is a valid fallback 11022 // for when Type=1 and the designator is invalid, because we're asked for an 11023 // upper-bound. 11024 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11025 // Type=3 wants a lower bound, so we can't fall back to this. 11026 if (Type == 3 && !DetermineForCompleteObject) 11027 return false; 11028 11029 llvm::APInt APEndOffset; 11030 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11031 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11032 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11033 11034 if (LVal.InvalidBase) 11035 return false; 11036 11037 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11038 return CheckedHandleSizeof(BaseTy, EndOffset); 11039 } 11040 11041 // We want to evaluate the size of a subobject. 11042 const SubobjectDesignator &Designator = LVal.Designator; 11043 11044 // The following is a moderately common idiom in C: 11045 // 11046 // struct Foo { int a; char c[1]; }; 11047 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11048 // strcpy(&F->c[0], Bar); 11049 // 11050 // In order to not break too much legacy code, we need to support it. 11051 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11052 // If we can resolve this to an alloc_size call, we can hand that back, 11053 // because we know for certain how many bytes there are to write to. 11054 llvm::APInt APEndOffset; 11055 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11056 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11057 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11058 11059 // If we cannot determine the size of the initial allocation, then we can't 11060 // given an accurate upper-bound. However, we are still able to give 11061 // conservative lower-bounds for Type=3. 11062 if (Type == 1) 11063 return false; 11064 } 11065 11066 CharUnits BytesPerElem; 11067 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11068 return false; 11069 11070 // According to the GCC documentation, we want the size of the subobject 11071 // denoted by the pointer. But that's not quite right -- what we actually 11072 // want is the size of the immediately-enclosing array, if there is one. 11073 int64_t ElemsRemaining; 11074 if (Designator.MostDerivedIsArrayElement && 11075 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11076 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11077 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11078 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11079 } else { 11080 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11081 } 11082 11083 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11084 return true; 11085 } 11086 11087 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11088 /// returns true and stores the result in @p Size. 11089 /// 11090 /// If @p WasError is non-null, this will report whether the failure to evaluate 11091 /// is to be treated as an Error in IntExprEvaluator. 11092 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11093 EvalInfo &Info, uint64_t &Size) { 11094 // Determine the denoted object. 11095 LValue LVal; 11096 { 11097 // The operand of __builtin_object_size is never evaluated for side-effects. 11098 // If there are any, but we can determine the pointed-to object anyway, then 11099 // ignore the side-effects. 11100 SpeculativeEvaluationRAII SpeculativeEval(Info); 11101 IgnoreSideEffectsRAII Fold(Info); 11102 11103 if (E->isGLValue()) { 11104 // It's possible for us to be given GLValues if we're called via 11105 // Expr::tryEvaluateObjectSize. 11106 APValue RVal; 11107 if (!EvaluateAsRValue(Info, E, RVal)) 11108 return false; 11109 LVal.setFrom(Info.Ctx, RVal); 11110 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11111 /*InvalidBaseOK=*/true)) 11112 return false; 11113 } 11114 11115 // If we point to before the start of the object, there are no accessible 11116 // bytes. 11117 if (LVal.getLValueOffset().isNegative()) { 11118 Size = 0; 11119 return true; 11120 } 11121 11122 CharUnits EndOffset; 11123 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11124 return false; 11125 11126 // If we've fallen outside of the end offset, just pretend there's nothing to 11127 // write to/read from. 11128 if (EndOffset <= LVal.getLValueOffset()) 11129 Size = 0; 11130 else 11131 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11132 return true; 11133 } 11134 11135 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11136 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11137 return VisitBuiltinCallExpr(E, BuiltinOp); 11138 11139 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11140 } 11141 11142 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11143 APValue &Val, APSInt &Alignment) { 11144 QualType SrcTy = E->getArg(0)->getType(); 11145 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11146 return false; 11147 // Even though we are evaluating integer expressions we could get a pointer 11148 // argument for the __builtin_is_aligned() case. 11149 if (SrcTy->isPointerType()) { 11150 LValue Ptr; 11151 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11152 return false; 11153 Ptr.moveInto(Val); 11154 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11155 Info.FFDiag(E->getArg(0)); 11156 return false; 11157 } else { 11158 APSInt SrcInt; 11159 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11160 return false; 11161 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11162 "Bit widths must be the same"); 11163 Val = APValue(SrcInt); 11164 } 11165 assert(Val.hasValue()); 11166 return true; 11167 } 11168 11169 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11170 unsigned BuiltinOp) { 11171 switch (BuiltinOp) { 11172 default: 11173 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11174 11175 case Builtin::BI__builtin_dynamic_object_size: 11176 case Builtin::BI__builtin_object_size: { 11177 // The type was checked when we built the expression. 11178 unsigned Type = 11179 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11180 assert(Type <= 3 && "unexpected type"); 11181 11182 uint64_t Size; 11183 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11184 return Success(Size, E); 11185 11186 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11187 return Success((Type & 2) ? 0 : -1, E); 11188 11189 // Expression had no side effects, but we couldn't statically determine the 11190 // size of the referenced object. 11191 switch (Info.EvalMode) { 11192 case EvalInfo::EM_ConstantExpression: 11193 case EvalInfo::EM_ConstantFold: 11194 case EvalInfo::EM_IgnoreSideEffects: 11195 // Leave it to IR generation. 11196 return Error(E); 11197 case EvalInfo::EM_ConstantExpressionUnevaluated: 11198 // Reduce it to a constant now. 11199 return Success((Type & 2) ? 0 : -1, E); 11200 } 11201 11202 llvm_unreachable("unexpected EvalMode"); 11203 } 11204 11205 case Builtin::BI__builtin_os_log_format_buffer_size: { 11206 analyze_os_log::OSLogBufferLayout Layout; 11207 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11208 return Success(Layout.size().getQuantity(), E); 11209 } 11210 11211 case Builtin::BI__builtin_is_aligned: { 11212 APValue Src; 11213 APSInt Alignment; 11214 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11215 return false; 11216 if (Src.isLValue()) { 11217 // If we evaluated a pointer, check the minimum known alignment. 11218 LValue Ptr; 11219 Ptr.setFrom(Info.Ctx, Src); 11220 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11221 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11222 // We can return true if the known alignment at the computed offset is 11223 // greater than the requested alignment. 11224 assert(PtrAlign.isPowerOfTwo()); 11225 assert(Alignment.isPowerOf2()); 11226 if (PtrAlign.getQuantity() >= Alignment) 11227 return Success(1, E); 11228 // If the alignment is not known to be sufficient, some cases could still 11229 // be aligned at run time. However, if the requested alignment is less or 11230 // equal to the base alignment and the offset is not aligned, we know that 11231 // the run-time value can never be aligned. 11232 if (BaseAlignment.getQuantity() >= Alignment && 11233 PtrAlign.getQuantity() < Alignment) 11234 return Success(0, E); 11235 // Otherwise we can't infer whether the value is sufficiently aligned. 11236 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11237 // in cases where we can't fully evaluate the pointer. 11238 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11239 << Alignment; 11240 return false; 11241 } 11242 assert(Src.isInt()); 11243 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11244 } 11245 case Builtin::BI__builtin_align_up: { 11246 APValue Src; 11247 APSInt Alignment; 11248 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11249 return false; 11250 if (!Src.isInt()) 11251 return Error(E); 11252 APSInt AlignedVal = 11253 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11254 Src.getInt().isUnsigned()); 11255 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11256 return Success(AlignedVal, E); 11257 } 11258 case Builtin::BI__builtin_align_down: { 11259 APValue Src; 11260 APSInt Alignment; 11261 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11262 return false; 11263 if (!Src.isInt()) 11264 return Error(E); 11265 APSInt AlignedVal = 11266 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11267 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11268 return Success(AlignedVal, E); 11269 } 11270 11271 case Builtin::BI__builtin_bitreverse8: 11272 case Builtin::BI__builtin_bitreverse16: 11273 case Builtin::BI__builtin_bitreverse32: 11274 case Builtin::BI__builtin_bitreverse64: { 11275 APSInt Val; 11276 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11277 return false; 11278 11279 return Success(Val.reverseBits(), E); 11280 } 11281 11282 case Builtin::BI__builtin_bswap16: 11283 case Builtin::BI__builtin_bswap32: 11284 case Builtin::BI__builtin_bswap64: { 11285 APSInt Val; 11286 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11287 return false; 11288 11289 return Success(Val.byteSwap(), E); 11290 } 11291 11292 case Builtin::BI__builtin_classify_type: 11293 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11294 11295 case Builtin::BI__builtin_clrsb: 11296 case Builtin::BI__builtin_clrsbl: 11297 case Builtin::BI__builtin_clrsbll: { 11298 APSInt Val; 11299 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11300 return false; 11301 11302 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11303 } 11304 11305 case Builtin::BI__builtin_clz: 11306 case Builtin::BI__builtin_clzl: 11307 case Builtin::BI__builtin_clzll: 11308 case Builtin::BI__builtin_clzs: { 11309 APSInt Val; 11310 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11311 return false; 11312 if (!Val) 11313 return Error(E); 11314 11315 return Success(Val.countLeadingZeros(), E); 11316 } 11317 11318 case Builtin::BI__builtin_constant_p: { 11319 const Expr *Arg = E->getArg(0); 11320 if (EvaluateBuiltinConstantP(Info, Arg)) 11321 return Success(true, E); 11322 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11323 // Outside a constant context, eagerly evaluate to false in the presence 11324 // of side-effects in order to avoid -Wunsequenced false-positives in 11325 // a branch on __builtin_constant_p(expr). 11326 return Success(false, E); 11327 } 11328 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11329 return false; 11330 } 11331 11332 case Builtin::BI__builtin_is_constant_evaluated: { 11333 const auto *Callee = Info.CurrentCall->getCallee(); 11334 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11335 (Info.CallStackDepth == 1 || 11336 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11337 Callee->getIdentifier() && 11338 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11339 // FIXME: Find a better way to avoid duplicated diagnostics. 11340 if (Info.EvalStatus.Diag) 11341 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11342 : Info.CurrentCall->CallLoc, 11343 diag::warn_is_constant_evaluated_always_true_constexpr) 11344 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11345 : "std::is_constant_evaluated"); 11346 } 11347 11348 return Success(Info.InConstantContext, E); 11349 } 11350 11351 case Builtin::BI__builtin_ctz: 11352 case Builtin::BI__builtin_ctzl: 11353 case Builtin::BI__builtin_ctzll: 11354 case Builtin::BI__builtin_ctzs: { 11355 APSInt Val; 11356 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11357 return false; 11358 if (!Val) 11359 return Error(E); 11360 11361 return Success(Val.countTrailingZeros(), E); 11362 } 11363 11364 case Builtin::BI__builtin_eh_return_data_regno: { 11365 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11366 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11367 return Success(Operand, E); 11368 } 11369 11370 case Builtin::BI__builtin_expect: 11371 case Builtin::BI__builtin_expect_with_probability: 11372 return Visit(E->getArg(0)); 11373 11374 case Builtin::BI__builtin_ffs: 11375 case Builtin::BI__builtin_ffsl: 11376 case Builtin::BI__builtin_ffsll: { 11377 APSInt Val; 11378 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11379 return false; 11380 11381 unsigned N = Val.countTrailingZeros(); 11382 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11383 } 11384 11385 case Builtin::BI__builtin_fpclassify: { 11386 APFloat Val(0.0); 11387 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11388 return false; 11389 unsigned Arg; 11390 switch (Val.getCategory()) { 11391 case APFloat::fcNaN: Arg = 0; break; 11392 case APFloat::fcInfinity: Arg = 1; break; 11393 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11394 case APFloat::fcZero: Arg = 4; break; 11395 } 11396 return Visit(E->getArg(Arg)); 11397 } 11398 11399 case Builtin::BI__builtin_isinf_sign: { 11400 APFloat Val(0.0); 11401 return EvaluateFloat(E->getArg(0), Val, Info) && 11402 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11403 } 11404 11405 case Builtin::BI__builtin_isinf: { 11406 APFloat Val(0.0); 11407 return EvaluateFloat(E->getArg(0), Val, Info) && 11408 Success(Val.isInfinity() ? 1 : 0, E); 11409 } 11410 11411 case Builtin::BI__builtin_isfinite: { 11412 APFloat Val(0.0); 11413 return EvaluateFloat(E->getArg(0), Val, Info) && 11414 Success(Val.isFinite() ? 1 : 0, E); 11415 } 11416 11417 case Builtin::BI__builtin_isnan: { 11418 APFloat Val(0.0); 11419 return EvaluateFloat(E->getArg(0), Val, Info) && 11420 Success(Val.isNaN() ? 1 : 0, E); 11421 } 11422 11423 case Builtin::BI__builtin_isnormal: { 11424 APFloat Val(0.0); 11425 return EvaluateFloat(E->getArg(0), Val, Info) && 11426 Success(Val.isNormal() ? 1 : 0, E); 11427 } 11428 11429 case Builtin::BI__builtin_parity: 11430 case Builtin::BI__builtin_parityl: 11431 case Builtin::BI__builtin_parityll: { 11432 APSInt Val; 11433 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11434 return false; 11435 11436 return Success(Val.countPopulation() % 2, E); 11437 } 11438 11439 case Builtin::BI__builtin_popcount: 11440 case Builtin::BI__builtin_popcountl: 11441 case Builtin::BI__builtin_popcountll: { 11442 APSInt Val; 11443 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11444 return false; 11445 11446 return Success(Val.countPopulation(), E); 11447 } 11448 11449 case Builtin::BI__builtin_rotateleft8: 11450 case Builtin::BI__builtin_rotateleft16: 11451 case Builtin::BI__builtin_rotateleft32: 11452 case Builtin::BI__builtin_rotateleft64: 11453 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11454 case Builtin::BI_rotl16: 11455 case Builtin::BI_rotl: 11456 case Builtin::BI_lrotl: 11457 case Builtin::BI_rotl64: { 11458 APSInt Val, Amt; 11459 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11460 !EvaluateInteger(E->getArg(1), Amt, Info)) 11461 return false; 11462 11463 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11464 } 11465 11466 case Builtin::BI__builtin_rotateright8: 11467 case Builtin::BI__builtin_rotateright16: 11468 case Builtin::BI__builtin_rotateright32: 11469 case Builtin::BI__builtin_rotateright64: 11470 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11471 case Builtin::BI_rotr16: 11472 case Builtin::BI_rotr: 11473 case Builtin::BI_lrotr: 11474 case Builtin::BI_rotr64: { 11475 APSInt Val, Amt; 11476 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11477 !EvaluateInteger(E->getArg(1), Amt, Info)) 11478 return false; 11479 11480 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11481 } 11482 11483 case Builtin::BIstrlen: 11484 case Builtin::BIwcslen: 11485 // A call to strlen is not a constant expression. 11486 if (Info.getLangOpts().CPlusPlus11) 11487 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11488 << /*isConstexpr*/0 << /*isConstructor*/0 11489 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11490 else 11491 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11492 LLVM_FALLTHROUGH; 11493 case Builtin::BI__builtin_strlen: 11494 case Builtin::BI__builtin_wcslen: { 11495 // As an extension, we support __builtin_strlen() as a constant expression, 11496 // and support folding strlen() to a constant. 11497 LValue String; 11498 if (!EvaluatePointer(E->getArg(0), String, Info)) 11499 return false; 11500 11501 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11502 11503 // Fast path: if it's a string literal, search the string value. 11504 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11505 String.getLValueBase().dyn_cast<const Expr *>())) { 11506 // The string literal may have embedded null characters. Find the first 11507 // one and truncate there. 11508 StringRef Str = S->getBytes(); 11509 int64_t Off = String.Offset.getQuantity(); 11510 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11511 S->getCharByteWidth() == 1 && 11512 // FIXME: Add fast-path for wchar_t too. 11513 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11514 Str = Str.substr(Off); 11515 11516 StringRef::size_type Pos = Str.find(0); 11517 if (Pos != StringRef::npos) 11518 Str = Str.substr(0, Pos); 11519 11520 return Success(Str.size(), E); 11521 } 11522 11523 // Fall through to slow path to issue appropriate diagnostic. 11524 } 11525 11526 // Slow path: scan the bytes of the string looking for the terminating 0. 11527 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11528 APValue Char; 11529 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11530 !Char.isInt()) 11531 return false; 11532 if (!Char.getInt()) 11533 return Success(Strlen, E); 11534 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11535 return false; 11536 } 11537 } 11538 11539 case Builtin::BIstrcmp: 11540 case Builtin::BIwcscmp: 11541 case Builtin::BIstrncmp: 11542 case Builtin::BIwcsncmp: 11543 case Builtin::BImemcmp: 11544 case Builtin::BIbcmp: 11545 case Builtin::BIwmemcmp: 11546 // A call to strlen is not a constant expression. 11547 if (Info.getLangOpts().CPlusPlus11) 11548 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11549 << /*isConstexpr*/0 << /*isConstructor*/0 11550 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11551 else 11552 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11553 LLVM_FALLTHROUGH; 11554 case Builtin::BI__builtin_strcmp: 11555 case Builtin::BI__builtin_wcscmp: 11556 case Builtin::BI__builtin_strncmp: 11557 case Builtin::BI__builtin_wcsncmp: 11558 case Builtin::BI__builtin_memcmp: 11559 case Builtin::BI__builtin_bcmp: 11560 case Builtin::BI__builtin_wmemcmp: { 11561 LValue String1, String2; 11562 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11563 !EvaluatePointer(E->getArg(1), String2, Info)) 11564 return false; 11565 11566 uint64_t MaxLength = uint64_t(-1); 11567 if (BuiltinOp != Builtin::BIstrcmp && 11568 BuiltinOp != Builtin::BIwcscmp && 11569 BuiltinOp != Builtin::BI__builtin_strcmp && 11570 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11571 APSInt N; 11572 if (!EvaluateInteger(E->getArg(2), N, Info)) 11573 return false; 11574 MaxLength = N.getExtValue(); 11575 } 11576 11577 // Empty substrings compare equal by definition. 11578 if (MaxLength == 0u) 11579 return Success(0, E); 11580 11581 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11582 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11583 String1.Designator.Invalid || String2.Designator.Invalid) 11584 return false; 11585 11586 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11587 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11588 11589 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11590 BuiltinOp == Builtin::BIbcmp || 11591 BuiltinOp == Builtin::BI__builtin_memcmp || 11592 BuiltinOp == Builtin::BI__builtin_bcmp; 11593 11594 assert(IsRawByte || 11595 (Info.Ctx.hasSameUnqualifiedType( 11596 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11597 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11598 11599 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11600 // 'char8_t', but no other types. 11601 if (IsRawByte && 11602 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11603 // FIXME: Consider using our bit_cast implementation to support this. 11604 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11605 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11606 << CharTy1 << CharTy2; 11607 return false; 11608 } 11609 11610 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11611 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11612 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11613 Char1.isInt() && Char2.isInt(); 11614 }; 11615 const auto &AdvanceElems = [&] { 11616 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11617 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11618 }; 11619 11620 bool StopAtNull = 11621 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11622 BuiltinOp != Builtin::BIwmemcmp && 11623 BuiltinOp != Builtin::BI__builtin_memcmp && 11624 BuiltinOp != Builtin::BI__builtin_bcmp && 11625 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11626 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11627 BuiltinOp == Builtin::BIwcsncmp || 11628 BuiltinOp == Builtin::BIwmemcmp || 11629 BuiltinOp == Builtin::BI__builtin_wcscmp || 11630 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11631 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11632 11633 for (; MaxLength; --MaxLength) { 11634 APValue Char1, Char2; 11635 if (!ReadCurElems(Char1, Char2)) 11636 return false; 11637 if (Char1.getInt().ne(Char2.getInt())) { 11638 if (IsWide) // wmemcmp compares with wchar_t signedness. 11639 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11640 // memcmp always compares unsigned chars. 11641 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11642 } 11643 if (StopAtNull && !Char1.getInt()) 11644 return Success(0, E); 11645 assert(!(StopAtNull && !Char2.getInt())); 11646 if (!AdvanceElems()) 11647 return false; 11648 } 11649 // We hit the strncmp / memcmp limit. 11650 return Success(0, E); 11651 } 11652 11653 case Builtin::BI__atomic_always_lock_free: 11654 case Builtin::BI__atomic_is_lock_free: 11655 case Builtin::BI__c11_atomic_is_lock_free: { 11656 APSInt SizeVal; 11657 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11658 return false; 11659 11660 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11661 // of two less than or equal to the maximum inline atomic width, we know it 11662 // is lock-free. If the size isn't a power of two, or greater than the 11663 // maximum alignment where we promote atomics, we know it is not lock-free 11664 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11665 // the answer can only be determined at runtime; for example, 16-byte 11666 // atomics have lock-free implementations on some, but not all, 11667 // x86-64 processors. 11668 11669 // Check power-of-two. 11670 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11671 if (Size.isPowerOfTwo()) { 11672 // Check against inlining width. 11673 unsigned InlineWidthBits = 11674 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11675 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11676 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11677 Size == CharUnits::One() || 11678 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11679 Expr::NPC_NeverValueDependent)) 11680 // OK, we will inline appropriately-aligned operations of this size, 11681 // and _Atomic(T) is appropriately-aligned. 11682 return Success(1, E); 11683 11684 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11685 castAs<PointerType>()->getPointeeType(); 11686 if (!PointeeType->isIncompleteType() && 11687 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11688 // OK, we will inline operations on this object. 11689 return Success(1, E); 11690 } 11691 } 11692 } 11693 11694 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11695 Success(0, E) : Error(E); 11696 } 11697 case Builtin::BIomp_is_initial_device: 11698 // We can decide statically which value the runtime would return if called. 11699 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11700 case Builtin::BI__builtin_add_overflow: 11701 case Builtin::BI__builtin_sub_overflow: 11702 case Builtin::BI__builtin_mul_overflow: 11703 case Builtin::BI__builtin_sadd_overflow: 11704 case Builtin::BI__builtin_uadd_overflow: 11705 case Builtin::BI__builtin_uaddl_overflow: 11706 case Builtin::BI__builtin_uaddll_overflow: 11707 case Builtin::BI__builtin_usub_overflow: 11708 case Builtin::BI__builtin_usubl_overflow: 11709 case Builtin::BI__builtin_usubll_overflow: 11710 case Builtin::BI__builtin_umul_overflow: 11711 case Builtin::BI__builtin_umull_overflow: 11712 case Builtin::BI__builtin_umulll_overflow: 11713 case Builtin::BI__builtin_saddl_overflow: 11714 case Builtin::BI__builtin_saddll_overflow: 11715 case Builtin::BI__builtin_ssub_overflow: 11716 case Builtin::BI__builtin_ssubl_overflow: 11717 case Builtin::BI__builtin_ssubll_overflow: 11718 case Builtin::BI__builtin_smul_overflow: 11719 case Builtin::BI__builtin_smull_overflow: 11720 case Builtin::BI__builtin_smulll_overflow: { 11721 LValue ResultLValue; 11722 APSInt LHS, RHS; 11723 11724 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11725 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11726 !EvaluateInteger(E->getArg(1), RHS, Info) || 11727 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11728 return false; 11729 11730 APSInt Result; 11731 bool DidOverflow = false; 11732 11733 // If the types don't have to match, enlarge all 3 to the largest of them. 11734 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11735 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11736 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11737 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11738 ResultType->isSignedIntegerOrEnumerationType(); 11739 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11740 ResultType->isSignedIntegerOrEnumerationType(); 11741 uint64_t LHSSize = LHS.getBitWidth(); 11742 uint64_t RHSSize = RHS.getBitWidth(); 11743 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11744 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11745 11746 // Add an additional bit if the signedness isn't uniformly agreed to. We 11747 // could do this ONLY if there is a signed and an unsigned that both have 11748 // MaxBits, but the code to check that is pretty nasty. The issue will be 11749 // caught in the shrink-to-result later anyway. 11750 if (IsSigned && !AllSigned) 11751 ++MaxBits; 11752 11753 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11754 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11755 Result = APSInt(MaxBits, !IsSigned); 11756 } 11757 11758 // Find largest int. 11759 switch (BuiltinOp) { 11760 default: 11761 llvm_unreachable("Invalid value for BuiltinOp"); 11762 case Builtin::BI__builtin_add_overflow: 11763 case Builtin::BI__builtin_sadd_overflow: 11764 case Builtin::BI__builtin_saddl_overflow: 11765 case Builtin::BI__builtin_saddll_overflow: 11766 case Builtin::BI__builtin_uadd_overflow: 11767 case Builtin::BI__builtin_uaddl_overflow: 11768 case Builtin::BI__builtin_uaddll_overflow: 11769 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11770 : LHS.uadd_ov(RHS, DidOverflow); 11771 break; 11772 case Builtin::BI__builtin_sub_overflow: 11773 case Builtin::BI__builtin_ssub_overflow: 11774 case Builtin::BI__builtin_ssubl_overflow: 11775 case Builtin::BI__builtin_ssubll_overflow: 11776 case Builtin::BI__builtin_usub_overflow: 11777 case Builtin::BI__builtin_usubl_overflow: 11778 case Builtin::BI__builtin_usubll_overflow: 11779 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11780 : LHS.usub_ov(RHS, DidOverflow); 11781 break; 11782 case Builtin::BI__builtin_mul_overflow: 11783 case Builtin::BI__builtin_smul_overflow: 11784 case Builtin::BI__builtin_smull_overflow: 11785 case Builtin::BI__builtin_smulll_overflow: 11786 case Builtin::BI__builtin_umul_overflow: 11787 case Builtin::BI__builtin_umull_overflow: 11788 case Builtin::BI__builtin_umulll_overflow: 11789 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11790 : LHS.umul_ov(RHS, DidOverflow); 11791 break; 11792 } 11793 11794 // In the case where multiple sizes are allowed, truncate and see if 11795 // the values are the same. 11796 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11797 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11798 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11799 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11800 // since it will give us the behavior of a TruncOrSelf in the case where 11801 // its parameter <= its size. We previously set Result to be at least the 11802 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11803 // will work exactly like TruncOrSelf. 11804 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11805 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11806 11807 if (!APSInt::isSameValue(Temp, Result)) 11808 DidOverflow = true; 11809 Result = Temp; 11810 } 11811 11812 APValue APV{Result}; 11813 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11814 return false; 11815 return Success(DidOverflow, E); 11816 } 11817 } 11818 } 11819 11820 /// Determine whether this is a pointer past the end of the complete 11821 /// object referred to by the lvalue. 11822 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11823 const LValue &LV) { 11824 // A null pointer can be viewed as being "past the end" but we don't 11825 // choose to look at it that way here. 11826 if (!LV.getLValueBase()) 11827 return false; 11828 11829 // If the designator is valid and refers to a subobject, we're not pointing 11830 // past the end. 11831 if (!LV.getLValueDesignator().Invalid && 11832 !LV.getLValueDesignator().isOnePastTheEnd()) 11833 return false; 11834 11835 // A pointer to an incomplete type might be past-the-end if the type's size is 11836 // zero. We cannot tell because the type is incomplete. 11837 QualType Ty = getType(LV.getLValueBase()); 11838 if (Ty->isIncompleteType()) 11839 return true; 11840 11841 // We're a past-the-end pointer if we point to the byte after the object, 11842 // no matter what our type or path is. 11843 auto Size = Ctx.getTypeSizeInChars(Ty); 11844 return LV.getLValueOffset() == Size; 11845 } 11846 11847 namespace { 11848 11849 /// Data recursive integer evaluator of certain binary operators. 11850 /// 11851 /// We use a data recursive algorithm for binary operators so that we are able 11852 /// to handle extreme cases of chained binary operators without causing stack 11853 /// overflow. 11854 class DataRecursiveIntBinOpEvaluator { 11855 struct EvalResult { 11856 APValue Val; 11857 bool Failed; 11858 11859 EvalResult() : Failed(false) { } 11860 11861 void swap(EvalResult &RHS) { 11862 Val.swap(RHS.Val); 11863 Failed = RHS.Failed; 11864 RHS.Failed = false; 11865 } 11866 }; 11867 11868 struct Job { 11869 const Expr *E; 11870 EvalResult LHSResult; // meaningful only for binary operator expression. 11871 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11872 11873 Job() = default; 11874 Job(Job &&) = default; 11875 11876 void startSpeculativeEval(EvalInfo &Info) { 11877 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11878 } 11879 11880 private: 11881 SpeculativeEvaluationRAII SpecEvalRAII; 11882 }; 11883 11884 SmallVector<Job, 16> Queue; 11885 11886 IntExprEvaluator &IntEval; 11887 EvalInfo &Info; 11888 APValue &FinalResult; 11889 11890 public: 11891 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11892 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11893 11894 /// True if \param E is a binary operator that we are going to handle 11895 /// data recursively. 11896 /// We handle binary operators that are comma, logical, or that have operands 11897 /// with integral or enumeration type. 11898 static bool shouldEnqueue(const BinaryOperator *E) { 11899 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11900 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11901 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11902 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11903 } 11904 11905 bool Traverse(const BinaryOperator *E) { 11906 enqueue(E); 11907 EvalResult PrevResult; 11908 while (!Queue.empty()) 11909 process(PrevResult); 11910 11911 if (PrevResult.Failed) return false; 11912 11913 FinalResult.swap(PrevResult.Val); 11914 return true; 11915 } 11916 11917 private: 11918 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11919 return IntEval.Success(Value, E, Result); 11920 } 11921 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11922 return IntEval.Success(Value, E, Result); 11923 } 11924 bool Error(const Expr *E) { 11925 return IntEval.Error(E); 11926 } 11927 bool Error(const Expr *E, diag::kind D) { 11928 return IntEval.Error(E, D); 11929 } 11930 11931 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11932 return Info.CCEDiag(E, D); 11933 } 11934 11935 // Returns true if visiting the RHS is necessary, false otherwise. 11936 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11937 bool &SuppressRHSDiags); 11938 11939 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11940 const BinaryOperator *E, APValue &Result); 11941 11942 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11943 Result.Failed = !Evaluate(Result.Val, Info, E); 11944 if (Result.Failed) 11945 Result.Val = APValue(); 11946 } 11947 11948 void process(EvalResult &Result); 11949 11950 void enqueue(const Expr *E) { 11951 E = E->IgnoreParens(); 11952 Queue.resize(Queue.size()+1); 11953 Queue.back().E = E; 11954 Queue.back().Kind = Job::AnyExprKind; 11955 } 11956 }; 11957 11958 } 11959 11960 bool DataRecursiveIntBinOpEvaluator:: 11961 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11962 bool &SuppressRHSDiags) { 11963 if (E->getOpcode() == BO_Comma) { 11964 // Ignore LHS but note if we could not evaluate it. 11965 if (LHSResult.Failed) 11966 return Info.noteSideEffect(); 11967 return true; 11968 } 11969 11970 if (E->isLogicalOp()) { 11971 bool LHSAsBool; 11972 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11973 // We were able to evaluate the LHS, see if we can get away with not 11974 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11975 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11976 Success(LHSAsBool, E, LHSResult.Val); 11977 return false; // Ignore RHS 11978 } 11979 } else { 11980 LHSResult.Failed = true; 11981 11982 // Since we weren't able to evaluate the left hand side, it 11983 // might have had side effects. 11984 if (!Info.noteSideEffect()) 11985 return false; 11986 11987 // We can't evaluate the LHS; however, sometimes the result 11988 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11989 // Don't ignore RHS and suppress diagnostics from this arm. 11990 SuppressRHSDiags = true; 11991 } 11992 11993 return true; 11994 } 11995 11996 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11997 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11998 11999 if (LHSResult.Failed && !Info.noteFailure()) 12000 return false; // Ignore RHS; 12001 12002 return true; 12003 } 12004 12005 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12006 bool IsSub) { 12007 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12008 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12009 // offsets. 12010 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12011 CharUnits &Offset = LVal.getLValueOffset(); 12012 uint64_t Offset64 = Offset.getQuantity(); 12013 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12014 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12015 : Offset64 + Index64); 12016 } 12017 12018 bool DataRecursiveIntBinOpEvaluator:: 12019 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12020 const BinaryOperator *E, APValue &Result) { 12021 if (E->getOpcode() == BO_Comma) { 12022 if (RHSResult.Failed) 12023 return false; 12024 Result = RHSResult.Val; 12025 return true; 12026 } 12027 12028 if (E->isLogicalOp()) { 12029 bool lhsResult, rhsResult; 12030 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12031 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12032 12033 if (LHSIsOK) { 12034 if (RHSIsOK) { 12035 if (E->getOpcode() == BO_LOr) 12036 return Success(lhsResult || rhsResult, E, Result); 12037 else 12038 return Success(lhsResult && rhsResult, E, Result); 12039 } 12040 } else { 12041 if (RHSIsOK) { 12042 // We can't evaluate the LHS; however, sometimes the result 12043 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12044 if (rhsResult == (E->getOpcode() == BO_LOr)) 12045 return Success(rhsResult, E, Result); 12046 } 12047 } 12048 12049 return false; 12050 } 12051 12052 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12053 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12054 12055 if (LHSResult.Failed || RHSResult.Failed) 12056 return false; 12057 12058 const APValue &LHSVal = LHSResult.Val; 12059 const APValue &RHSVal = RHSResult.Val; 12060 12061 // Handle cases like (unsigned long)&a + 4. 12062 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12063 Result = LHSVal; 12064 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12065 return true; 12066 } 12067 12068 // Handle cases like 4 + (unsigned long)&a 12069 if (E->getOpcode() == BO_Add && 12070 RHSVal.isLValue() && LHSVal.isInt()) { 12071 Result = RHSVal; 12072 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12073 return true; 12074 } 12075 12076 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12077 // Handle (intptr_t)&&A - (intptr_t)&&B. 12078 if (!LHSVal.getLValueOffset().isZero() || 12079 !RHSVal.getLValueOffset().isZero()) 12080 return false; 12081 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12082 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12083 if (!LHSExpr || !RHSExpr) 12084 return false; 12085 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12086 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12087 if (!LHSAddrExpr || !RHSAddrExpr) 12088 return false; 12089 // Make sure both labels come from the same function. 12090 if (LHSAddrExpr->getLabel()->getDeclContext() != 12091 RHSAddrExpr->getLabel()->getDeclContext()) 12092 return false; 12093 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12094 return true; 12095 } 12096 12097 // All the remaining cases expect both operands to be an integer 12098 if (!LHSVal.isInt() || !RHSVal.isInt()) 12099 return Error(E); 12100 12101 // Set up the width and signedness manually, in case it can't be deduced 12102 // from the operation we're performing. 12103 // FIXME: Don't do this in the cases where we can deduce it. 12104 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12105 E->getType()->isUnsignedIntegerOrEnumerationType()); 12106 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12107 RHSVal.getInt(), Value)) 12108 return false; 12109 return Success(Value, E, Result); 12110 } 12111 12112 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12113 Job &job = Queue.back(); 12114 12115 switch (job.Kind) { 12116 case Job::AnyExprKind: { 12117 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12118 if (shouldEnqueue(Bop)) { 12119 job.Kind = Job::BinOpKind; 12120 enqueue(Bop->getLHS()); 12121 return; 12122 } 12123 } 12124 12125 EvaluateExpr(job.E, Result); 12126 Queue.pop_back(); 12127 return; 12128 } 12129 12130 case Job::BinOpKind: { 12131 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12132 bool SuppressRHSDiags = false; 12133 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12134 Queue.pop_back(); 12135 return; 12136 } 12137 if (SuppressRHSDiags) 12138 job.startSpeculativeEval(Info); 12139 job.LHSResult.swap(Result); 12140 job.Kind = Job::BinOpVisitedLHSKind; 12141 enqueue(Bop->getRHS()); 12142 return; 12143 } 12144 12145 case Job::BinOpVisitedLHSKind: { 12146 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12147 EvalResult RHS; 12148 RHS.swap(Result); 12149 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12150 Queue.pop_back(); 12151 return; 12152 } 12153 } 12154 12155 llvm_unreachable("Invalid Job::Kind!"); 12156 } 12157 12158 namespace { 12159 /// Used when we determine that we should fail, but can keep evaluating prior to 12160 /// noting that we had a failure. 12161 class DelayedNoteFailureRAII { 12162 EvalInfo &Info; 12163 bool NoteFailure; 12164 12165 public: 12166 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12167 : Info(Info), NoteFailure(NoteFailure) {} 12168 ~DelayedNoteFailureRAII() { 12169 if (NoteFailure) { 12170 bool ContinueAfterFailure = Info.noteFailure(); 12171 (void)ContinueAfterFailure; 12172 assert(ContinueAfterFailure && 12173 "Shouldn't have kept evaluating on failure."); 12174 } 12175 } 12176 }; 12177 12178 enum class CmpResult { 12179 Unequal, 12180 Less, 12181 Equal, 12182 Greater, 12183 Unordered, 12184 }; 12185 } 12186 12187 template <class SuccessCB, class AfterCB> 12188 static bool 12189 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12190 SuccessCB &&Success, AfterCB &&DoAfter) { 12191 assert(E->isComparisonOp() && "expected comparison operator"); 12192 assert((E->getOpcode() == BO_Cmp || 12193 E->getType()->isIntegralOrEnumerationType()) && 12194 "unsupported binary expression evaluation"); 12195 auto Error = [&](const Expr *E) { 12196 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12197 return false; 12198 }; 12199 12200 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12201 bool IsEquality = E->isEqualityOp(); 12202 12203 QualType LHSTy = E->getLHS()->getType(); 12204 QualType RHSTy = E->getRHS()->getType(); 12205 12206 if (LHSTy->isIntegralOrEnumerationType() && 12207 RHSTy->isIntegralOrEnumerationType()) { 12208 APSInt LHS, RHS; 12209 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12210 if (!LHSOK && !Info.noteFailure()) 12211 return false; 12212 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12213 return false; 12214 if (LHS < RHS) 12215 return Success(CmpResult::Less, E); 12216 if (LHS > RHS) 12217 return Success(CmpResult::Greater, E); 12218 return Success(CmpResult::Equal, E); 12219 } 12220 12221 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12222 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12223 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12224 12225 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12226 if (!LHSOK && !Info.noteFailure()) 12227 return false; 12228 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12229 return false; 12230 if (LHSFX < RHSFX) 12231 return Success(CmpResult::Less, E); 12232 if (LHSFX > RHSFX) 12233 return Success(CmpResult::Greater, E); 12234 return Success(CmpResult::Equal, E); 12235 } 12236 12237 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12238 ComplexValue LHS, RHS; 12239 bool LHSOK; 12240 if (E->isAssignmentOp()) { 12241 LValue LV; 12242 EvaluateLValue(E->getLHS(), LV, Info); 12243 LHSOK = false; 12244 } else if (LHSTy->isRealFloatingType()) { 12245 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12246 if (LHSOK) { 12247 LHS.makeComplexFloat(); 12248 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12249 } 12250 } else { 12251 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12252 } 12253 if (!LHSOK && !Info.noteFailure()) 12254 return false; 12255 12256 if (E->getRHS()->getType()->isRealFloatingType()) { 12257 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12258 return false; 12259 RHS.makeComplexFloat(); 12260 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12261 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12262 return false; 12263 12264 if (LHS.isComplexFloat()) { 12265 APFloat::cmpResult CR_r = 12266 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12267 APFloat::cmpResult CR_i = 12268 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12269 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12270 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12271 } else { 12272 assert(IsEquality && "invalid complex comparison"); 12273 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12274 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12275 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12276 } 12277 } 12278 12279 if (LHSTy->isRealFloatingType() && 12280 RHSTy->isRealFloatingType()) { 12281 APFloat RHS(0.0), LHS(0.0); 12282 12283 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12284 if (!LHSOK && !Info.noteFailure()) 12285 return false; 12286 12287 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12288 return false; 12289 12290 assert(E->isComparisonOp() && "Invalid binary operator!"); 12291 auto GetCmpRes = [&]() { 12292 switch (LHS.compare(RHS)) { 12293 case APFloat::cmpEqual: 12294 return CmpResult::Equal; 12295 case APFloat::cmpLessThan: 12296 return CmpResult::Less; 12297 case APFloat::cmpGreaterThan: 12298 return CmpResult::Greater; 12299 case APFloat::cmpUnordered: 12300 return CmpResult::Unordered; 12301 } 12302 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12303 }; 12304 return Success(GetCmpRes(), E); 12305 } 12306 12307 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12308 LValue LHSValue, RHSValue; 12309 12310 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12311 if (!LHSOK && !Info.noteFailure()) 12312 return false; 12313 12314 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12315 return false; 12316 12317 // Reject differing bases from the normal codepath; we special-case 12318 // comparisons to null. 12319 if (!HasSameBase(LHSValue, RHSValue)) { 12320 // Inequalities and subtractions between unrelated pointers have 12321 // unspecified or undefined behavior. 12322 if (!IsEquality) { 12323 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12324 return false; 12325 } 12326 // A constant address may compare equal to the address of a symbol. 12327 // The one exception is that address of an object cannot compare equal 12328 // to a null pointer constant. 12329 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12330 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12331 return Error(E); 12332 // It's implementation-defined whether distinct literals will have 12333 // distinct addresses. In clang, the result of such a comparison is 12334 // unspecified, so it is not a constant expression. However, we do know 12335 // that the address of a literal will be non-null. 12336 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12337 LHSValue.Base && RHSValue.Base) 12338 return Error(E); 12339 // We can't tell whether weak symbols will end up pointing to the same 12340 // object. 12341 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12342 return Error(E); 12343 // We can't compare the address of the start of one object with the 12344 // past-the-end address of another object, per C++ DR1652. 12345 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12346 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12347 (RHSValue.Base && RHSValue.Offset.isZero() && 12348 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12349 return Error(E); 12350 // We can't tell whether an object is at the same address as another 12351 // zero sized object. 12352 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12353 (LHSValue.Base && isZeroSized(RHSValue))) 12354 return Error(E); 12355 return Success(CmpResult::Unequal, E); 12356 } 12357 12358 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12359 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12360 12361 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12362 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12363 12364 // C++11 [expr.rel]p3: 12365 // Pointers to void (after pointer conversions) can be compared, with a 12366 // result defined as follows: If both pointers represent the same 12367 // address or are both the null pointer value, the result is true if the 12368 // operator is <= or >= and false otherwise; otherwise the result is 12369 // unspecified. 12370 // We interpret this as applying to pointers to *cv* void. 12371 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12372 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12373 12374 // C++11 [expr.rel]p2: 12375 // - If two pointers point to non-static data members of the same object, 12376 // or to subobjects or array elements fo such members, recursively, the 12377 // pointer to the later declared member compares greater provided the 12378 // two members have the same access control and provided their class is 12379 // not a union. 12380 // [...] 12381 // - Otherwise pointer comparisons are unspecified. 12382 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12383 bool WasArrayIndex; 12384 unsigned Mismatch = FindDesignatorMismatch( 12385 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12386 // At the point where the designators diverge, the comparison has a 12387 // specified value if: 12388 // - we are comparing array indices 12389 // - we are comparing fields of a union, or fields with the same access 12390 // Otherwise, the result is unspecified and thus the comparison is not a 12391 // constant expression. 12392 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12393 Mismatch < RHSDesignator.Entries.size()) { 12394 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12395 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12396 if (!LF && !RF) 12397 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12398 else if (!LF) 12399 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12400 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12401 << RF->getParent() << RF; 12402 else if (!RF) 12403 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12404 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12405 << LF->getParent() << LF; 12406 else if (!LF->getParent()->isUnion() && 12407 LF->getAccess() != RF->getAccess()) 12408 Info.CCEDiag(E, 12409 diag::note_constexpr_pointer_comparison_differing_access) 12410 << LF << LF->getAccess() << RF << RF->getAccess() 12411 << LF->getParent(); 12412 } 12413 } 12414 12415 // The comparison here must be unsigned, and performed with the same 12416 // width as the pointer. 12417 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12418 uint64_t CompareLHS = LHSOffset.getQuantity(); 12419 uint64_t CompareRHS = RHSOffset.getQuantity(); 12420 assert(PtrSize <= 64 && "Unexpected pointer width"); 12421 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12422 CompareLHS &= Mask; 12423 CompareRHS &= Mask; 12424 12425 // If there is a base and this is a relational operator, we can only 12426 // compare pointers within the object in question; otherwise, the result 12427 // depends on where the object is located in memory. 12428 if (!LHSValue.Base.isNull() && IsRelational) { 12429 QualType BaseTy = getType(LHSValue.Base); 12430 if (BaseTy->isIncompleteType()) 12431 return Error(E); 12432 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12433 uint64_t OffsetLimit = Size.getQuantity(); 12434 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12435 return Error(E); 12436 } 12437 12438 if (CompareLHS < CompareRHS) 12439 return Success(CmpResult::Less, E); 12440 if (CompareLHS > CompareRHS) 12441 return Success(CmpResult::Greater, E); 12442 return Success(CmpResult::Equal, E); 12443 } 12444 12445 if (LHSTy->isMemberPointerType()) { 12446 assert(IsEquality && "unexpected member pointer operation"); 12447 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12448 12449 MemberPtr LHSValue, RHSValue; 12450 12451 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12452 if (!LHSOK && !Info.noteFailure()) 12453 return false; 12454 12455 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12456 return false; 12457 12458 // C++11 [expr.eq]p2: 12459 // If both operands are null, they compare equal. Otherwise if only one is 12460 // null, they compare unequal. 12461 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12462 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12463 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12464 } 12465 12466 // Otherwise if either is a pointer to a virtual member function, the 12467 // result is unspecified. 12468 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12469 if (MD->isVirtual()) 12470 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12471 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12472 if (MD->isVirtual()) 12473 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12474 12475 // Otherwise they compare equal if and only if they would refer to the 12476 // same member of the same most derived object or the same subobject if 12477 // they were dereferenced with a hypothetical object of the associated 12478 // class type. 12479 bool Equal = LHSValue == RHSValue; 12480 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12481 } 12482 12483 if (LHSTy->isNullPtrType()) { 12484 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12485 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12486 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12487 // are compared, the result is true of the operator is <=, >= or ==, and 12488 // false otherwise. 12489 return Success(CmpResult::Equal, E); 12490 } 12491 12492 return DoAfter(); 12493 } 12494 12495 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12496 if (!CheckLiteralType(Info, E)) 12497 return false; 12498 12499 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12500 ComparisonCategoryResult CCR; 12501 switch (CR) { 12502 case CmpResult::Unequal: 12503 llvm_unreachable("should never produce Unequal for three-way comparison"); 12504 case CmpResult::Less: 12505 CCR = ComparisonCategoryResult::Less; 12506 break; 12507 case CmpResult::Equal: 12508 CCR = ComparisonCategoryResult::Equal; 12509 break; 12510 case CmpResult::Greater: 12511 CCR = ComparisonCategoryResult::Greater; 12512 break; 12513 case CmpResult::Unordered: 12514 CCR = ComparisonCategoryResult::Unordered; 12515 break; 12516 } 12517 // Evaluation succeeded. Lookup the information for the comparison category 12518 // type and fetch the VarDecl for the result. 12519 const ComparisonCategoryInfo &CmpInfo = 12520 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12521 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12522 // Check and evaluate the result as a constant expression. 12523 LValue LV; 12524 LV.set(VD); 12525 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12526 return false; 12527 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12528 }; 12529 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12530 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12531 }); 12532 } 12533 12534 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12535 // We don't call noteFailure immediately because the assignment happens after 12536 // we evaluate LHS and RHS. 12537 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12538 return Error(E); 12539 12540 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12541 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12542 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12543 12544 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12545 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12546 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12547 12548 if (E->isComparisonOp()) { 12549 // Evaluate builtin binary comparisons by evaluating them as three-way 12550 // comparisons and then translating the result. 12551 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12552 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12553 "should only produce Unequal for equality comparisons"); 12554 bool IsEqual = CR == CmpResult::Equal, 12555 IsLess = CR == CmpResult::Less, 12556 IsGreater = CR == CmpResult::Greater; 12557 auto Op = E->getOpcode(); 12558 switch (Op) { 12559 default: 12560 llvm_unreachable("unsupported binary operator"); 12561 case BO_EQ: 12562 case BO_NE: 12563 return Success(IsEqual == (Op == BO_EQ), E); 12564 case BO_LT: 12565 return Success(IsLess, E); 12566 case BO_GT: 12567 return Success(IsGreater, E); 12568 case BO_LE: 12569 return Success(IsEqual || IsLess, E); 12570 case BO_GE: 12571 return Success(IsEqual || IsGreater, E); 12572 } 12573 }; 12574 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12575 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12576 }); 12577 } 12578 12579 QualType LHSTy = E->getLHS()->getType(); 12580 QualType RHSTy = E->getRHS()->getType(); 12581 12582 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12583 E->getOpcode() == BO_Sub) { 12584 LValue LHSValue, RHSValue; 12585 12586 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12587 if (!LHSOK && !Info.noteFailure()) 12588 return false; 12589 12590 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12591 return false; 12592 12593 // Reject differing bases from the normal codepath; we special-case 12594 // comparisons to null. 12595 if (!HasSameBase(LHSValue, RHSValue)) { 12596 // Handle &&A - &&B. 12597 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12598 return Error(E); 12599 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12600 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12601 if (!LHSExpr || !RHSExpr) 12602 return Error(E); 12603 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12604 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12605 if (!LHSAddrExpr || !RHSAddrExpr) 12606 return Error(E); 12607 // Make sure both labels come from the same function. 12608 if (LHSAddrExpr->getLabel()->getDeclContext() != 12609 RHSAddrExpr->getLabel()->getDeclContext()) 12610 return Error(E); 12611 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12612 } 12613 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12614 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12615 12616 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12617 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12618 12619 // C++11 [expr.add]p6: 12620 // Unless both pointers point to elements of the same array object, or 12621 // one past the last element of the array object, the behavior is 12622 // undefined. 12623 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12624 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12625 RHSDesignator)) 12626 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12627 12628 QualType Type = E->getLHS()->getType(); 12629 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12630 12631 CharUnits ElementSize; 12632 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12633 return false; 12634 12635 // As an extension, a type may have zero size (empty struct or union in 12636 // C, array of zero length). Pointer subtraction in such cases has 12637 // undefined behavior, so is not constant. 12638 if (ElementSize.isZero()) { 12639 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12640 << ElementType; 12641 return false; 12642 } 12643 12644 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12645 // and produce incorrect results when it overflows. Such behavior 12646 // appears to be non-conforming, but is common, so perhaps we should 12647 // assume the standard intended for such cases to be undefined behavior 12648 // and check for them. 12649 12650 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12651 // overflow in the final conversion to ptrdiff_t. 12652 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12653 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12654 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12655 false); 12656 APSInt TrueResult = (LHS - RHS) / ElemSize; 12657 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12658 12659 if (Result.extend(65) != TrueResult && 12660 !HandleOverflow(Info, E, TrueResult, E->getType())) 12661 return false; 12662 return Success(Result, E); 12663 } 12664 12665 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12666 } 12667 12668 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12669 /// a result as the expression's type. 12670 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12671 const UnaryExprOrTypeTraitExpr *E) { 12672 switch(E->getKind()) { 12673 case UETT_PreferredAlignOf: 12674 case UETT_AlignOf: { 12675 if (E->isArgumentType()) 12676 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12677 E); 12678 else 12679 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12680 E); 12681 } 12682 12683 case UETT_VecStep: { 12684 QualType Ty = E->getTypeOfArgument(); 12685 12686 if (Ty->isVectorType()) { 12687 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12688 12689 // The vec_step built-in functions that take a 3-component 12690 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12691 if (n == 3) 12692 n = 4; 12693 12694 return Success(n, E); 12695 } else 12696 return Success(1, E); 12697 } 12698 12699 case UETT_SizeOf: { 12700 QualType SrcTy = E->getTypeOfArgument(); 12701 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12702 // the result is the size of the referenced type." 12703 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12704 SrcTy = Ref->getPointeeType(); 12705 12706 CharUnits Sizeof; 12707 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12708 return false; 12709 return Success(Sizeof, E); 12710 } 12711 case UETT_OpenMPRequiredSimdAlign: 12712 assert(E->isArgumentType()); 12713 return Success( 12714 Info.Ctx.toCharUnitsFromBits( 12715 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12716 .getQuantity(), 12717 E); 12718 } 12719 12720 llvm_unreachable("unknown expr/type trait"); 12721 } 12722 12723 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12724 CharUnits Result; 12725 unsigned n = OOE->getNumComponents(); 12726 if (n == 0) 12727 return Error(OOE); 12728 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12729 for (unsigned i = 0; i != n; ++i) { 12730 OffsetOfNode ON = OOE->getComponent(i); 12731 switch (ON.getKind()) { 12732 case OffsetOfNode::Array: { 12733 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12734 APSInt IdxResult; 12735 if (!EvaluateInteger(Idx, IdxResult, Info)) 12736 return false; 12737 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12738 if (!AT) 12739 return Error(OOE); 12740 CurrentType = AT->getElementType(); 12741 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12742 Result += IdxResult.getSExtValue() * ElementSize; 12743 break; 12744 } 12745 12746 case OffsetOfNode::Field: { 12747 FieldDecl *MemberDecl = ON.getField(); 12748 const RecordType *RT = CurrentType->getAs<RecordType>(); 12749 if (!RT) 12750 return Error(OOE); 12751 RecordDecl *RD = RT->getDecl(); 12752 if (RD->isInvalidDecl()) return false; 12753 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12754 unsigned i = MemberDecl->getFieldIndex(); 12755 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12756 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12757 CurrentType = MemberDecl->getType().getNonReferenceType(); 12758 break; 12759 } 12760 12761 case OffsetOfNode::Identifier: 12762 llvm_unreachable("dependent __builtin_offsetof"); 12763 12764 case OffsetOfNode::Base: { 12765 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12766 if (BaseSpec->isVirtual()) 12767 return Error(OOE); 12768 12769 // Find the layout of the class whose base we are looking into. 12770 const RecordType *RT = CurrentType->getAs<RecordType>(); 12771 if (!RT) 12772 return Error(OOE); 12773 RecordDecl *RD = RT->getDecl(); 12774 if (RD->isInvalidDecl()) return false; 12775 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12776 12777 // Find the base class itself. 12778 CurrentType = BaseSpec->getType(); 12779 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12780 if (!BaseRT) 12781 return Error(OOE); 12782 12783 // Add the offset to the base. 12784 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12785 break; 12786 } 12787 } 12788 } 12789 return Success(Result, OOE); 12790 } 12791 12792 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12793 switch (E->getOpcode()) { 12794 default: 12795 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12796 // See C99 6.6p3. 12797 return Error(E); 12798 case UO_Extension: 12799 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12800 // If so, we could clear the diagnostic ID. 12801 return Visit(E->getSubExpr()); 12802 case UO_Plus: 12803 // The result is just the value. 12804 return Visit(E->getSubExpr()); 12805 case UO_Minus: { 12806 if (!Visit(E->getSubExpr())) 12807 return false; 12808 if (!Result.isInt()) return Error(E); 12809 const APSInt &Value = Result.getInt(); 12810 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12811 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12812 E->getType())) 12813 return false; 12814 return Success(-Value, E); 12815 } 12816 case UO_Not: { 12817 if (!Visit(E->getSubExpr())) 12818 return false; 12819 if (!Result.isInt()) return Error(E); 12820 return Success(~Result.getInt(), E); 12821 } 12822 case UO_LNot: { 12823 bool bres; 12824 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12825 return false; 12826 return Success(!bres, E); 12827 } 12828 } 12829 } 12830 12831 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12832 /// result type is integer. 12833 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12834 const Expr *SubExpr = E->getSubExpr(); 12835 QualType DestType = E->getType(); 12836 QualType SrcType = SubExpr->getType(); 12837 12838 switch (E->getCastKind()) { 12839 case CK_BaseToDerived: 12840 case CK_DerivedToBase: 12841 case CK_UncheckedDerivedToBase: 12842 case CK_Dynamic: 12843 case CK_ToUnion: 12844 case CK_ArrayToPointerDecay: 12845 case CK_FunctionToPointerDecay: 12846 case CK_NullToPointer: 12847 case CK_NullToMemberPointer: 12848 case CK_BaseToDerivedMemberPointer: 12849 case CK_DerivedToBaseMemberPointer: 12850 case CK_ReinterpretMemberPointer: 12851 case CK_ConstructorConversion: 12852 case CK_IntegralToPointer: 12853 case CK_ToVoid: 12854 case CK_VectorSplat: 12855 case CK_IntegralToFloating: 12856 case CK_FloatingCast: 12857 case CK_CPointerToObjCPointerCast: 12858 case CK_BlockPointerToObjCPointerCast: 12859 case CK_AnyPointerToBlockPointerCast: 12860 case CK_ObjCObjectLValueCast: 12861 case CK_FloatingRealToComplex: 12862 case CK_FloatingComplexToReal: 12863 case CK_FloatingComplexCast: 12864 case CK_FloatingComplexToIntegralComplex: 12865 case CK_IntegralRealToComplex: 12866 case CK_IntegralComplexCast: 12867 case CK_IntegralComplexToFloatingComplex: 12868 case CK_BuiltinFnToFnPtr: 12869 case CK_ZeroToOCLOpaqueType: 12870 case CK_NonAtomicToAtomic: 12871 case CK_AddressSpaceConversion: 12872 case CK_IntToOCLSampler: 12873 case CK_FixedPointCast: 12874 case CK_IntegralToFixedPoint: 12875 llvm_unreachable("invalid cast kind for integral value"); 12876 12877 case CK_BitCast: 12878 case CK_Dependent: 12879 case CK_LValueBitCast: 12880 case CK_ARCProduceObject: 12881 case CK_ARCConsumeObject: 12882 case CK_ARCReclaimReturnedObject: 12883 case CK_ARCExtendBlockObject: 12884 case CK_CopyAndAutoreleaseBlockObject: 12885 return Error(E); 12886 12887 case CK_UserDefinedConversion: 12888 case CK_LValueToRValue: 12889 case CK_AtomicToNonAtomic: 12890 case CK_NoOp: 12891 case CK_LValueToRValueBitCast: 12892 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12893 12894 case CK_MemberPointerToBoolean: 12895 case CK_PointerToBoolean: 12896 case CK_IntegralToBoolean: 12897 case CK_FloatingToBoolean: 12898 case CK_BooleanToSignedIntegral: 12899 case CK_FloatingComplexToBoolean: 12900 case CK_IntegralComplexToBoolean: { 12901 bool BoolResult; 12902 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12903 return false; 12904 uint64_t IntResult = BoolResult; 12905 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12906 IntResult = (uint64_t)-1; 12907 return Success(IntResult, E); 12908 } 12909 12910 case CK_FixedPointToIntegral: { 12911 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12912 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12913 return false; 12914 bool Overflowed; 12915 llvm::APSInt Result = Src.convertToInt( 12916 Info.Ctx.getIntWidth(DestType), 12917 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12918 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12919 return false; 12920 return Success(Result, E); 12921 } 12922 12923 case CK_FixedPointToBoolean: { 12924 // Unsigned padding does not affect this. 12925 APValue Val; 12926 if (!Evaluate(Val, Info, SubExpr)) 12927 return false; 12928 return Success(Val.getFixedPoint().getBoolValue(), E); 12929 } 12930 12931 case CK_IntegralCast: { 12932 if (!Visit(SubExpr)) 12933 return false; 12934 12935 if (!Result.isInt()) { 12936 // Allow casts of address-of-label differences if they are no-ops 12937 // or narrowing. (The narrowing case isn't actually guaranteed to 12938 // be constant-evaluatable except in some narrow cases which are hard 12939 // to detect here. We let it through on the assumption the user knows 12940 // what they are doing.) 12941 if (Result.isAddrLabelDiff()) 12942 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12943 // Only allow casts of lvalues if they are lossless. 12944 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12945 } 12946 12947 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12948 Result.getInt()), E); 12949 } 12950 12951 case CK_PointerToIntegral: { 12952 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12953 12954 LValue LV; 12955 if (!EvaluatePointer(SubExpr, LV, Info)) 12956 return false; 12957 12958 if (LV.getLValueBase()) { 12959 // Only allow based lvalue casts if they are lossless. 12960 // FIXME: Allow a larger integer size than the pointer size, and allow 12961 // narrowing back down to pointer width in subsequent integral casts. 12962 // FIXME: Check integer type's active bits, not its type size. 12963 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12964 return Error(E); 12965 12966 LV.Designator.setInvalid(); 12967 LV.moveInto(Result); 12968 return true; 12969 } 12970 12971 APSInt AsInt; 12972 APValue V; 12973 LV.moveInto(V); 12974 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12975 llvm_unreachable("Can't cast this!"); 12976 12977 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 12978 } 12979 12980 case CK_IntegralComplexToReal: { 12981 ComplexValue C; 12982 if (!EvaluateComplex(SubExpr, C, Info)) 12983 return false; 12984 return Success(C.getComplexIntReal(), E); 12985 } 12986 12987 case CK_FloatingToIntegral: { 12988 APFloat F(0.0); 12989 if (!EvaluateFloat(SubExpr, F, Info)) 12990 return false; 12991 12992 APSInt Value; 12993 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 12994 return false; 12995 return Success(Value, E); 12996 } 12997 } 12998 12999 llvm_unreachable("unknown cast resulting in integral value"); 13000 } 13001 13002 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13003 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13004 ComplexValue LV; 13005 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13006 return false; 13007 if (!LV.isComplexInt()) 13008 return Error(E); 13009 return Success(LV.getComplexIntReal(), E); 13010 } 13011 13012 return Visit(E->getSubExpr()); 13013 } 13014 13015 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13016 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13017 ComplexValue LV; 13018 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13019 return false; 13020 if (!LV.isComplexInt()) 13021 return Error(E); 13022 return Success(LV.getComplexIntImag(), E); 13023 } 13024 13025 VisitIgnoredValue(E->getSubExpr()); 13026 return Success(0, E); 13027 } 13028 13029 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13030 return Success(E->getPackLength(), E); 13031 } 13032 13033 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13034 return Success(E->getValue(), E); 13035 } 13036 13037 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13038 const ConceptSpecializationExpr *E) { 13039 return Success(E->isSatisfied(), E); 13040 } 13041 13042 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13043 return Success(E->isSatisfied(), E); 13044 } 13045 13046 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13047 switch (E->getOpcode()) { 13048 default: 13049 // Invalid unary operators 13050 return Error(E); 13051 case UO_Plus: 13052 // The result is just the value. 13053 return Visit(E->getSubExpr()); 13054 case UO_Minus: { 13055 if (!Visit(E->getSubExpr())) return false; 13056 if (!Result.isFixedPoint()) 13057 return Error(E); 13058 bool Overflowed; 13059 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13060 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13061 return false; 13062 return Success(Negated, E); 13063 } 13064 case UO_LNot: { 13065 bool bres; 13066 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13067 return false; 13068 return Success(!bres, E); 13069 } 13070 } 13071 } 13072 13073 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13074 const Expr *SubExpr = E->getSubExpr(); 13075 QualType DestType = E->getType(); 13076 assert(DestType->isFixedPointType() && 13077 "Expected destination type to be a fixed point type"); 13078 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13079 13080 switch (E->getCastKind()) { 13081 case CK_FixedPointCast: { 13082 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13083 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13084 return false; 13085 bool Overflowed; 13086 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13087 if (Overflowed) { 13088 if (Info.checkingForUndefinedBehavior()) 13089 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13090 diag::warn_fixedpoint_constant_overflow) 13091 << Result.toString() << E->getType(); 13092 else if (!HandleOverflow(Info, E, Result, E->getType())) 13093 return false; 13094 } 13095 return Success(Result, E); 13096 } 13097 case CK_IntegralToFixedPoint: { 13098 APSInt Src; 13099 if (!EvaluateInteger(SubExpr, Src, Info)) 13100 return false; 13101 13102 bool Overflowed; 13103 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13104 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13105 13106 if (Overflowed) { 13107 if (Info.checkingForUndefinedBehavior()) 13108 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13109 diag::warn_fixedpoint_constant_overflow) 13110 << IntResult.toString() << E->getType(); 13111 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13112 return false; 13113 } 13114 13115 return Success(IntResult, E); 13116 } 13117 case CK_NoOp: 13118 case CK_LValueToRValue: 13119 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13120 default: 13121 return Error(E); 13122 } 13123 } 13124 13125 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13126 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13127 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13128 13129 const Expr *LHS = E->getLHS(); 13130 const Expr *RHS = E->getRHS(); 13131 FixedPointSemantics ResultFXSema = 13132 Info.Ctx.getFixedPointSemantics(E->getType()); 13133 13134 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13135 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13136 return false; 13137 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13138 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13139 return false; 13140 13141 bool OpOverflow = false, ConversionOverflow = false; 13142 APFixedPoint Result(LHSFX.getSemantics()); 13143 switch (E->getOpcode()) { 13144 case BO_Add: { 13145 Result = LHSFX.add(RHSFX, &OpOverflow) 13146 .convert(ResultFXSema, &ConversionOverflow); 13147 break; 13148 } 13149 case BO_Sub: { 13150 Result = LHSFX.sub(RHSFX, &OpOverflow) 13151 .convert(ResultFXSema, &ConversionOverflow); 13152 break; 13153 } 13154 case BO_Mul: { 13155 Result = LHSFX.mul(RHSFX, &OpOverflow) 13156 .convert(ResultFXSema, &ConversionOverflow); 13157 break; 13158 } 13159 case BO_Div: { 13160 if (RHSFX.getValue() == 0) { 13161 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13162 return false; 13163 } 13164 Result = LHSFX.div(RHSFX, &OpOverflow) 13165 .convert(ResultFXSema, &ConversionOverflow); 13166 break; 13167 } 13168 case BO_Shl: 13169 case BO_Shr: { 13170 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13171 llvm::APSInt RHSVal = RHSFX.getValue(); 13172 13173 unsigned ShiftBW = 13174 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13175 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13176 // Embedded-C 4.1.6.2.2: 13177 // The right operand must be nonnegative and less than the total number 13178 // of (nonpadding) bits of the fixed-point operand ... 13179 if (RHSVal.isNegative()) 13180 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13181 else if (Amt != RHSVal) 13182 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13183 << RHSVal << E->getType() << ShiftBW; 13184 13185 if (E->getOpcode() == BO_Shl) 13186 Result = LHSFX.shl(Amt, &OpOverflow); 13187 else 13188 Result = LHSFX.shr(Amt, &OpOverflow); 13189 break; 13190 } 13191 default: 13192 return false; 13193 } 13194 if (OpOverflow || ConversionOverflow) { 13195 if (Info.checkingForUndefinedBehavior()) 13196 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13197 diag::warn_fixedpoint_constant_overflow) 13198 << Result.toString() << E->getType(); 13199 else if (!HandleOverflow(Info, E, Result, E->getType())) 13200 return false; 13201 } 13202 return Success(Result, E); 13203 } 13204 13205 //===----------------------------------------------------------------------===// 13206 // Float Evaluation 13207 //===----------------------------------------------------------------------===// 13208 13209 namespace { 13210 class FloatExprEvaluator 13211 : public ExprEvaluatorBase<FloatExprEvaluator> { 13212 APFloat &Result; 13213 public: 13214 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13215 : ExprEvaluatorBaseTy(info), Result(result) {} 13216 13217 bool Success(const APValue &V, const Expr *e) { 13218 Result = V.getFloat(); 13219 return true; 13220 } 13221 13222 bool ZeroInitialization(const Expr *E) { 13223 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13224 return true; 13225 } 13226 13227 bool VisitCallExpr(const CallExpr *E); 13228 13229 bool VisitUnaryOperator(const UnaryOperator *E); 13230 bool VisitBinaryOperator(const BinaryOperator *E); 13231 bool VisitFloatingLiteral(const FloatingLiteral *E); 13232 bool VisitCastExpr(const CastExpr *E); 13233 13234 bool VisitUnaryReal(const UnaryOperator *E); 13235 bool VisitUnaryImag(const UnaryOperator *E); 13236 13237 // FIXME: Missing: array subscript of vector, member of vector 13238 }; 13239 } // end anonymous namespace 13240 13241 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13242 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13243 return FloatExprEvaluator(Info, Result).Visit(E); 13244 } 13245 13246 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13247 QualType ResultTy, 13248 const Expr *Arg, 13249 bool SNaN, 13250 llvm::APFloat &Result) { 13251 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13252 if (!S) return false; 13253 13254 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13255 13256 llvm::APInt fill; 13257 13258 // Treat empty strings as if they were zero. 13259 if (S->getString().empty()) 13260 fill = llvm::APInt(32, 0); 13261 else if (S->getString().getAsInteger(0, fill)) 13262 return false; 13263 13264 if (Context.getTargetInfo().isNan2008()) { 13265 if (SNaN) 13266 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13267 else 13268 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13269 } else { 13270 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13271 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13272 // a different encoding to what became a standard in 2008, and for pre- 13273 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13274 // sNaN. This is now known as "legacy NaN" encoding. 13275 if (SNaN) 13276 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13277 else 13278 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13279 } 13280 13281 return true; 13282 } 13283 13284 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13285 switch (E->getBuiltinCallee()) { 13286 default: 13287 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13288 13289 case Builtin::BI__builtin_huge_val: 13290 case Builtin::BI__builtin_huge_valf: 13291 case Builtin::BI__builtin_huge_vall: 13292 case Builtin::BI__builtin_huge_valf128: 13293 case Builtin::BI__builtin_inf: 13294 case Builtin::BI__builtin_inff: 13295 case Builtin::BI__builtin_infl: 13296 case Builtin::BI__builtin_inff128: { 13297 const llvm::fltSemantics &Sem = 13298 Info.Ctx.getFloatTypeSemantics(E->getType()); 13299 Result = llvm::APFloat::getInf(Sem); 13300 return true; 13301 } 13302 13303 case Builtin::BI__builtin_nans: 13304 case Builtin::BI__builtin_nansf: 13305 case Builtin::BI__builtin_nansl: 13306 case Builtin::BI__builtin_nansf128: 13307 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13308 true, Result)) 13309 return Error(E); 13310 return true; 13311 13312 case Builtin::BI__builtin_nan: 13313 case Builtin::BI__builtin_nanf: 13314 case Builtin::BI__builtin_nanl: 13315 case Builtin::BI__builtin_nanf128: 13316 // If this is __builtin_nan() turn this into a nan, otherwise we 13317 // can't constant fold it. 13318 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13319 false, Result)) 13320 return Error(E); 13321 return true; 13322 13323 case Builtin::BI__builtin_fabs: 13324 case Builtin::BI__builtin_fabsf: 13325 case Builtin::BI__builtin_fabsl: 13326 case Builtin::BI__builtin_fabsf128: 13327 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13328 return false; 13329 13330 if (Result.isNegative()) 13331 Result.changeSign(); 13332 return true; 13333 13334 // FIXME: Builtin::BI__builtin_powi 13335 // FIXME: Builtin::BI__builtin_powif 13336 // FIXME: Builtin::BI__builtin_powil 13337 13338 case Builtin::BI__builtin_copysign: 13339 case Builtin::BI__builtin_copysignf: 13340 case Builtin::BI__builtin_copysignl: 13341 case Builtin::BI__builtin_copysignf128: { 13342 APFloat RHS(0.); 13343 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13344 !EvaluateFloat(E->getArg(1), RHS, Info)) 13345 return false; 13346 Result.copySign(RHS); 13347 return true; 13348 } 13349 } 13350 } 13351 13352 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13353 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13354 ComplexValue CV; 13355 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13356 return false; 13357 Result = CV.FloatReal; 13358 return true; 13359 } 13360 13361 return Visit(E->getSubExpr()); 13362 } 13363 13364 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13365 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13366 ComplexValue CV; 13367 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13368 return false; 13369 Result = CV.FloatImag; 13370 return true; 13371 } 13372 13373 VisitIgnoredValue(E->getSubExpr()); 13374 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13375 Result = llvm::APFloat::getZero(Sem); 13376 return true; 13377 } 13378 13379 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13380 switch (E->getOpcode()) { 13381 default: return Error(E); 13382 case UO_Plus: 13383 return EvaluateFloat(E->getSubExpr(), Result, Info); 13384 case UO_Minus: 13385 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13386 return false; 13387 Result.changeSign(); 13388 return true; 13389 } 13390 } 13391 13392 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13393 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13394 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13395 13396 APFloat RHS(0.0); 13397 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13398 if (!LHSOK && !Info.noteFailure()) 13399 return false; 13400 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13401 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13402 } 13403 13404 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13405 Result = E->getValue(); 13406 return true; 13407 } 13408 13409 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13410 const Expr* SubExpr = E->getSubExpr(); 13411 13412 switch (E->getCastKind()) { 13413 default: 13414 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13415 13416 case CK_IntegralToFloating: { 13417 APSInt IntResult; 13418 return EvaluateInteger(SubExpr, IntResult, Info) && 13419 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13420 E->getType(), Result); 13421 } 13422 13423 case CK_FloatingCast: { 13424 if (!Visit(SubExpr)) 13425 return false; 13426 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13427 Result); 13428 } 13429 13430 case CK_FloatingComplexToReal: { 13431 ComplexValue V; 13432 if (!EvaluateComplex(SubExpr, V, Info)) 13433 return false; 13434 Result = V.getComplexFloatReal(); 13435 return true; 13436 } 13437 } 13438 } 13439 13440 //===----------------------------------------------------------------------===// 13441 // Complex Evaluation (for float and integer) 13442 //===----------------------------------------------------------------------===// 13443 13444 namespace { 13445 class ComplexExprEvaluator 13446 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13447 ComplexValue &Result; 13448 13449 public: 13450 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13451 : ExprEvaluatorBaseTy(info), Result(Result) {} 13452 13453 bool Success(const APValue &V, const Expr *e) { 13454 Result.setFrom(V); 13455 return true; 13456 } 13457 13458 bool ZeroInitialization(const Expr *E); 13459 13460 //===--------------------------------------------------------------------===// 13461 // Visitor Methods 13462 //===--------------------------------------------------------------------===// 13463 13464 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13465 bool VisitCastExpr(const CastExpr *E); 13466 bool VisitBinaryOperator(const BinaryOperator *E); 13467 bool VisitUnaryOperator(const UnaryOperator *E); 13468 bool VisitInitListExpr(const InitListExpr *E); 13469 bool VisitCallExpr(const CallExpr *E); 13470 }; 13471 } // end anonymous namespace 13472 13473 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13474 EvalInfo &Info) { 13475 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13476 return ComplexExprEvaluator(Info, Result).Visit(E); 13477 } 13478 13479 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13480 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13481 if (ElemTy->isRealFloatingType()) { 13482 Result.makeComplexFloat(); 13483 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13484 Result.FloatReal = Zero; 13485 Result.FloatImag = Zero; 13486 } else { 13487 Result.makeComplexInt(); 13488 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13489 Result.IntReal = Zero; 13490 Result.IntImag = Zero; 13491 } 13492 return true; 13493 } 13494 13495 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13496 const Expr* SubExpr = E->getSubExpr(); 13497 13498 if (SubExpr->getType()->isRealFloatingType()) { 13499 Result.makeComplexFloat(); 13500 APFloat &Imag = Result.FloatImag; 13501 if (!EvaluateFloat(SubExpr, Imag, Info)) 13502 return false; 13503 13504 Result.FloatReal = APFloat(Imag.getSemantics()); 13505 return true; 13506 } else { 13507 assert(SubExpr->getType()->isIntegerType() && 13508 "Unexpected imaginary literal."); 13509 13510 Result.makeComplexInt(); 13511 APSInt &Imag = Result.IntImag; 13512 if (!EvaluateInteger(SubExpr, Imag, Info)) 13513 return false; 13514 13515 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13516 return true; 13517 } 13518 } 13519 13520 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13521 13522 switch (E->getCastKind()) { 13523 case CK_BitCast: 13524 case CK_BaseToDerived: 13525 case CK_DerivedToBase: 13526 case CK_UncheckedDerivedToBase: 13527 case CK_Dynamic: 13528 case CK_ToUnion: 13529 case CK_ArrayToPointerDecay: 13530 case CK_FunctionToPointerDecay: 13531 case CK_NullToPointer: 13532 case CK_NullToMemberPointer: 13533 case CK_BaseToDerivedMemberPointer: 13534 case CK_DerivedToBaseMemberPointer: 13535 case CK_MemberPointerToBoolean: 13536 case CK_ReinterpretMemberPointer: 13537 case CK_ConstructorConversion: 13538 case CK_IntegralToPointer: 13539 case CK_PointerToIntegral: 13540 case CK_PointerToBoolean: 13541 case CK_ToVoid: 13542 case CK_VectorSplat: 13543 case CK_IntegralCast: 13544 case CK_BooleanToSignedIntegral: 13545 case CK_IntegralToBoolean: 13546 case CK_IntegralToFloating: 13547 case CK_FloatingToIntegral: 13548 case CK_FloatingToBoolean: 13549 case CK_FloatingCast: 13550 case CK_CPointerToObjCPointerCast: 13551 case CK_BlockPointerToObjCPointerCast: 13552 case CK_AnyPointerToBlockPointerCast: 13553 case CK_ObjCObjectLValueCast: 13554 case CK_FloatingComplexToReal: 13555 case CK_FloatingComplexToBoolean: 13556 case CK_IntegralComplexToReal: 13557 case CK_IntegralComplexToBoolean: 13558 case CK_ARCProduceObject: 13559 case CK_ARCConsumeObject: 13560 case CK_ARCReclaimReturnedObject: 13561 case CK_ARCExtendBlockObject: 13562 case CK_CopyAndAutoreleaseBlockObject: 13563 case CK_BuiltinFnToFnPtr: 13564 case CK_ZeroToOCLOpaqueType: 13565 case CK_NonAtomicToAtomic: 13566 case CK_AddressSpaceConversion: 13567 case CK_IntToOCLSampler: 13568 case CK_FixedPointCast: 13569 case CK_FixedPointToBoolean: 13570 case CK_FixedPointToIntegral: 13571 case CK_IntegralToFixedPoint: 13572 llvm_unreachable("invalid cast kind for complex value"); 13573 13574 case CK_LValueToRValue: 13575 case CK_AtomicToNonAtomic: 13576 case CK_NoOp: 13577 case CK_LValueToRValueBitCast: 13578 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13579 13580 case CK_Dependent: 13581 case CK_LValueBitCast: 13582 case CK_UserDefinedConversion: 13583 return Error(E); 13584 13585 case CK_FloatingRealToComplex: { 13586 APFloat &Real = Result.FloatReal; 13587 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13588 return false; 13589 13590 Result.makeComplexFloat(); 13591 Result.FloatImag = APFloat(Real.getSemantics()); 13592 return true; 13593 } 13594 13595 case CK_FloatingComplexCast: { 13596 if (!Visit(E->getSubExpr())) 13597 return false; 13598 13599 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13600 QualType From 13601 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13602 13603 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13604 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13605 } 13606 13607 case CK_FloatingComplexToIntegralComplex: { 13608 if (!Visit(E->getSubExpr())) 13609 return false; 13610 13611 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13612 QualType From 13613 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13614 Result.makeComplexInt(); 13615 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13616 To, Result.IntReal) && 13617 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13618 To, Result.IntImag); 13619 } 13620 13621 case CK_IntegralRealToComplex: { 13622 APSInt &Real = Result.IntReal; 13623 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13624 return false; 13625 13626 Result.makeComplexInt(); 13627 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13628 return true; 13629 } 13630 13631 case CK_IntegralComplexCast: { 13632 if (!Visit(E->getSubExpr())) 13633 return false; 13634 13635 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13636 QualType From 13637 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13638 13639 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13640 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13641 return true; 13642 } 13643 13644 case CK_IntegralComplexToFloatingComplex: { 13645 if (!Visit(E->getSubExpr())) 13646 return false; 13647 13648 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13649 QualType From 13650 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13651 Result.makeComplexFloat(); 13652 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13653 To, Result.FloatReal) && 13654 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13655 To, Result.FloatImag); 13656 } 13657 } 13658 13659 llvm_unreachable("unknown cast resulting in complex value"); 13660 } 13661 13662 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13663 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13664 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13665 13666 // Track whether the LHS or RHS is real at the type system level. When this is 13667 // the case we can simplify our evaluation strategy. 13668 bool LHSReal = false, RHSReal = false; 13669 13670 bool LHSOK; 13671 if (E->getLHS()->getType()->isRealFloatingType()) { 13672 LHSReal = true; 13673 APFloat &Real = Result.FloatReal; 13674 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13675 if (LHSOK) { 13676 Result.makeComplexFloat(); 13677 Result.FloatImag = APFloat(Real.getSemantics()); 13678 } 13679 } else { 13680 LHSOK = Visit(E->getLHS()); 13681 } 13682 if (!LHSOK && !Info.noteFailure()) 13683 return false; 13684 13685 ComplexValue RHS; 13686 if (E->getRHS()->getType()->isRealFloatingType()) { 13687 RHSReal = true; 13688 APFloat &Real = RHS.FloatReal; 13689 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13690 return false; 13691 RHS.makeComplexFloat(); 13692 RHS.FloatImag = APFloat(Real.getSemantics()); 13693 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13694 return false; 13695 13696 assert(!(LHSReal && RHSReal) && 13697 "Cannot have both operands of a complex operation be real."); 13698 switch (E->getOpcode()) { 13699 default: return Error(E); 13700 case BO_Add: 13701 if (Result.isComplexFloat()) { 13702 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13703 APFloat::rmNearestTiesToEven); 13704 if (LHSReal) 13705 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13706 else if (!RHSReal) 13707 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13708 APFloat::rmNearestTiesToEven); 13709 } else { 13710 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13711 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13712 } 13713 break; 13714 case BO_Sub: 13715 if (Result.isComplexFloat()) { 13716 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13717 APFloat::rmNearestTiesToEven); 13718 if (LHSReal) { 13719 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13720 Result.getComplexFloatImag().changeSign(); 13721 } else if (!RHSReal) { 13722 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13723 APFloat::rmNearestTiesToEven); 13724 } 13725 } else { 13726 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13727 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13728 } 13729 break; 13730 case BO_Mul: 13731 if (Result.isComplexFloat()) { 13732 // This is an implementation of complex multiplication according to the 13733 // constraints laid out in C11 Annex G. The implementation uses the 13734 // following naming scheme: 13735 // (a + ib) * (c + id) 13736 ComplexValue LHS = Result; 13737 APFloat &A = LHS.getComplexFloatReal(); 13738 APFloat &B = LHS.getComplexFloatImag(); 13739 APFloat &C = RHS.getComplexFloatReal(); 13740 APFloat &D = RHS.getComplexFloatImag(); 13741 APFloat &ResR = Result.getComplexFloatReal(); 13742 APFloat &ResI = Result.getComplexFloatImag(); 13743 if (LHSReal) { 13744 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13745 ResR = A * C; 13746 ResI = A * D; 13747 } else if (RHSReal) { 13748 ResR = C * A; 13749 ResI = C * B; 13750 } else { 13751 // In the fully general case, we need to handle NaNs and infinities 13752 // robustly. 13753 APFloat AC = A * C; 13754 APFloat BD = B * D; 13755 APFloat AD = A * D; 13756 APFloat BC = B * C; 13757 ResR = AC - BD; 13758 ResI = AD + BC; 13759 if (ResR.isNaN() && ResI.isNaN()) { 13760 bool Recalc = false; 13761 if (A.isInfinity() || B.isInfinity()) { 13762 A = APFloat::copySign( 13763 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13764 B = APFloat::copySign( 13765 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13766 if (C.isNaN()) 13767 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13768 if (D.isNaN()) 13769 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13770 Recalc = true; 13771 } 13772 if (C.isInfinity() || D.isInfinity()) { 13773 C = APFloat::copySign( 13774 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13775 D = APFloat::copySign( 13776 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13777 if (A.isNaN()) 13778 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13779 if (B.isNaN()) 13780 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13781 Recalc = true; 13782 } 13783 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13784 AD.isInfinity() || BC.isInfinity())) { 13785 if (A.isNaN()) 13786 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13787 if (B.isNaN()) 13788 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13789 if (C.isNaN()) 13790 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13791 if (D.isNaN()) 13792 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13793 Recalc = true; 13794 } 13795 if (Recalc) { 13796 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13797 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13798 } 13799 } 13800 } 13801 } else { 13802 ComplexValue LHS = Result; 13803 Result.getComplexIntReal() = 13804 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13805 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13806 Result.getComplexIntImag() = 13807 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13808 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13809 } 13810 break; 13811 case BO_Div: 13812 if (Result.isComplexFloat()) { 13813 // This is an implementation of complex division according to the 13814 // constraints laid out in C11 Annex G. The implementation uses the 13815 // following naming scheme: 13816 // (a + ib) / (c + id) 13817 ComplexValue LHS = Result; 13818 APFloat &A = LHS.getComplexFloatReal(); 13819 APFloat &B = LHS.getComplexFloatImag(); 13820 APFloat &C = RHS.getComplexFloatReal(); 13821 APFloat &D = RHS.getComplexFloatImag(); 13822 APFloat &ResR = Result.getComplexFloatReal(); 13823 APFloat &ResI = Result.getComplexFloatImag(); 13824 if (RHSReal) { 13825 ResR = A / C; 13826 ResI = B / C; 13827 } else { 13828 if (LHSReal) { 13829 // No real optimizations we can do here, stub out with zero. 13830 B = APFloat::getZero(A.getSemantics()); 13831 } 13832 int DenomLogB = 0; 13833 APFloat MaxCD = maxnum(abs(C), abs(D)); 13834 if (MaxCD.isFinite()) { 13835 DenomLogB = ilogb(MaxCD); 13836 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13837 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13838 } 13839 APFloat Denom = C * C + D * D; 13840 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13841 APFloat::rmNearestTiesToEven); 13842 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13843 APFloat::rmNearestTiesToEven); 13844 if (ResR.isNaN() && ResI.isNaN()) { 13845 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13846 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13847 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13848 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13849 D.isFinite()) { 13850 A = APFloat::copySign( 13851 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13852 B = APFloat::copySign( 13853 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13854 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13855 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13856 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13857 C = APFloat::copySign( 13858 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13859 D = APFloat::copySign( 13860 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13861 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13862 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13863 } 13864 } 13865 } 13866 } else { 13867 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13868 return Error(E, diag::note_expr_divide_by_zero); 13869 13870 ComplexValue LHS = Result; 13871 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13872 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13873 Result.getComplexIntReal() = 13874 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13875 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13876 Result.getComplexIntImag() = 13877 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13878 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13879 } 13880 break; 13881 } 13882 13883 return true; 13884 } 13885 13886 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13887 // Get the operand value into 'Result'. 13888 if (!Visit(E->getSubExpr())) 13889 return false; 13890 13891 switch (E->getOpcode()) { 13892 default: 13893 return Error(E); 13894 case UO_Extension: 13895 return true; 13896 case UO_Plus: 13897 // The result is always just the subexpr. 13898 return true; 13899 case UO_Minus: 13900 if (Result.isComplexFloat()) { 13901 Result.getComplexFloatReal().changeSign(); 13902 Result.getComplexFloatImag().changeSign(); 13903 } 13904 else { 13905 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13906 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13907 } 13908 return true; 13909 case UO_Not: 13910 if (Result.isComplexFloat()) 13911 Result.getComplexFloatImag().changeSign(); 13912 else 13913 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13914 return true; 13915 } 13916 } 13917 13918 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13919 if (E->getNumInits() == 2) { 13920 if (E->getType()->isComplexType()) { 13921 Result.makeComplexFloat(); 13922 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13923 return false; 13924 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13925 return false; 13926 } else { 13927 Result.makeComplexInt(); 13928 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13929 return false; 13930 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13931 return false; 13932 } 13933 return true; 13934 } 13935 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13936 } 13937 13938 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 13939 switch (E->getBuiltinCallee()) { 13940 case Builtin::BI__builtin_complex: 13941 Result.makeComplexFloat(); 13942 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 13943 return false; 13944 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 13945 return false; 13946 return true; 13947 13948 default: 13949 break; 13950 } 13951 13952 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13953 } 13954 13955 //===----------------------------------------------------------------------===// 13956 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13957 // implicit conversion. 13958 //===----------------------------------------------------------------------===// 13959 13960 namespace { 13961 class AtomicExprEvaluator : 13962 public ExprEvaluatorBase<AtomicExprEvaluator> { 13963 const LValue *This; 13964 APValue &Result; 13965 public: 13966 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13967 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13968 13969 bool Success(const APValue &V, const Expr *E) { 13970 Result = V; 13971 return true; 13972 } 13973 13974 bool ZeroInitialization(const Expr *E) { 13975 ImplicitValueInitExpr VIE( 13976 E->getType()->castAs<AtomicType>()->getValueType()); 13977 // For atomic-qualified class (and array) types in C++, initialize the 13978 // _Atomic-wrapped subobject directly, in-place. 13979 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 13980 : Evaluate(Result, Info, &VIE); 13981 } 13982 13983 bool VisitCastExpr(const CastExpr *E) { 13984 switch (E->getCastKind()) { 13985 default: 13986 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13987 case CK_NonAtomicToAtomic: 13988 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 13989 : Evaluate(Result, Info, E->getSubExpr()); 13990 } 13991 } 13992 }; 13993 } // end anonymous namespace 13994 13995 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 13996 EvalInfo &Info) { 13997 assert(E->isRValue() && E->getType()->isAtomicType()); 13998 return AtomicExprEvaluator(Info, This, Result).Visit(E); 13999 } 14000 14001 //===----------------------------------------------------------------------===// 14002 // Void expression evaluation, primarily for a cast to void on the LHS of a 14003 // comma operator 14004 //===----------------------------------------------------------------------===// 14005 14006 namespace { 14007 class VoidExprEvaluator 14008 : public ExprEvaluatorBase<VoidExprEvaluator> { 14009 public: 14010 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14011 14012 bool Success(const APValue &V, const Expr *e) { return true; } 14013 14014 bool ZeroInitialization(const Expr *E) { return true; } 14015 14016 bool VisitCastExpr(const CastExpr *E) { 14017 switch (E->getCastKind()) { 14018 default: 14019 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14020 case CK_ToVoid: 14021 VisitIgnoredValue(E->getSubExpr()); 14022 return true; 14023 } 14024 } 14025 14026 bool VisitCallExpr(const CallExpr *E) { 14027 switch (E->getBuiltinCallee()) { 14028 case Builtin::BI__assume: 14029 case Builtin::BI__builtin_assume: 14030 // The argument is not evaluated! 14031 return true; 14032 14033 case Builtin::BI__builtin_operator_delete: 14034 return HandleOperatorDeleteCall(Info, E); 14035 14036 default: 14037 break; 14038 } 14039 14040 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14041 } 14042 14043 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14044 }; 14045 } // end anonymous namespace 14046 14047 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14048 // We cannot speculatively evaluate a delete expression. 14049 if (Info.SpeculativeEvaluationDepth) 14050 return false; 14051 14052 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14053 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14054 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14055 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14056 return false; 14057 } 14058 14059 const Expr *Arg = E->getArgument(); 14060 14061 LValue Pointer; 14062 if (!EvaluatePointer(Arg, Pointer, Info)) 14063 return false; 14064 if (Pointer.Designator.Invalid) 14065 return false; 14066 14067 // Deleting a null pointer has no effect. 14068 if (Pointer.isNullPointer()) { 14069 // This is the only case where we need to produce an extension warning: 14070 // the only other way we can succeed is if we find a dynamic allocation, 14071 // and we will have warned when we allocated it in that case. 14072 if (!Info.getLangOpts().CPlusPlus20) 14073 Info.CCEDiag(E, diag::note_constexpr_new); 14074 return true; 14075 } 14076 14077 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14078 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14079 if (!Alloc) 14080 return false; 14081 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14082 14083 // For the non-array case, the designator must be empty if the static type 14084 // does not have a virtual destructor. 14085 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14086 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14087 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14088 << Arg->getType()->getPointeeType() << AllocType; 14089 return false; 14090 } 14091 14092 // For a class type with a virtual destructor, the selected operator delete 14093 // is the one looked up when building the destructor. 14094 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14095 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14096 if (VirtualDelete && 14097 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14098 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14099 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14100 return false; 14101 } 14102 } 14103 14104 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14105 (*Alloc)->Value, AllocType)) 14106 return false; 14107 14108 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14109 // The element was already erased. This means the destructor call also 14110 // deleted the object. 14111 // FIXME: This probably results in undefined behavior before we get this 14112 // far, and should be diagnosed elsewhere first. 14113 Info.FFDiag(E, diag::note_constexpr_double_delete); 14114 return false; 14115 } 14116 14117 return true; 14118 } 14119 14120 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14121 assert(E->isRValue() && E->getType()->isVoidType()); 14122 return VoidExprEvaluator(Info).Visit(E); 14123 } 14124 14125 //===----------------------------------------------------------------------===// 14126 // Top level Expr::EvaluateAsRValue method. 14127 //===----------------------------------------------------------------------===// 14128 14129 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14130 // In C, function designators are not lvalues, but we evaluate them as if they 14131 // are. 14132 QualType T = E->getType(); 14133 if (E->isGLValue() || T->isFunctionType()) { 14134 LValue LV; 14135 if (!EvaluateLValue(E, LV, Info)) 14136 return false; 14137 LV.moveInto(Result); 14138 } else if (T->isVectorType()) { 14139 if (!EvaluateVector(E, Result, Info)) 14140 return false; 14141 } else if (T->isIntegralOrEnumerationType()) { 14142 if (!IntExprEvaluator(Info, Result).Visit(E)) 14143 return false; 14144 } else if (T->hasPointerRepresentation()) { 14145 LValue LV; 14146 if (!EvaluatePointer(E, LV, Info)) 14147 return false; 14148 LV.moveInto(Result); 14149 } else if (T->isRealFloatingType()) { 14150 llvm::APFloat F(0.0); 14151 if (!EvaluateFloat(E, F, Info)) 14152 return false; 14153 Result = APValue(F); 14154 } else if (T->isAnyComplexType()) { 14155 ComplexValue C; 14156 if (!EvaluateComplex(E, C, Info)) 14157 return false; 14158 C.moveInto(Result); 14159 } else if (T->isFixedPointType()) { 14160 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14161 } else if (T->isMemberPointerType()) { 14162 MemberPtr P; 14163 if (!EvaluateMemberPointer(E, P, Info)) 14164 return false; 14165 P.moveInto(Result); 14166 return true; 14167 } else if (T->isArrayType()) { 14168 LValue LV; 14169 APValue &Value = 14170 Info.CurrentCall->createTemporary(E, T, false, LV); 14171 if (!EvaluateArray(E, LV, Value, Info)) 14172 return false; 14173 Result = Value; 14174 } else if (T->isRecordType()) { 14175 LValue LV; 14176 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 14177 if (!EvaluateRecord(E, LV, Value, Info)) 14178 return false; 14179 Result = Value; 14180 } else if (T->isVoidType()) { 14181 if (!Info.getLangOpts().CPlusPlus11) 14182 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14183 << E->getType(); 14184 if (!EvaluateVoid(E, Info)) 14185 return false; 14186 } else if (T->isAtomicType()) { 14187 QualType Unqual = T.getAtomicUnqualifiedType(); 14188 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14189 LValue LV; 14190 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 14191 if (!EvaluateAtomic(E, &LV, Value, Info)) 14192 return false; 14193 } else { 14194 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14195 return false; 14196 } 14197 } else if (Info.getLangOpts().CPlusPlus11) { 14198 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14199 return false; 14200 } else { 14201 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14202 return false; 14203 } 14204 14205 return true; 14206 } 14207 14208 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14209 /// cases, the in-place evaluation is essential, since later initializers for 14210 /// an object can indirectly refer to subobjects which were initialized earlier. 14211 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14212 const Expr *E, bool AllowNonLiteralTypes) { 14213 assert(!E->isValueDependent()); 14214 14215 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14216 return false; 14217 14218 if (E->isRValue()) { 14219 // Evaluate arrays and record types in-place, so that later initializers can 14220 // refer to earlier-initialized members of the object. 14221 QualType T = E->getType(); 14222 if (T->isArrayType()) 14223 return EvaluateArray(E, This, Result, Info); 14224 else if (T->isRecordType()) 14225 return EvaluateRecord(E, This, Result, Info); 14226 else if (T->isAtomicType()) { 14227 QualType Unqual = T.getAtomicUnqualifiedType(); 14228 if (Unqual->isArrayType() || Unqual->isRecordType()) 14229 return EvaluateAtomic(E, &This, Result, Info); 14230 } 14231 } 14232 14233 // For any other type, in-place evaluation is unimportant. 14234 return Evaluate(Result, Info, E); 14235 } 14236 14237 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14238 /// lvalue-to-rvalue cast if it is an lvalue. 14239 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14240 if (Info.EnableNewConstInterp) { 14241 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14242 return false; 14243 } else { 14244 if (E->getType().isNull()) 14245 return false; 14246 14247 if (!CheckLiteralType(Info, E)) 14248 return false; 14249 14250 if (!::Evaluate(Result, Info, E)) 14251 return false; 14252 14253 if (E->isGLValue()) { 14254 LValue LV; 14255 LV.setFrom(Info.Ctx, Result); 14256 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14257 return false; 14258 } 14259 } 14260 14261 // Check this core constant expression is a constant expression. 14262 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14263 CheckMemoryLeaks(Info); 14264 } 14265 14266 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14267 const ASTContext &Ctx, bool &IsConst) { 14268 // Fast-path evaluations of integer literals, since we sometimes see files 14269 // containing vast quantities of these. 14270 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14271 Result.Val = APValue(APSInt(L->getValue(), 14272 L->getType()->isUnsignedIntegerType())); 14273 IsConst = true; 14274 return true; 14275 } 14276 14277 // This case should be rare, but we need to check it before we check on 14278 // the type below. 14279 if (Exp->getType().isNull()) { 14280 IsConst = false; 14281 return true; 14282 } 14283 14284 // FIXME: Evaluating values of large array and record types can cause 14285 // performance problems. Only do so in C++11 for now. 14286 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14287 Exp->getType()->isRecordType()) && 14288 !Ctx.getLangOpts().CPlusPlus11) { 14289 IsConst = false; 14290 return true; 14291 } 14292 return false; 14293 } 14294 14295 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14296 Expr::SideEffectsKind SEK) { 14297 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14298 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14299 } 14300 14301 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14302 const ASTContext &Ctx, EvalInfo &Info) { 14303 bool IsConst; 14304 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14305 return IsConst; 14306 14307 return EvaluateAsRValue(Info, E, Result.Val); 14308 } 14309 14310 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14311 const ASTContext &Ctx, 14312 Expr::SideEffectsKind AllowSideEffects, 14313 EvalInfo &Info) { 14314 if (!E->getType()->isIntegralOrEnumerationType()) 14315 return false; 14316 14317 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14318 !ExprResult.Val.isInt() || 14319 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14320 return false; 14321 14322 return true; 14323 } 14324 14325 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14326 const ASTContext &Ctx, 14327 Expr::SideEffectsKind AllowSideEffects, 14328 EvalInfo &Info) { 14329 if (!E->getType()->isFixedPointType()) 14330 return false; 14331 14332 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14333 return false; 14334 14335 if (!ExprResult.Val.isFixedPoint() || 14336 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14337 return false; 14338 14339 return true; 14340 } 14341 14342 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14343 /// any crazy technique (that has nothing to do with language standards) that 14344 /// we want to. If this function returns true, it returns the folded constant 14345 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14346 /// will be applied to the result. 14347 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14348 bool InConstantContext) const { 14349 assert(!isValueDependent() && 14350 "Expression evaluator can't be called on a dependent expression."); 14351 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14352 Info.InConstantContext = InConstantContext; 14353 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14354 } 14355 14356 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14357 bool InConstantContext) const { 14358 assert(!isValueDependent() && 14359 "Expression evaluator can't be called on a dependent expression."); 14360 EvalResult Scratch; 14361 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14362 HandleConversionToBool(Scratch.Val, Result); 14363 } 14364 14365 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14366 SideEffectsKind AllowSideEffects, 14367 bool InConstantContext) const { 14368 assert(!isValueDependent() && 14369 "Expression evaluator can't be called on a dependent expression."); 14370 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14371 Info.InConstantContext = InConstantContext; 14372 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14373 } 14374 14375 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14376 SideEffectsKind AllowSideEffects, 14377 bool InConstantContext) const { 14378 assert(!isValueDependent() && 14379 "Expression evaluator can't be called on a dependent expression."); 14380 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14381 Info.InConstantContext = InConstantContext; 14382 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14383 } 14384 14385 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14386 SideEffectsKind AllowSideEffects, 14387 bool InConstantContext) const { 14388 assert(!isValueDependent() && 14389 "Expression evaluator can't be called on a dependent expression."); 14390 14391 if (!getType()->isRealFloatingType()) 14392 return false; 14393 14394 EvalResult ExprResult; 14395 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14396 !ExprResult.Val.isFloat() || 14397 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14398 return false; 14399 14400 Result = ExprResult.Val.getFloat(); 14401 return true; 14402 } 14403 14404 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14405 bool InConstantContext) const { 14406 assert(!isValueDependent() && 14407 "Expression evaluator can't be called on a dependent expression."); 14408 14409 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14410 Info.InConstantContext = InConstantContext; 14411 LValue LV; 14412 CheckedTemporaries CheckedTemps; 14413 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14414 Result.HasSideEffects || 14415 !CheckLValueConstantExpression(Info, getExprLoc(), 14416 Ctx.getLValueReferenceType(getType()), LV, 14417 Expr::EvaluateForCodeGen, CheckedTemps)) 14418 return false; 14419 14420 LV.moveInto(Result.Val); 14421 return true; 14422 } 14423 14424 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14425 const ASTContext &Ctx, bool InPlace) const { 14426 assert(!isValueDependent() && 14427 "Expression evaluator can't be called on a dependent expression."); 14428 14429 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14430 EvalInfo Info(Ctx, Result, EM); 14431 Info.InConstantContext = true; 14432 14433 if (InPlace) { 14434 Info.setEvaluatingDecl(this, Result.Val); 14435 LValue LVal; 14436 LVal.set(this); 14437 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14438 Result.HasSideEffects) 14439 return false; 14440 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14441 return false; 14442 14443 if (!Info.discardCleanups()) 14444 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14445 14446 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14447 Result.Val, Usage) && 14448 CheckMemoryLeaks(Info); 14449 } 14450 14451 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14452 const VarDecl *VD, 14453 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14454 assert(!isValueDependent() && 14455 "Expression evaluator can't be called on a dependent expression."); 14456 14457 // FIXME: Evaluating initializers for large array and record types can cause 14458 // performance problems. Only do so in C++11 for now. 14459 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14460 !Ctx.getLangOpts().CPlusPlus11) 14461 return false; 14462 14463 Expr::EvalStatus EStatus; 14464 EStatus.Diag = &Notes; 14465 14466 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14467 ? EvalInfo::EM_ConstantExpression 14468 : EvalInfo::EM_ConstantFold); 14469 Info.setEvaluatingDecl(VD, Value); 14470 Info.InConstantContext = true; 14471 14472 SourceLocation DeclLoc = VD->getLocation(); 14473 QualType DeclTy = VD->getType(); 14474 14475 if (Info.EnableNewConstInterp) { 14476 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14477 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14478 return false; 14479 } else { 14480 LValue LVal; 14481 LVal.set(VD); 14482 14483 if (!EvaluateInPlace(Value, Info, LVal, this, 14484 /*AllowNonLiteralTypes=*/true) || 14485 EStatus.HasSideEffects) 14486 return false; 14487 14488 // At this point, any lifetime-extended temporaries are completely 14489 // initialized. 14490 Info.performLifetimeExtension(); 14491 14492 if (!Info.discardCleanups()) 14493 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14494 } 14495 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14496 CheckMemoryLeaks(Info); 14497 } 14498 14499 bool VarDecl::evaluateDestruction( 14500 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14501 Expr::EvalStatus EStatus; 14502 EStatus.Diag = &Notes; 14503 14504 // Make a copy of the value for the destructor to mutate, if we know it. 14505 // Otherwise, treat the value as default-initialized; if the destructor works 14506 // anyway, then the destruction is constant (and must be essentially empty). 14507 APValue DestroyedValue; 14508 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14509 DestroyedValue = *getEvaluatedValue(); 14510 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14511 return false; 14512 14513 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14514 Info.setEvaluatingDecl(this, DestroyedValue, 14515 EvalInfo::EvaluatingDeclKind::Dtor); 14516 Info.InConstantContext = true; 14517 14518 SourceLocation DeclLoc = getLocation(); 14519 QualType DeclTy = getType(); 14520 14521 LValue LVal; 14522 LVal.set(this); 14523 14524 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14525 EStatus.HasSideEffects) 14526 return false; 14527 14528 if (!Info.discardCleanups()) 14529 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14530 14531 ensureEvaluatedStmt()->HasConstantDestruction = true; 14532 return true; 14533 } 14534 14535 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14536 /// constant folded, but discard the result. 14537 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14538 assert(!isValueDependent() && 14539 "Expression evaluator can't be called on a dependent expression."); 14540 14541 EvalResult Result; 14542 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14543 !hasUnacceptableSideEffect(Result, SEK); 14544 } 14545 14546 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14547 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14548 assert(!isValueDependent() && 14549 "Expression evaluator can't be called on a dependent expression."); 14550 14551 EvalResult EVResult; 14552 EVResult.Diag = Diag; 14553 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14554 Info.InConstantContext = true; 14555 14556 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14557 (void)Result; 14558 assert(Result && "Could not evaluate expression"); 14559 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14560 14561 return EVResult.Val.getInt(); 14562 } 14563 14564 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14565 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14566 assert(!isValueDependent() && 14567 "Expression evaluator can't be called on a dependent expression."); 14568 14569 EvalResult EVResult; 14570 EVResult.Diag = Diag; 14571 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14572 Info.InConstantContext = true; 14573 Info.CheckingForUndefinedBehavior = true; 14574 14575 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14576 (void)Result; 14577 assert(Result && "Could not evaluate expression"); 14578 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14579 14580 return EVResult.Val.getInt(); 14581 } 14582 14583 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14584 assert(!isValueDependent() && 14585 "Expression evaluator can't be called on a dependent expression."); 14586 14587 bool IsConst; 14588 EvalResult EVResult; 14589 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14590 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14591 Info.CheckingForUndefinedBehavior = true; 14592 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14593 } 14594 } 14595 14596 bool Expr::EvalResult::isGlobalLValue() const { 14597 assert(Val.isLValue()); 14598 return IsGlobalLValue(Val.getLValueBase()); 14599 } 14600 14601 14602 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14603 /// an integer constant expression. 14604 14605 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14606 /// comma, etc 14607 14608 // CheckICE - This function does the fundamental ICE checking: the returned 14609 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14610 // and a (possibly null) SourceLocation indicating the location of the problem. 14611 // 14612 // Note that to reduce code duplication, this helper does no evaluation 14613 // itself; the caller checks whether the expression is evaluatable, and 14614 // in the rare cases where CheckICE actually cares about the evaluated 14615 // value, it calls into Evaluate. 14616 14617 namespace { 14618 14619 enum ICEKind { 14620 /// This expression is an ICE. 14621 IK_ICE, 14622 /// This expression is not an ICE, but if it isn't evaluated, it's 14623 /// a legal subexpression for an ICE. This return value is used to handle 14624 /// the comma operator in C99 mode, and non-constant subexpressions. 14625 IK_ICEIfUnevaluated, 14626 /// This expression is not an ICE, and is not a legal subexpression for one. 14627 IK_NotICE 14628 }; 14629 14630 struct ICEDiag { 14631 ICEKind Kind; 14632 SourceLocation Loc; 14633 14634 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14635 }; 14636 14637 } 14638 14639 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14640 14641 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14642 14643 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14644 Expr::EvalResult EVResult; 14645 Expr::EvalStatus Status; 14646 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14647 14648 Info.InConstantContext = true; 14649 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14650 !EVResult.Val.isInt()) 14651 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14652 14653 return NoDiag(); 14654 } 14655 14656 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14657 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14658 if (!E->getType()->isIntegralOrEnumerationType()) 14659 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14660 14661 switch (E->getStmtClass()) { 14662 #define ABSTRACT_STMT(Node) 14663 #define STMT(Node, Base) case Expr::Node##Class: 14664 #define EXPR(Node, Base) 14665 #include "clang/AST/StmtNodes.inc" 14666 case Expr::PredefinedExprClass: 14667 case Expr::FloatingLiteralClass: 14668 case Expr::ImaginaryLiteralClass: 14669 case Expr::StringLiteralClass: 14670 case Expr::ArraySubscriptExprClass: 14671 case Expr::MatrixSubscriptExprClass: 14672 case Expr::OMPArraySectionExprClass: 14673 case Expr::OMPArrayShapingExprClass: 14674 case Expr::OMPIteratorExprClass: 14675 case Expr::MemberExprClass: 14676 case Expr::CompoundAssignOperatorClass: 14677 case Expr::CompoundLiteralExprClass: 14678 case Expr::ExtVectorElementExprClass: 14679 case Expr::DesignatedInitExprClass: 14680 case Expr::ArrayInitLoopExprClass: 14681 case Expr::ArrayInitIndexExprClass: 14682 case Expr::NoInitExprClass: 14683 case Expr::DesignatedInitUpdateExprClass: 14684 case Expr::ImplicitValueInitExprClass: 14685 case Expr::ParenListExprClass: 14686 case Expr::VAArgExprClass: 14687 case Expr::AddrLabelExprClass: 14688 case Expr::StmtExprClass: 14689 case Expr::CXXMemberCallExprClass: 14690 case Expr::CUDAKernelCallExprClass: 14691 case Expr::CXXAddrspaceCastExprClass: 14692 case Expr::CXXDynamicCastExprClass: 14693 case Expr::CXXTypeidExprClass: 14694 case Expr::CXXUuidofExprClass: 14695 case Expr::MSPropertyRefExprClass: 14696 case Expr::MSPropertySubscriptExprClass: 14697 case Expr::CXXNullPtrLiteralExprClass: 14698 case Expr::UserDefinedLiteralClass: 14699 case Expr::CXXThisExprClass: 14700 case Expr::CXXThrowExprClass: 14701 case Expr::CXXNewExprClass: 14702 case Expr::CXXDeleteExprClass: 14703 case Expr::CXXPseudoDestructorExprClass: 14704 case Expr::UnresolvedLookupExprClass: 14705 case Expr::TypoExprClass: 14706 case Expr::RecoveryExprClass: 14707 case Expr::DependentScopeDeclRefExprClass: 14708 case Expr::CXXConstructExprClass: 14709 case Expr::CXXInheritedCtorInitExprClass: 14710 case Expr::CXXStdInitializerListExprClass: 14711 case Expr::CXXBindTemporaryExprClass: 14712 case Expr::ExprWithCleanupsClass: 14713 case Expr::CXXTemporaryObjectExprClass: 14714 case Expr::CXXUnresolvedConstructExprClass: 14715 case Expr::CXXDependentScopeMemberExprClass: 14716 case Expr::UnresolvedMemberExprClass: 14717 case Expr::ObjCStringLiteralClass: 14718 case Expr::ObjCBoxedExprClass: 14719 case Expr::ObjCArrayLiteralClass: 14720 case Expr::ObjCDictionaryLiteralClass: 14721 case Expr::ObjCEncodeExprClass: 14722 case Expr::ObjCMessageExprClass: 14723 case Expr::ObjCSelectorExprClass: 14724 case Expr::ObjCProtocolExprClass: 14725 case Expr::ObjCIvarRefExprClass: 14726 case Expr::ObjCPropertyRefExprClass: 14727 case Expr::ObjCSubscriptRefExprClass: 14728 case Expr::ObjCIsaExprClass: 14729 case Expr::ObjCAvailabilityCheckExprClass: 14730 case Expr::ShuffleVectorExprClass: 14731 case Expr::ConvertVectorExprClass: 14732 case Expr::BlockExprClass: 14733 case Expr::NoStmtClass: 14734 case Expr::OpaqueValueExprClass: 14735 case Expr::PackExpansionExprClass: 14736 case Expr::SubstNonTypeTemplateParmPackExprClass: 14737 case Expr::FunctionParmPackExprClass: 14738 case Expr::AsTypeExprClass: 14739 case Expr::ObjCIndirectCopyRestoreExprClass: 14740 case Expr::MaterializeTemporaryExprClass: 14741 case Expr::PseudoObjectExprClass: 14742 case Expr::AtomicExprClass: 14743 case Expr::LambdaExprClass: 14744 case Expr::CXXFoldExprClass: 14745 case Expr::CoawaitExprClass: 14746 case Expr::DependentCoawaitExprClass: 14747 case Expr::CoyieldExprClass: 14748 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14749 14750 case Expr::InitListExprClass: { 14751 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14752 // form "T x = { a };" is equivalent to "T x = a;". 14753 // Unless we're initializing a reference, T is a scalar as it is known to be 14754 // of integral or enumeration type. 14755 if (E->isRValue()) 14756 if (cast<InitListExpr>(E)->getNumInits() == 1) 14757 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14758 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14759 } 14760 14761 case Expr::SizeOfPackExprClass: 14762 case Expr::GNUNullExprClass: 14763 case Expr::SourceLocExprClass: 14764 return NoDiag(); 14765 14766 case Expr::SubstNonTypeTemplateParmExprClass: 14767 return 14768 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14769 14770 case Expr::ConstantExprClass: 14771 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14772 14773 case Expr::ParenExprClass: 14774 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14775 case Expr::GenericSelectionExprClass: 14776 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14777 case Expr::IntegerLiteralClass: 14778 case Expr::FixedPointLiteralClass: 14779 case Expr::CharacterLiteralClass: 14780 case Expr::ObjCBoolLiteralExprClass: 14781 case Expr::CXXBoolLiteralExprClass: 14782 case Expr::CXXScalarValueInitExprClass: 14783 case Expr::TypeTraitExprClass: 14784 case Expr::ConceptSpecializationExprClass: 14785 case Expr::RequiresExprClass: 14786 case Expr::ArrayTypeTraitExprClass: 14787 case Expr::ExpressionTraitExprClass: 14788 case Expr::CXXNoexceptExprClass: 14789 return NoDiag(); 14790 case Expr::CallExprClass: 14791 case Expr::CXXOperatorCallExprClass: { 14792 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14793 // constant expressions, but they can never be ICEs because an ICE cannot 14794 // contain an operand of (pointer to) function type. 14795 const CallExpr *CE = cast<CallExpr>(E); 14796 if (CE->getBuiltinCallee()) 14797 return CheckEvalInICE(E, Ctx); 14798 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14799 } 14800 case Expr::CXXRewrittenBinaryOperatorClass: 14801 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14802 Ctx); 14803 case Expr::DeclRefExprClass: { 14804 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14805 return NoDiag(); 14806 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14807 if (Ctx.getLangOpts().CPlusPlus && 14808 D && IsConstNonVolatile(D->getType())) { 14809 // Parameter variables are never constants. Without this check, 14810 // getAnyInitializer() can find a default argument, which leads 14811 // to chaos. 14812 if (isa<ParmVarDecl>(D)) 14813 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14814 14815 // C++ 7.1.5.1p2 14816 // A variable of non-volatile const-qualified integral or enumeration 14817 // type initialized by an ICE can be used in ICEs. 14818 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14819 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14820 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14821 14822 const VarDecl *VD; 14823 // Look for a declaration of this variable that has an initializer, and 14824 // check whether it is an ICE. 14825 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 14826 return NoDiag(); 14827 else 14828 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14829 } 14830 } 14831 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14832 } 14833 case Expr::UnaryOperatorClass: { 14834 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14835 switch (Exp->getOpcode()) { 14836 case UO_PostInc: 14837 case UO_PostDec: 14838 case UO_PreInc: 14839 case UO_PreDec: 14840 case UO_AddrOf: 14841 case UO_Deref: 14842 case UO_Coawait: 14843 // C99 6.6/3 allows increment and decrement within unevaluated 14844 // subexpressions of constant expressions, but they can never be ICEs 14845 // because an ICE cannot contain an lvalue operand. 14846 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14847 case UO_Extension: 14848 case UO_LNot: 14849 case UO_Plus: 14850 case UO_Minus: 14851 case UO_Not: 14852 case UO_Real: 14853 case UO_Imag: 14854 return CheckICE(Exp->getSubExpr(), Ctx); 14855 } 14856 llvm_unreachable("invalid unary operator class"); 14857 } 14858 case Expr::OffsetOfExprClass: { 14859 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14860 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14861 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14862 // compliance: we should warn earlier for offsetof expressions with 14863 // array subscripts that aren't ICEs, and if the array subscripts 14864 // are ICEs, the value of the offsetof must be an integer constant. 14865 return CheckEvalInICE(E, Ctx); 14866 } 14867 case Expr::UnaryExprOrTypeTraitExprClass: { 14868 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14869 if ((Exp->getKind() == UETT_SizeOf) && 14870 Exp->getTypeOfArgument()->isVariableArrayType()) 14871 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14872 return NoDiag(); 14873 } 14874 case Expr::BinaryOperatorClass: { 14875 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14876 switch (Exp->getOpcode()) { 14877 case BO_PtrMemD: 14878 case BO_PtrMemI: 14879 case BO_Assign: 14880 case BO_MulAssign: 14881 case BO_DivAssign: 14882 case BO_RemAssign: 14883 case BO_AddAssign: 14884 case BO_SubAssign: 14885 case BO_ShlAssign: 14886 case BO_ShrAssign: 14887 case BO_AndAssign: 14888 case BO_XorAssign: 14889 case BO_OrAssign: 14890 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14891 // constant expressions, but they can never be ICEs because an ICE cannot 14892 // contain an lvalue operand. 14893 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14894 14895 case BO_Mul: 14896 case BO_Div: 14897 case BO_Rem: 14898 case BO_Add: 14899 case BO_Sub: 14900 case BO_Shl: 14901 case BO_Shr: 14902 case BO_LT: 14903 case BO_GT: 14904 case BO_LE: 14905 case BO_GE: 14906 case BO_EQ: 14907 case BO_NE: 14908 case BO_And: 14909 case BO_Xor: 14910 case BO_Or: 14911 case BO_Comma: 14912 case BO_Cmp: { 14913 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14914 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14915 if (Exp->getOpcode() == BO_Div || 14916 Exp->getOpcode() == BO_Rem) { 14917 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14918 // we don't evaluate one. 14919 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14920 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14921 if (REval == 0) 14922 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14923 if (REval.isSigned() && REval.isAllOnesValue()) { 14924 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14925 if (LEval.isMinSignedValue()) 14926 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14927 } 14928 } 14929 } 14930 if (Exp->getOpcode() == BO_Comma) { 14931 if (Ctx.getLangOpts().C99) { 14932 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14933 // if it isn't evaluated. 14934 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14935 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14936 } else { 14937 // In both C89 and C++, commas in ICEs are illegal. 14938 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14939 } 14940 } 14941 return Worst(LHSResult, RHSResult); 14942 } 14943 case BO_LAnd: 14944 case BO_LOr: { 14945 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14946 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14947 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14948 // Rare case where the RHS has a comma "side-effect"; we need 14949 // to actually check the condition to see whether the side 14950 // with the comma is evaluated. 14951 if ((Exp->getOpcode() == BO_LAnd) != 14952 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14953 return RHSResult; 14954 return NoDiag(); 14955 } 14956 14957 return Worst(LHSResult, RHSResult); 14958 } 14959 } 14960 llvm_unreachable("invalid binary operator kind"); 14961 } 14962 case Expr::ImplicitCastExprClass: 14963 case Expr::CStyleCastExprClass: 14964 case Expr::CXXFunctionalCastExprClass: 14965 case Expr::CXXStaticCastExprClass: 14966 case Expr::CXXReinterpretCastExprClass: 14967 case Expr::CXXConstCastExprClass: 14968 case Expr::ObjCBridgedCastExprClass: { 14969 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14970 if (isa<ExplicitCastExpr>(E)) { 14971 if (const FloatingLiteral *FL 14972 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14973 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14974 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14975 APSInt IgnoredVal(DestWidth, !DestSigned); 14976 bool Ignored; 14977 // If the value does not fit in the destination type, the behavior is 14978 // undefined, so we are not required to treat it as a constant 14979 // expression. 14980 if (FL->getValue().convertToInteger(IgnoredVal, 14981 llvm::APFloat::rmTowardZero, 14982 &Ignored) & APFloat::opInvalidOp) 14983 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14984 return NoDiag(); 14985 } 14986 } 14987 switch (cast<CastExpr>(E)->getCastKind()) { 14988 case CK_LValueToRValue: 14989 case CK_AtomicToNonAtomic: 14990 case CK_NonAtomicToAtomic: 14991 case CK_NoOp: 14992 case CK_IntegralToBoolean: 14993 case CK_IntegralCast: 14994 return CheckICE(SubExpr, Ctx); 14995 default: 14996 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14997 } 14998 } 14999 case Expr::BinaryConditionalOperatorClass: { 15000 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15001 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15002 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15003 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15004 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15005 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15006 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15007 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15008 return FalseResult; 15009 } 15010 case Expr::ConditionalOperatorClass: { 15011 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15012 // If the condition (ignoring parens) is a __builtin_constant_p call, 15013 // then only the true side is actually considered in an integer constant 15014 // expression, and it is fully evaluated. This is an important GNU 15015 // extension. See GCC PR38377 for discussion. 15016 if (const CallExpr *CallCE 15017 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15018 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15019 return CheckEvalInICE(E, Ctx); 15020 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15021 if (CondResult.Kind == IK_NotICE) 15022 return CondResult; 15023 15024 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15025 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15026 15027 if (TrueResult.Kind == IK_NotICE) 15028 return TrueResult; 15029 if (FalseResult.Kind == IK_NotICE) 15030 return FalseResult; 15031 if (CondResult.Kind == IK_ICEIfUnevaluated) 15032 return CondResult; 15033 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15034 return NoDiag(); 15035 // Rare case where the diagnostics depend on which side is evaluated 15036 // Note that if we get here, CondResult is 0, and at least one of 15037 // TrueResult and FalseResult is non-zero. 15038 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15039 return FalseResult; 15040 return TrueResult; 15041 } 15042 case Expr::CXXDefaultArgExprClass: 15043 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15044 case Expr::CXXDefaultInitExprClass: 15045 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15046 case Expr::ChooseExprClass: { 15047 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15048 } 15049 case Expr::BuiltinBitCastExprClass: { 15050 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15051 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15052 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15053 } 15054 } 15055 15056 llvm_unreachable("Invalid StmtClass!"); 15057 } 15058 15059 /// Evaluate an expression as a C++11 integral constant expression. 15060 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15061 const Expr *E, 15062 llvm::APSInt *Value, 15063 SourceLocation *Loc) { 15064 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15065 if (Loc) *Loc = E->getExprLoc(); 15066 return false; 15067 } 15068 15069 APValue Result; 15070 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15071 return false; 15072 15073 if (!Result.isInt()) { 15074 if (Loc) *Loc = E->getExprLoc(); 15075 return false; 15076 } 15077 15078 if (Value) *Value = Result.getInt(); 15079 return true; 15080 } 15081 15082 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15083 SourceLocation *Loc) const { 15084 assert(!isValueDependent() && 15085 "Expression evaluator can't be called on a dependent expression."); 15086 15087 if (Ctx.getLangOpts().CPlusPlus11) 15088 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15089 15090 ICEDiag D = CheckICE(this, Ctx); 15091 if (D.Kind != IK_ICE) { 15092 if (Loc) *Loc = D.Loc; 15093 return false; 15094 } 15095 return true; 15096 } 15097 15098 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15099 SourceLocation *Loc, 15100 bool isEvaluated) const { 15101 assert(!isValueDependent() && 15102 "Expression evaluator can't be called on a dependent expression."); 15103 15104 APSInt Value; 15105 15106 if (Ctx.getLangOpts().CPlusPlus11) { 15107 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15108 return Value; 15109 return None; 15110 } 15111 15112 if (!isIntegerConstantExpr(Ctx, Loc)) 15113 return None; 15114 15115 // The only possible side-effects here are due to UB discovered in the 15116 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15117 // required to treat the expression as an ICE, so we produce the folded 15118 // value. 15119 EvalResult ExprResult; 15120 Expr::EvalStatus Status; 15121 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15122 Info.InConstantContext = true; 15123 15124 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15125 llvm_unreachable("ICE cannot be evaluated!"); 15126 15127 return ExprResult.Val.getInt(); 15128 } 15129 15130 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15131 assert(!isValueDependent() && 15132 "Expression evaluator can't be called on a dependent expression."); 15133 15134 return CheckICE(this, Ctx).Kind == IK_ICE; 15135 } 15136 15137 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15138 SourceLocation *Loc) const { 15139 assert(!isValueDependent() && 15140 "Expression evaluator can't be called on a dependent expression."); 15141 15142 // We support this checking in C++98 mode in order to diagnose compatibility 15143 // issues. 15144 assert(Ctx.getLangOpts().CPlusPlus); 15145 15146 // Build evaluation settings. 15147 Expr::EvalStatus Status; 15148 SmallVector<PartialDiagnosticAt, 8> Diags; 15149 Status.Diag = &Diags; 15150 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15151 15152 APValue Scratch; 15153 bool IsConstExpr = 15154 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15155 // FIXME: We don't produce a diagnostic for this, but the callers that 15156 // call us on arbitrary full-expressions should generally not care. 15157 Info.discardCleanups() && !Status.HasSideEffects; 15158 15159 if (!Diags.empty()) { 15160 IsConstExpr = false; 15161 if (Loc) *Loc = Diags[0].first; 15162 } else if (!IsConstExpr) { 15163 // FIXME: This shouldn't happen. 15164 if (Loc) *Loc = getExprLoc(); 15165 } 15166 15167 return IsConstExpr; 15168 } 15169 15170 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15171 const FunctionDecl *Callee, 15172 ArrayRef<const Expr*> Args, 15173 const Expr *This) const { 15174 assert(!isValueDependent() && 15175 "Expression evaluator can't be called on a dependent expression."); 15176 15177 Expr::EvalStatus Status; 15178 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15179 Info.InConstantContext = true; 15180 15181 LValue ThisVal; 15182 const LValue *ThisPtr = nullptr; 15183 if (This) { 15184 #ifndef NDEBUG 15185 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15186 assert(MD && "Don't provide `this` for non-methods."); 15187 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15188 #endif 15189 if (!This->isValueDependent() && 15190 EvaluateObjectArgument(Info, This, ThisVal) && 15191 !Info.EvalStatus.HasSideEffects) 15192 ThisPtr = &ThisVal; 15193 15194 // Ignore any side-effects from a failed evaluation. This is safe because 15195 // they can't interfere with any other argument evaluation. 15196 Info.EvalStatus.HasSideEffects = false; 15197 } 15198 15199 ArgVector ArgValues(Args.size()); 15200 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15201 I != E; ++I) { 15202 if ((*I)->isValueDependent() || 15203 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 15204 Info.EvalStatus.HasSideEffects) 15205 // If evaluation fails, throw away the argument entirely. 15206 ArgValues[I - Args.begin()] = APValue(); 15207 15208 // Ignore any side-effects from a failed evaluation. This is safe because 15209 // they can't interfere with any other argument evaluation. 15210 Info.EvalStatus.HasSideEffects = false; 15211 } 15212 15213 // Parameter cleanups happen in the caller and are not part of this 15214 // evaluation. 15215 Info.discardCleanups(); 15216 Info.EvalStatus.HasSideEffects = false; 15217 15218 // Build fake call to Callee. 15219 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 15220 ArgValues.data()); 15221 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15222 FullExpressionRAII Scope(Info); 15223 return Evaluate(Value, Info, this) && Scope.destroy() && 15224 !Info.EvalStatus.HasSideEffects; 15225 } 15226 15227 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15228 SmallVectorImpl< 15229 PartialDiagnosticAt> &Diags) { 15230 // FIXME: It would be useful to check constexpr function templates, but at the 15231 // moment the constant expression evaluator cannot cope with the non-rigorous 15232 // ASTs which we build for dependent expressions. 15233 if (FD->isDependentContext()) 15234 return true; 15235 15236 // Bail out if a constexpr constructor has an initializer that contains an 15237 // error. We deliberately don't produce a diagnostic, as we have produced a 15238 // relevant diagnostic when parsing the error initializer. 15239 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15240 for (const auto *InitExpr : Ctor->inits()) { 15241 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15242 return false; 15243 } 15244 } 15245 Expr::EvalStatus Status; 15246 Status.Diag = &Diags; 15247 15248 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15249 Info.InConstantContext = true; 15250 Info.CheckingPotentialConstantExpression = true; 15251 15252 // The constexpr VM attempts to compile all methods to bytecode here. 15253 if (Info.EnableNewConstInterp) { 15254 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15255 return Diags.empty(); 15256 } 15257 15258 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15259 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15260 15261 // Fabricate an arbitrary expression on the stack and pretend that it 15262 // is a temporary being used as the 'this' pointer. 15263 LValue This; 15264 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15265 This.set({&VIE, Info.CurrentCall->Index}); 15266 15267 ArrayRef<const Expr*> Args; 15268 15269 APValue Scratch; 15270 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15271 // Evaluate the call as a constant initializer, to allow the construction 15272 // of objects of non-literal types. 15273 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15274 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15275 } else { 15276 SourceLocation Loc = FD->getLocation(); 15277 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15278 Args, FD->getBody(), Info, Scratch, nullptr); 15279 } 15280 15281 return Diags.empty(); 15282 } 15283 15284 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15285 const FunctionDecl *FD, 15286 SmallVectorImpl< 15287 PartialDiagnosticAt> &Diags) { 15288 assert(!E->isValueDependent() && 15289 "Expression evaluator can't be called on a dependent expression."); 15290 15291 Expr::EvalStatus Status; 15292 Status.Diag = &Diags; 15293 15294 EvalInfo Info(FD->getASTContext(), Status, 15295 EvalInfo::EM_ConstantExpressionUnevaluated); 15296 Info.InConstantContext = true; 15297 Info.CheckingPotentialConstantExpression = true; 15298 15299 // Fabricate a call stack frame to give the arguments a plausible cover story. 15300 ArrayRef<const Expr*> Args; 15301 ArgVector ArgValues(0); 15302 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 15303 (void)Success; 15304 assert(Success && 15305 "Failed to set up arguments for potential constant evaluation"); 15306 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 15307 15308 APValue ResultScratch; 15309 Evaluate(ResultScratch, Info, E); 15310 return Diags.empty(); 15311 } 15312 15313 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15314 unsigned Type) const { 15315 if (!getType()->isPointerType()) 15316 return false; 15317 15318 Expr::EvalStatus Status; 15319 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15320 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15321 } 15322