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/DiagnosticSema.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "llvm/ADT/APFixedPoint.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/ADT/StringExtras.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/SaveAndRestore.h" 60 #include "llvm/Support/TimeProfiler.h" 61 #include "llvm/Support/raw_ostream.h" 62 #include <cstring> 63 #include <functional> 64 #include <optional> 65 66 #define DEBUG_TYPE "exprconstant" 67 68 using namespace clang; 69 using llvm::APFixedPoint; 70 using llvm::APInt; 71 using llvm::APSInt; 72 using llvm::APFloat; 73 using llvm::FixedPointSemantics; 74 75 namespace { 76 struct LValue; 77 class CallStackFrame; 78 class EvalInfo; 79 80 using SourceLocExprScopeGuard = 81 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 82 83 static QualType getType(APValue::LValueBase B) { 84 return B.getType(); 85 } 86 87 /// Get an LValue path entry, which is known to not be an array index, as a 88 /// field declaration. 89 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 90 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 91 } 92 /// Get an LValue path entry, which is known to not be an array index, as a 93 /// base class declaration. 94 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 95 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 96 } 97 /// Determine whether this LValue path entry for a base class names a virtual 98 /// base class. 99 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 100 return E.getAsBaseOrMember().getInt(); 101 } 102 103 /// Given an expression, determine the type used to store the result of 104 /// evaluating that expression. 105 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 106 if (E->isPRValue()) 107 return E->getType(); 108 return Ctx.getLValueReferenceType(E->getType()); 109 } 110 111 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 112 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 113 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 114 return DirectCallee->getAttr<AllocSizeAttr>(); 115 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 116 return IndirectCallee->getAttr<AllocSizeAttr>(); 117 return nullptr; 118 } 119 120 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 121 /// This will look through a single cast. 122 /// 123 /// Returns null if we couldn't unwrap a function with alloc_size. 124 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 125 if (!E->getType()->isPointerType()) 126 return nullptr; 127 128 E = E->IgnoreParens(); 129 // If we're doing a variable assignment from e.g. malloc(N), there will 130 // probably be a cast of some kind. In exotic cases, we might also see a 131 // top-level ExprWithCleanups. Ignore them either way. 132 if (const auto *FE = dyn_cast<FullExpr>(E)) 133 E = FE->getSubExpr()->IgnoreParens(); 134 135 if (const auto *Cast = dyn_cast<CastExpr>(E)) 136 E = Cast->getSubExpr()->IgnoreParens(); 137 138 if (const auto *CE = dyn_cast<CallExpr>(E)) 139 return getAllocSizeAttr(CE) ? CE : nullptr; 140 return nullptr; 141 } 142 143 /// Determines whether or not the given Base contains a call to a function 144 /// with the alloc_size attribute. 145 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 146 const auto *E = Base.dyn_cast<const Expr *>(); 147 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 148 } 149 150 /// Determines whether the given kind of constant expression is only ever 151 /// used for name mangling. If so, it's permitted to reference things that we 152 /// can't generate code for (in particular, dllimported functions). 153 static bool isForManglingOnly(ConstantExprKind Kind) { 154 switch (Kind) { 155 case ConstantExprKind::Normal: 156 case ConstantExprKind::ClassTemplateArgument: 157 case ConstantExprKind::ImmediateInvocation: 158 // Note that non-type template arguments of class type are emitted as 159 // template parameter objects. 160 return false; 161 162 case ConstantExprKind::NonClassTemplateArgument: 163 return true; 164 } 165 llvm_unreachable("unknown ConstantExprKind"); 166 } 167 168 static bool isTemplateArgument(ConstantExprKind Kind) { 169 switch (Kind) { 170 case ConstantExprKind::Normal: 171 case ConstantExprKind::ImmediateInvocation: 172 return false; 173 174 case ConstantExprKind::ClassTemplateArgument: 175 case ConstantExprKind::NonClassTemplateArgument: 176 return true; 177 } 178 llvm_unreachable("unknown ConstantExprKind"); 179 } 180 181 /// The bound to claim that an array of unknown bound has. 182 /// The value in MostDerivedArraySize is undefined in this case. So, set it 183 /// to an arbitrary value that's likely to loudly break things if it's used. 184 static const uint64_t AssumedSizeForUnsizedArray = 185 std::numeric_limits<uint64_t>::max() / 2; 186 187 /// Determines if an LValue with the given LValueBase will have an unsized 188 /// array in its designator. 189 /// Find the path length and type of the most-derived subobject in the given 190 /// path, and find the size of the containing array, if any. 191 static unsigned 192 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 193 ArrayRef<APValue::LValuePathEntry> Path, 194 uint64_t &ArraySize, QualType &Type, bool &IsArray, 195 bool &FirstEntryIsUnsizedArray) { 196 // This only accepts LValueBases from APValues, and APValues don't support 197 // arrays that lack size info. 198 assert(!isBaseAnAllocSizeCall(Base) && 199 "Unsized arrays shouldn't appear here"); 200 unsigned MostDerivedLength = 0; 201 Type = getType(Base); 202 203 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 204 if (Type->isArrayType()) { 205 const ArrayType *AT = Ctx.getAsArrayType(Type); 206 Type = AT->getElementType(); 207 MostDerivedLength = I + 1; 208 IsArray = true; 209 210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 211 ArraySize = CAT->getSize().getZExtValue(); 212 } else { 213 assert(I == 0 && "unexpected unsized array designator"); 214 FirstEntryIsUnsizedArray = true; 215 ArraySize = AssumedSizeForUnsizedArray; 216 } 217 } else if (Type->isAnyComplexType()) { 218 const ComplexType *CT = Type->castAs<ComplexType>(); 219 Type = CT->getElementType(); 220 ArraySize = 2; 221 MostDerivedLength = I + 1; 222 IsArray = true; 223 } else if (const FieldDecl *FD = getAsField(Path[I])) { 224 Type = FD->getType(); 225 ArraySize = 0; 226 MostDerivedLength = I + 1; 227 IsArray = false; 228 } else { 229 // Path[I] describes a base class. 230 ArraySize = 0; 231 IsArray = false; 232 } 233 } 234 return MostDerivedLength; 235 } 236 237 /// A path from a glvalue to a subobject of that glvalue. 238 struct SubobjectDesignator { 239 /// True if the subobject was named in a manner not supported by C++11. Such 240 /// lvalues can still be folded, but they are not core constant expressions 241 /// and we cannot perform lvalue-to-rvalue conversions on them. 242 unsigned Invalid : 1; 243 244 /// Is this a pointer one past the end of an object? 245 unsigned IsOnePastTheEnd : 1; 246 247 /// Indicator of whether the first entry is an unsized array. 248 unsigned FirstEntryIsAnUnsizedArray : 1; 249 250 /// Indicator of whether the most-derived object is an array element. 251 unsigned MostDerivedIsArrayElement : 1; 252 253 /// The length of the path to the most-derived object of which this is a 254 /// subobject. 255 unsigned MostDerivedPathLength : 28; 256 257 /// The size of the array of which the most-derived object is an element. 258 /// This will always be 0 if the most-derived object is not an array 259 /// element. 0 is not an indicator of whether or not the most-derived object 260 /// is an array, however, because 0-length arrays are allowed. 261 /// 262 /// If the current array is an unsized array, the value of this is 263 /// undefined. 264 uint64_t MostDerivedArraySize; 265 266 /// The type of the most derived object referred to by this address. 267 QualType MostDerivedType; 268 269 typedef APValue::LValuePathEntry PathEntry; 270 271 /// The entries on the path from the glvalue to the designated subobject. 272 SmallVector<PathEntry, 8> Entries; 273 274 SubobjectDesignator() : Invalid(true) {} 275 276 explicit SubobjectDesignator(QualType T) 277 : Invalid(false), IsOnePastTheEnd(false), 278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 279 MostDerivedPathLength(0), MostDerivedArraySize(0), 280 MostDerivedType(T) {} 281 282 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 283 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 284 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 285 MostDerivedPathLength(0), MostDerivedArraySize(0) { 286 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 287 if (!Invalid) { 288 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 289 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 290 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 291 if (V.getLValueBase()) { 292 bool IsArray = false; 293 bool FirstIsUnsizedArray = false; 294 MostDerivedPathLength = findMostDerivedSubobject( 295 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 296 MostDerivedType, IsArray, FirstIsUnsizedArray); 297 MostDerivedIsArrayElement = IsArray; 298 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 299 } 300 } 301 } 302 303 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 304 unsigned NewLength) { 305 if (Invalid) 306 return; 307 308 assert(Base && "cannot truncate path for null pointer"); 309 assert(NewLength <= Entries.size() && "not a truncation"); 310 311 if (NewLength == Entries.size()) 312 return; 313 Entries.resize(NewLength); 314 315 bool IsArray = false; 316 bool FirstIsUnsizedArray = false; 317 MostDerivedPathLength = findMostDerivedSubobject( 318 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 319 FirstIsUnsizedArray); 320 MostDerivedIsArrayElement = IsArray; 321 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 322 } 323 324 void setInvalid() { 325 Invalid = true; 326 Entries.clear(); 327 } 328 329 /// Determine whether the most derived subobject is an array without a 330 /// known bound. 331 bool isMostDerivedAnUnsizedArray() const { 332 assert(!Invalid && "Calling this makes no sense on invalid designators"); 333 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 334 } 335 336 /// Determine what the most derived array's size is. Results in an assertion 337 /// failure if the most derived array lacks a size. 338 uint64_t getMostDerivedArraySize() const { 339 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 340 return MostDerivedArraySize; 341 } 342 343 /// Determine whether this is a one-past-the-end pointer. 344 bool isOnePastTheEnd() const { 345 assert(!Invalid); 346 if (IsOnePastTheEnd) 347 return true; 348 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 349 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 350 MostDerivedArraySize) 351 return true; 352 return false; 353 } 354 355 /// Get the range of valid index adjustments in the form 356 /// {maximum value that can be subtracted from this pointer, 357 /// maximum value that can be added to this pointer} 358 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 359 if (Invalid || isMostDerivedAnUnsizedArray()) 360 return {0, 0}; 361 362 // [expr.add]p4: For the purposes of these operators, a pointer to a 363 // nonarray object behaves the same as a pointer to the first element of 364 // an array of length one with the type of the object as its element type. 365 bool IsArray = MostDerivedPathLength == Entries.size() && 366 MostDerivedIsArrayElement; 367 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 368 : (uint64_t)IsOnePastTheEnd; 369 uint64_t ArraySize = 370 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 371 return {ArrayIndex, ArraySize - ArrayIndex}; 372 } 373 374 /// Check that this refers to a valid subobject. 375 bool isValidSubobject() const { 376 if (Invalid) 377 return false; 378 return !isOnePastTheEnd(); 379 } 380 /// Check that this refers to a valid subobject, and if not, produce a 381 /// relevant diagnostic and set the designator as invalid. 382 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 383 384 /// Get the type of the designated object. 385 QualType getType(ASTContext &Ctx) const { 386 assert(!Invalid && "invalid designator has no subobject type"); 387 return MostDerivedPathLength == Entries.size() 388 ? MostDerivedType 389 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 390 } 391 392 /// Update this designator to refer to the first element within this array. 393 void addArrayUnchecked(const ConstantArrayType *CAT) { 394 Entries.push_back(PathEntry::ArrayIndex(0)); 395 396 // This is a most-derived object. 397 MostDerivedType = CAT->getElementType(); 398 MostDerivedIsArrayElement = true; 399 MostDerivedArraySize = CAT->getSize().getZExtValue(); 400 MostDerivedPathLength = Entries.size(); 401 } 402 /// Update this designator to refer to the first element within the array of 403 /// elements of type T. This is an array of unknown size. 404 void addUnsizedArrayUnchecked(QualType ElemTy) { 405 Entries.push_back(PathEntry::ArrayIndex(0)); 406 407 MostDerivedType = ElemTy; 408 MostDerivedIsArrayElement = true; 409 // The value in MostDerivedArraySize is undefined in this case. So, set it 410 // to an arbitrary value that's likely to loudly break things if it's 411 // used. 412 MostDerivedArraySize = AssumedSizeForUnsizedArray; 413 MostDerivedPathLength = Entries.size(); 414 } 415 /// Update this designator to refer to the given base or member of this 416 /// object. 417 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 418 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 419 420 // If this isn't a base class, it's a new most-derived object. 421 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 422 MostDerivedType = FD->getType(); 423 MostDerivedIsArrayElement = false; 424 MostDerivedArraySize = 0; 425 MostDerivedPathLength = Entries.size(); 426 } 427 } 428 /// Update this designator to refer to the given complex component. 429 void addComplexUnchecked(QualType EltTy, bool Imag) { 430 Entries.push_back(PathEntry::ArrayIndex(Imag)); 431 432 // This is technically a most-derived object, though in practice this 433 // is unlikely to matter. 434 MostDerivedType = EltTy; 435 MostDerivedIsArrayElement = true; 436 MostDerivedArraySize = 2; 437 MostDerivedPathLength = Entries.size(); 438 } 439 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 440 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 441 const APSInt &N); 442 /// Add N to the address of this subobject. 443 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 444 if (Invalid || !N) return; 445 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 446 if (isMostDerivedAnUnsizedArray()) { 447 diagnoseUnsizedArrayPointerArithmetic(Info, E); 448 // Can't verify -- trust that the user is doing the right thing (or if 449 // not, trust that the caller will catch the bad behavior). 450 // FIXME: Should we reject if this overflows, at least? 451 Entries.back() = PathEntry::ArrayIndex( 452 Entries.back().getAsArrayIndex() + TruncatedN); 453 return; 454 } 455 456 // [expr.add]p4: For the purposes of these operators, a pointer to a 457 // nonarray object behaves the same as a pointer to the first element of 458 // an array of length one with the type of the object as its element type. 459 bool IsArray = MostDerivedPathLength == Entries.size() && 460 MostDerivedIsArrayElement; 461 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 462 : (uint64_t)IsOnePastTheEnd; 463 uint64_t ArraySize = 464 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 465 466 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 467 // Calculate the actual index in a wide enough type, so we can include 468 // it in the note. 469 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 470 (llvm::APInt&)N += ArrayIndex; 471 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 472 diagnosePointerArithmetic(Info, E, N); 473 setInvalid(); 474 return; 475 } 476 477 ArrayIndex += TruncatedN; 478 assert(ArrayIndex <= ArraySize && 479 "bounds check succeeded for out-of-bounds index"); 480 481 if (IsArray) 482 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 483 else 484 IsOnePastTheEnd = (ArrayIndex != 0); 485 } 486 }; 487 488 /// A scope at the end of which an object can need to be destroyed. 489 enum class ScopeKind { 490 Block, 491 FullExpression, 492 Call 493 }; 494 495 /// A reference to a particular call and its arguments. 496 struct CallRef { 497 CallRef() : OrigCallee(), CallIndex(0), Version() {} 498 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 499 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 500 501 explicit operator bool() const { return OrigCallee; } 502 503 /// Get the parameter that the caller initialized, corresponding to the 504 /// given parameter in the callee. 505 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 506 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 507 : PVD; 508 } 509 510 /// The callee at the point where the arguments were evaluated. This might 511 /// be different from the actual callee (a different redeclaration, or a 512 /// virtual override), but this function's parameters are the ones that 513 /// appear in the parameter map. 514 const FunctionDecl *OrigCallee; 515 /// The call index of the frame that holds the argument values. 516 unsigned CallIndex; 517 /// The version of the parameters corresponding to this call. 518 unsigned Version; 519 }; 520 521 /// A stack frame in the constexpr call stack. 522 class CallStackFrame : public interp::Frame { 523 public: 524 EvalInfo &Info; 525 526 /// Parent - The caller of this stack frame. 527 CallStackFrame *Caller; 528 529 /// Callee - The function which was called. 530 const FunctionDecl *Callee; 531 532 /// This - The binding for the this pointer in this call, if any. 533 const LValue *This; 534 535 /// CallExpr - The syntactical structure of member function calls 536 const Expr *CallExpr; 537 538 /// Information on how to find the arguments to this call. Our arguments 539 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 540 /// key and this value as the version. 541 CallRef Arguments; 542 543 /// Source location information about the default argument or default 544 /// initializer expression we're evaluating, if any. 545 CurrentSourceLocExprScope CurSourceLocExprScope; 546 547 // Note that we intentionally use std::map here so that references to 548 // values are stable. 549 typedef std::pair<const void *, unsigned> MapKeyTy; 550 typedef std::map<MapKeyTy, APValue> MapTy; 551 /// Temporaries - Temporary lvalues materialized within this stack frame. 552 MapTy Temporaries; 553 554 /// CallLoc - The location of the call expression for this call. 555 SourceLocation CallLoc; 556 557 /// Index - The call index of this call. 558 unsigned Index; 559 560 /// The stack of integers for tracking version numbers for temporaries. 561 SmallVector<unsigned, 2> TempVersionStack = {1}; 562 unsigned CurTempVersion = TempVersionStack.back(); 563 564 unsigned getTempVersion() const { return TempVersionStack.back(); } 565 566 void pushTempVersion() { 567 TempVersionStack.push_back(++CurTempVersion); 568 } 569 570 void popTempVersion() { 571 TempVersionStack.pop_back(); 572 } 573 574 CallRef createCall(const FunctionDecl *Callee) { 575 return {Callee, Index, ++CurTempVersion}; 576 } 577 578 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 579 // on the overall stack usage of deeply-recursing constexpr evaluations. 580 // (We should cache this map rather than recomputing it repeatedly.) 581 // But let's try this and see how it goes; we can look into caching the map 582 // as a later change. 583 584 /// LambdaCaptureFields - Mapping from captured variables/this to 585 /// corresponding data members in the closure class. 586 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; 587 FieldDecl *LambdaThisCaptureField = nullptr; 588 589 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 590 const FunctionDecl *Callee, const LValue *This, 591 const Expr *CallExpr, CallRef Arguments); 592 ~CallStackFrame(); 593 594 // Return the temporary for Key whose version number is Version. 595 APValue *getTemporary(const void *Key, unsigned Version) { 596 MapKeyTy KV(Key, Version); 597 auto LB = Temporaries.lower_bound(KV); 598 if (LB != Temporaries.end() && LB->first == KV) 599 return &LB->second; 600 return nullptr; 601 } 602 603 // Return the current temporary for Key in the map. 604 APValue *getCurrentTemporary(const void *Key) { 605 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 606 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 607 return &std::prev(UB)->second; 608 return nullptr; 609 } 610 611 // Return the version number of the current temporary for Key. 612 unsigned getCurrentTemporaryVersion(const void *Key) const { 613 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 614 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 615 return std::prev(UB)->first.second; 616 return 0; 617 } 618 619 /// Allocate storage for an object of type T in this stack frame. 620 /// Populates LV with a handle to the created object. Key identifies 621 /// the temporary within the stack frame, and must not be reused without 622 /// bumping the temporary version number. 623 template<typename KeyT> 624 APValue &createTemporary(const KeyT *Key, QualType T, 625 ScopeKind Scope, LValue &LV); 626 627 /// Allocate storage for a parameter of a function call made in this frame. 628 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 629 630 void describe(llvm::raw_ostream &OS) const override; 631 632 Frame *getCaller() const override { return Caller; } 633 SourceLocation getCallLocation() const override { return CallLoc; } 634 const FunctionDecl *getCallee() const override { return Callee; } 635 636 bool isStdFunction() const { 637 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 638 if (DC->isStdNamespace()) 639 return true; 640 return false; 641 } 642 643 private: 644 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 645 ScopeKind Scope); 646 }; 647 648 /// Temporarily override 'this'. 649 class ThisOverrideRAII { 650 public: 651 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 652 : Frame(Frame), OldThis(Frame.This) { 653 if (Enable) 654 Frame.This = NewThis; 655 } 656 ~ThisOverrideRAII() { 657 Frame.This = OldThis; 658 } 659 private: 660 CallStackFrame &Frame; 661 const LValue *OldThis; 662 }; 663 664 // A shorthand time trace scope struct, prints source range, for example 665 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}} 666 class ExprTimeTraceScope { 667 public: 668 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name) 669 : TimeScope(Name, [E, &Ctx] { 670 return E->getSourceRange().printToString(Ctx.getSourceManager()); 671 }) {} 672 673 private: 674 llvm::TimeTraceScope TimeScope; 675 }; 676 } 677 678 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 679 const LValue &This, QualType ThisType); 680 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 681 APValue::LValueBase LVBase, APValue &Value, 682 QualType T); 683 684 namespace { 685 /// A cleanup, and a flag indicating whether it is lifetime-extended. 686 class Cleanup { 687 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 688 APValue::LValueBase Base; 689 QualType T; 690 691 public: 692 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 693 ScopeKind Scope) 694 : Value(Val, Scope), Base(Base), T(T) {} 695 696 /// Determine whether this cleanup should be performed at the end of the 697 /// given kind of scope. 698 bool isDestroyedAtEndOf(ScopeKind K) const { 699 return (int)Value.getInt() >= (int)K; 700 } 701 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 702 if (RunDestructors) { 703 SourceLocation Loc; 704 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 705 Loc = VD->getLocation(); 706 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 707 Loc = E->getExprLoc(); 708 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 709 } 710 *Value.getPointer() = APValue(); 711 return true; 712 } 713 714 bool hasSideEffect() { 715 return T.isDestructedType(); 716 } 717 }; 718 719 /// A reference to an object whose construction we are currently evaluating. 720 struct ObjectUnderConstruction { 721 APValue::LValueBase Base; 722 ArrayRef<APValue::LValuePathEntry> Path; 723 friend bool operator==(const ObjectUnderConstruction &LHS, 724 const ObjectUnderConstruction &RHS) { 725 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 726 } 727 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 728 return llvm::hash_combine(Obj.Base, Obj.Path); 729 } 730 }; 731 enum class ConstructionPhase { 732 None, 733 Bases, 734 AfterBases, 735 AfterFields, 736 Destroying, 737 DestroyingBases 738 }; 739 } 740 741 namespace llvm { 742 template<> struct DenseMapInfo<ObjectUnderConstruction> { 743 using Base = DenseMapInfo<APValue::LValueBase>; 744 static ObjectUnderConstruction getEmptyKey() { 745 return {Base::getEmptyKey(), {}}; } 746 static ObjectUnderConstruction getTombstoneKey() { 747 return {Base::getTombstoneKey(), {}}; 748 } 749 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 750 return hash_value(Object); 751 } 752 static bool isEqual(const ObjectUnderConstruction &LHS, 753 const ObjectUnderConstruction &RHS) { 754 return LHS == RHS; 755 } 756 }; 757 } 758 759 namespace { 760 /// A dynamically-allocated heap object. 761 struct DynAlloc { 762 /// The value of this heap-allocated object. 763 APValue Value; 764 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 765 /// or a CallExpr (the latter is for direct calls to operator new inside 766 /// std::allocator<T>::allocate). 767 const Expr *AllocExpr = nullptr; 768 769 enum Kind { 770 New, 771 ArrayNew, 772 StdAllocator 773 }; 774 775 /// Get the kind of the allocation. This must match between allocation 776 /// and deallocation. 777 Kind getKind() const { 778 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 779 return NE->isArray() ? ArrayNew : New; 780 assert(isa<CallExpr>(AllocExpr)); 781 return StdAllocator; 782 } 783 }; 784 785 struct DynAllocOrder { 786 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 787 return L.getIndex() < R.getIndex(); 788 } 789 }; 790 791 /// EvalInfo - This is a private struct used by the evaluator to capture 792 /// information about a subexpression as it is folded. It retains information 793 /// about the AST context, but also maintains information about the folded 794 /// expression. 795 /// 796 /// If an expression could be evaluated, it is still possible it is not a C 797 /// "integer constant expression" or constant expression. If not, this struct 798 /// captures information about how and why not. 799 /// 800 /// One bit of information passed *into* the request for constant folding 801 /// indicates whether the subexpression is "evaluated" or not according to C 802 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 803 /// evaluate the expression regardless of what the RHS is, but C only allows 804 /// certain things in certain situations. 805 class EvalInfo : public interp::State { 806 public: 807 ASTContext &Ctx; 808 809 /// EvalStatus - Contains information about the evaluation. 810 Expr::EvalStatus &EvalStatus; 811 812 /// CurrentCall - The top of the constexpr call stack. 813 CallStackFrame *CurrentCall; 814 815 /// CallStackDepth - The number of calls in the call stack right now. 816 unsigned CallStackDepth; 817 818 /// NextCallIndex - The next call index to assign. 819 unsigned NextCallIndex; 820 821 /// StepsLeft - The remaining number of evaluation steps we're permitted 822 /// to perform. This is essentially a limit for the number of statements 823 /// we will evaluate. 824 unsigned StepsLeft; 825 826 /// Enable the experimental new constant interpreter. If an expression is 827 /// not supported by the interpreter, an error is triggered. 828 bool EnableNewConstInterp; 829 830 /// BottomFrame - The frame in which evaluation started. This must be 831 /// initialized after CurrentCall and CallStackDepth. 832 CallStackFrame BottomFrame; 833 834 /// A stack of values whose lifetimes end at the end of some surrounding 835 /// evaluation frame. 836 llvm::SmallVector<Cleanup, 16> CleanupStack; 837 838 /// EvaluatingDecl - This is the declaration whose initializer is being 839 /// evaluated, if any. 840 APValue::LValueBase EvaluatingDecl; 841 842 enum class EvaluatingDeclKind { 843 None, 844 /// We're evaluating the construction of EvaluatingDecl. 845 Ctor, 846 /// We're evaluating the destruction of EvaluatingDecl. 847 Dtor, 848 }; 849 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 850 851 /// EvaluatingDeclValue - This is the value being constructed for the 852 /// declaration whose initializer is being evaluated, if any. 853 APValue *EvaluatingDeclValue; 854 855 /// Set of objects that are currently being constructed. 856 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 857 ObjectsUnderConstruction; 858 859 /// Current heap allocations, along with the location where each was 860 /// allocated. We use std::map here because we need stable addresses 861 /// for the stored APValues. 862 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 863 864 /// The number of heap allocations performed so far in this evaluation. 865 unsigned NumHeapAllocs = 0; 866 867 struct EvaluatingConstructorRAII { 868 EvalInfo &EI; 869 ObjectUnderConstruction Object; 870 bool DidInsert; 871 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 872 bool HasBases) 873 : EI(EI), Object(Object) { 874 DidInsert = 875 EI.ObjectsUnderConstruction 876 .insert({Object, HasBases ? ConstructionPhase::Bases 877 : ConstructionPhase::AfterBases}) 878 .second; 879 } 880 void finishedConstructingBases() { 881 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 882 } 883 void finishedConstructingFields() { 884 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 885 } 886 ~EvaluatingConstructorRAII() { 887 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 888 } 889 }; 890 891 struct EvaluatingDestructorRAII { 892 EvalInfo &EI; 893 ObjectUnderConstruction Object; 894 bool DidInsert; 895 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 896 : EI(EI), Object(Object) { 897 DidInsert = EI.ObjectsUnderConstruction 898 .insert({Object, ConstructionPhase::Destroying}) 899 .second; 900 } 901 void startedDestroyingBases() { 902 EI.ObjectsUnderConstruction[Object] = 903 ConstructionPhase::DestroyingBases; 904 } 905 ~EvaluatingDestructorRAII() { 906 if (DidInsert) 907 EI.ObjectsUnderConstruction.erase(Object); 908 } 909 }; 910 911 ConstructionPhase 912 isEvaluatingCtorDtor(APValue::LValueBase Base, 913 ArrayRef<APValue::LValuePathEntry> Path) { 914 return ObjectsUnderConstruction.lookup({Base, Path}); 915 } 916 917 /// If we're currently speculatively evaluating, the outermost call stack 918 /// depth at which we can mutate state, otherwise 0. 919 unsigned SpeculativeEvaluationDepth = 0; 920 921 /// The current array initialization index, if we're performing array 922 /// initialization. 923 uint64_t ArrayInitIndex = -1; 924 925 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 926 /// notes attached to it will also be stored, otherwise they will not be. 927 bool HasActiveDiagnostic; 928 929 /// Have we emitted a diagnostic explaining why we couldn't constant 930 /// fold (not just why it's not strictly a constant expression)? 931 bool HasFoldFailureDiagnostic; 932 933 /// Whether we're checking that an expression is a potential constant 934 /// expression. If so, do not fail on constructs that could become constant 935 /// later on (such as a use of an undefined global). 936 bool CheckingPotentialConstantExpression = false; 937 938 /// Whether we're checking for an expression that has undefined behavior. 939 /// If so, we will produce warnings if we encounter an operation that is 940 /// always undefined. 941 /// 942 /// Note that we still need to evaluate the expression normally when this 943 /// is set; this is used when evaluating ICEs in C. 944 bool CheckingForUndefinedBehavior = false; 945 946 enum EvaluationMode { 947 /// Evaluate as a constant expression. Stop if we find that the expression 948 /// is not a constant expression. 949 EM_ConstantExpression, 950 951 /// Evaluate as a constant expression. Stop if we find that the expression 952 /// is not a constant expression. Some expressions can be retried in the 953 /// optimizer if we don't constant fold them here, but in an unevaluated 954 /// context we try to fold them immediately since the optimizer never 955 /// gets a chance to look at it. 956 EM_ConstantExpressionUnevaluated, 957 958 /// Fold the expression to a constant. Stop if we hit a side-effect that 959 /// we can't model. 960 EM_ConstantFold, 961 962 /// Evaluate in any way we know how. Don't worry about side-effects that 963 /// can't be modeled. 964 EM_IgnoreSideEffects, 965 } EvalMode; 966 967 /// Are we checking whether the expression is a potential constant 968 /// expression? 969 bool checkingPotentialConstantExpression() const override { 970 return CheckingPotentialConstantExpression; 971 } 972 973 /// Are we checking an expression for overflow? 974 // FIXME: We should check for any kind of undefined or suspicious behavior 975 // in such constructs, not just overflow. 976 bool checkingForUndefinedBehavior() const override { 977 return CheckingForUndefinedBehavior; 978 } 979 980 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 981 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 982 CallStackDepth(0), NextCallIndex(1), 983 StepsLeft(C.getLangOpts().ConstexprStepLimit), 984 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 985 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr, 986 /*This=*/nullptr, 987 /*CallExpr=*/nullptr, CallRef()), 988 EvaluatingDecl((const ValueDecl *)nullptr), 989 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 990 HasFoldFailureDiagnostic(false), EvalMode(Mode) {} 991 992 ~EvalInfo() { 993 discardCleanups(); 994 } 995 996 ASTContext &getCtx() const override { return Ctx; } 997 998 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 999 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 1000 EvaluatingDecl = Base; 1001 IsEvaluatingDecl = EDK; 1002 EvaluatingDeclValue = &Value; 1003 } 1004 1005 bool CheckCallLimit(SourceLocation Loc) { 1006 // Don't perform any constexpr calls (other than the call we're checking) 1007 // when checking a potential constant expression. 1008 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 1009 return false; 1010 if (NextCallIndex == 0) { 1011 // NextCallIndex has wrapped around. 1012 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1013 return false; 1014 } 1015 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1016 return true; 1017 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1018 << getLangOpts().ConstexprCallDepth; 1019 return false; 1020 } 1021 1022 std::pair<CallStackFrame *, unsigned> 1023 getCallFrameAndDepth(unsigned CallIndex) { 1024 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1025 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1026 // be null in this loop. 1027 unsigned Depth = CallStackDepth; 1028 CallStackFrame *Frame = CurrentCall; 1029 while (Frame->Index > CallIndex) { 1030 Frame = Frame->Caller; 1031 --Depth; 1032 } 1033 if (Frame->Index == CallIndex) 1034 return {Frame, Depth}; 1035 return {nullptr, 0}; 1036 } 1037 1038 bool nextStep(const Stmt *S) { 1039 if (!StepsLeft) { 1040 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1041 return false; 1042 } 1043 --StepsLeft; 1044 return true; 1045 } 1046 1047 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1048 1049 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) { 1050 std::optional<DynAlloc *> Result; 1051 auto It = HeapAllocs.find(DA); 1052 if (It != HeapAllocs.end()) 1053 Result = &It->second; 1054 return Result; 1055 } 1056 1057 /// Get the allocated storage for the given parameter of the given call. 1058 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1059 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1060 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1061 : nullptr; 1062 } 1063 1064 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1065 struct StdAllocatorCaller { 1066 unsigned FrameIndex; 1067 QualType ElemType; 1068 explicit operator bool() const { return FrameIndex != 0; }; 1069 }; 1070 1071 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1072 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1073 Call = Call->Caller) { 1074 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1075 if (!MD) 1076 continue; 1077 const IdentifierInfo *FnII = MD->getIdentifier(); 1078 if (!FnII || !FnII->isStr(FnName)) 1079 continue; 1080 1081 const auto *CTSD = 1082 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1083 if (!CTSD) 1084 continue; 1085 1086 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1087 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1088 if (CTSD->isInStdNamespace() && ClassII && 1089 ClassII->isStr("allocator") && TAL.size() >= 1 && 1090 TAL[0].getKind() == TemplateArgument::Type) 1091 return {Call->Index, TAL[0].getAsType()}; 1092 } 1093 1094 return {}; 1095 } 1096 1097 void performLifetimeExtension() { 1098 // Disable the cleanups for lifetime-extended temporaries. 1099 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1100 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1101 }); 1102 } 1103 1104 /// Throw away any remaining cleanups at the end of evaluation. If any 1105 /// cleanups would have had a side-effect, note that as an unmodeled 1106 /// side-effect and return false. Otherwise, return true. 1107 bool discardCleanups() { 1108 for (Cleanup &C : CleanupStack) { 1109 if (C.hasSideEffect() && !noteSideEffect()) { 1110 CleanupStack.clear(); 1111 return false; 1112 } 1113 } 1114 CleanupStack.clear(); 1115 return true; 1116 } 1117 1118 private: 1119 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1120 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1121 1122 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1123 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1124 1125 void setFoldFailureDiagnostic(bool Flag) override { 1126 HasFoldFailureDiagnostic = Flag; 1127 } 1128 1129 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1130 1131 // If we have a prior diagnostic, it will be noting that the expression 1132 // isn't a constant expression. This diagnostic is more important, 1133 // unless we require this evaluation to produce a constant expression. 1134 // 1135 // FIXME: We might want to show both diagnostics to the user in 1136 // EM_ConstantFold mode. 1137 bool hasPriorDiagnostic() override { 1138 if (!EvalStatus.Diag->empty()) { 1139 switch (EvalMode) { 1140 case EM_ConstantFold: 1141 case EM_IgnoreSideEffects: 1142 if (!HasFoldFailureDiagnostic) 1143 break; 1144 // We've already failed to fold something. Keep that diagnostic. 1145 [[fallthrough]]; 1146 case EM_ConstantExpression: 1147 case EM_ConstantExpressionUnevaluated: 1148 setActiveDiagnostic(false); 1149 return true; 1150 } 1151 } 1152 return false; 1153 } 1154 1155 unsigned getCallStackDepth() override { return CallStackDepth; } 1156 1157 public: 1158 /// Should we continue evaluation after encountering a side-effect that we 1159 /// couldn't model? 1160 bool keepEvaluatingAfterSideEffect() { 1161 switch (EvalMode) { 1162 case EM_IgnoreSideEffects: 1163 return true; 1164 1165 case EM_ConstantExpression: 1166 case EM_ConstantExpressionUnevaluated: 1167 case EM_ConstantFold: 1168 // By default, assume any side effect might be valid in some other 1169 // evaluation of this expression from a different context. 1170 return checkingPotentialConstantExpression() || 1171 checkingForUndefinedBehavior(); 1172 } 1173 llvm_unreachable("Missed EvalMode case"); 1174 } 1175 1176 /// Note that we have had a side-effect, and determine whether we should 1177 /// keep evaluating. 1178 bool noteSideEffect() { 1179 EvalStatus.HasSideEffects = true; 1180 return keepEvaluatingAfterSideEffect(); 1181 } 1182 1183 /// Should we continue evaluation after encountering undefined behavior? 1184 bool keepEvaluatingAfterUndefinedBehavior() { 1185 switch (EvalMode) { 1186 case EM_IgnoreSideEffects: 1187 case EM_ConstantFold: 1188 return true; 1189 1190 case EM_ConstantExpression: 1191 case EM_ConstantExpressionUnevaluated: 1192 return checkingForUndefinedBehavior(); 1193 } 1194 llvm_unreachable("Missed EvalMode case"); 1195 } 1196 1197 /// Note that we hit something that was technically undefined behavior, but 1198 /// that we can evaluate past it (such as signed overflow or floating-point 1199 /// division by zero.) 1200 bool noteUndefinedBehavior() override { 1201 EvalStatus.HasUndefinedBehavior = true; 1202 return keepEvaluatingAfterUndefinedBehavior(); 1203 } 1204 1205 /// Should we continue evaluation as much as possible after encountering a 1206 /// construct which can't be reduced to a value? 1207 bool keepEvaluatingAfterFailure() const override { 1208 if (!StepsLeft) 1209 return false; 1210 1211 switch (EvalMode) { 1212 case EM_ConstantExpression: 1213 case EM_ConstantExpressionUnevaluated: 1214 case EM_ConstantFold: 1215 case EM_IgnoreSideEffects: 1216 return checkingPotentialConstantExpression() || 1217 checkingForUndefinedBehavior(); 1218 } 1219 llvm_unreachable("Missed EvalMode case"); 1220 } 1221 1222 /// Notes that we failed to evaluate an expression that other expressions 1223 /// directly depend on, and determine if we should keep evaluating. This 1224 /// should only be called if we actually intend to keep evaluating. 1225 /// 1226 /// Call noteSideEffect() instead if we may be able to ignore the value that 1227 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1228 /// 1229 /// (Foo(), 1) // use noteSideEffect 1230 /// (Foo() || true) // use noteSideEffect 1231 /// Foo() + 1 // use noteFailure 1232 [[nodiscard]] bool noteFailure() { 1233 // Failure when evaluating some expression often means there is some 1234 // subexpression whose evaluation was skipped. Therefore, (because we 1235 // don't track whether we skipped an expression when unwinding after an 1236 // evaluation failure) every evaluation failure that bubbles up from a 1237 // subexpression implies that a side-effect has potentially happened. We 1238 // skip setting the HasSideEffects flag to true until we decide to 1239 // continue evaluating after that point, which happens here. 1240 bool KeepGoing = keepEvaluatingAfterFailure(); 1241 EvalStatus.HasSideEffects |= KeepGoing; 1242 return KeepGoing; 1243 } 1244 1245 class ArrayInitLoopIndex { 1246 EvalInfo &Info; 1247 uint64_t OuterIndex; 1248 1249 public: 1250 ArrayInitLoopIndex(EvalInfo &Info) 1251 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1252 Info.ArrayInitIndex = 0; 1253 } 1254 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1255 1256 operator uint64_t&() { return Info.ArrayInitIndex; } 1257 }; 1258 }; 1259 1260 /// Object used to treat all foldable expressions as constant expressions. 1261 struct FoldConstant { 1262 EvalInfo &Info; 1263 bool Enabled; 1264 bool HadNoPriorDiags; 1265 EvalInfo::EvaluationMode OldMode; 1266 1267 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1268 : Info(Info), 1269 Enabled(Enabled), 1270 HadNoPriorDiags(Info.EvalStatus.Diag && 1271 Info.EvalStatus.Diag->empty() && 1272 !Info.EvalStatus.HasSideEffects), 1273 OldMode(Info.EvalMode) { 1274 if (Enabled) 1275 Info.EvalMode = EvalInfo::EM_ConstantFold; 1276 } 1277 void keepDiagnostics() { Enabled = false; } 1278 ~FoldConstant() { 1279 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1280 !Info.EvalStatus.HasSideEffects) 1281 Info.EvalStatus.Diag->clear(); 1282 Info.EvalMode = OldMode; 1283 } 1284 }; 1285 1286 /// RAII object used to set the current evaluation mode to ignore 1287 /// side-effects. 1288 struct IgnoreSideEffectsRAII { 1289 EvalInfo &Info; 1290 EvalInfo::EvaluationMode OldMode; 1291 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1292 : Info(Info), OldMode(Info.EvalMode) { 1293 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1294 } 1295 1296 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1297 }; 1298 1299 /// RAII object used to optionally suppress diagnostics and side-effects from 1300 /// a speculative evaluation. 1301 class SpeculativeEvaluationRAII { 1302 EvalInfo *Info = nullptr; 1303 Expr::EvalStatus OldStatus; 1304 unsigned OldSpeculativeEvaluationDepth = 0; 1305 1306 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1307 Info = Other.Info; 1308 OldStatus = Other.OldStatus; 1309 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1310 Other.Info = nullptr; 1311 } 1312 1313 void maybeRestoreState() { 1314 if (!Info) 1315 return; 1316 1317 Info->EvalStatus = OldStatus; 1318 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1319 } 1320 1321 public: 1322 SpeculativeEvaluationRAII() = default; 1323 1324 SpeculativeEvaluationRAII( 1325 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1326 : Info(&Info), OldStatus(Info.EvalStatus), 1327 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1328 Info.EvalStatus.Diag = NewDiag; 1329 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1330 } 1331 1332 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1333 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1334 moveFromAndCancel(std::move(Other)); 1335 } 1336 1337 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1338 maybeRestoreState(); 1339 moveFromAndCancel(std::move(Other)); 1340 return *this; 1341 } 1342 1343 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1344 }; 1345 1346 /// RAII object wrapping a full-expression or block scope, and handling 1347 /// the ending of the lifetime of temporaries created within it. 1348 template<ScopeKind Kind> 1349 class ScopeRAII { 1350 EvalInfo &Info; 1351 unsigned OldStackSize; 1352 public: 1353 ScopeRAII(EvalInfo &Info) 1354 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1355 // Push a new temporary version. This is needed to distinguish between 1356 // temporaries created in different iterations of a loop. 1357 Info.CurrentCall->pushTempVersion(); 1358 } 1359 bool destroy(bool RunDestructors = true) { 1360 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1361 OldStackSize = -1U; 1362 return OK; 1363 } 1364 ~ScopeRAII() { 1365 if (OldStackSize != -1U) 1366 destroy(false); 1367 // Body moved to a static method to encourage the compiler to inline away 1368 // instances of this class. 1369 Info.CurrentCall->popTempVersion(); 1370 } 1371 private: 1372 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1373 unsigned OldStackSize) { 1374 assert(OldStackSize <= Info.CleanupStack.size() && 1375 "running cleanups out of order?"); 1376 1377 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1378 // for a full-expression scope. 1379 bool Success = true; 1380 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1381 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1382 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1383 Success = false; 1384 break; 1385 } 1386 } 1387 } 1388 1389 // Compact any retained cleanups. 1390 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1391 if (Kind != ScopeKind::Block) 1392 NewEnd = 1393 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1394 return C.isDestroyedAtEndOf(Kind); 1395 }); 1396 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1397 return Success; 1398 } 1399 }; 1400 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1401 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1402 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1403 } 1404 1405 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1406 CheckSubobjectKind CSK) { 1407 if (Invalid) 1408 return false; 1409 if (isOnePastTheEnd()) { 1410 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1411 << CSK; 1412 setInvalid(); 1413 return false; 1414 } 1415 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1416 // must actually be at least one array element; even a VLA cannot have a 1417 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1418 return true; 1419 } 1420 1421 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1422 const Expr *E) { 1423 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1424 // Do not set the designator as invalid: we can represent this situation, 1425 // and correct handling of __builtin_object_size requires us to do so. 1426 } 1427 1428 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1429 const Expr *E, 1430 const APSInt &N) { 1431 // If we're complaining, we must be able to statically determine the size of 1432 // the most derived array. 1433 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1434 Info.CCEDiag(E, diag::note_constexpr_array_index) 1435 << N << /*array*/ 0 1436 << static_cast<unsigned>(getMostDerivedArraySize()); 1437 else 1438 Info.CCEDiag(E, diag::note_constexpr_array_index) 1439 << N << /*non-array*/ 1; 1440 setInvalid(); 1441 } 1442 1443 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1444 const FunctionDecl *Callee, const LValue *This, 1445 const Expr *CallExpr, CallRef Call) 1446 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1447 CallExpr(CallExpr), Arguments(Call), CallLoc(CallLoc), 1448 Index(Info.NextCallIndex++) { 1449 Info.CurrentCall = this; 1450 ++Info.CallStackDepth; 1451 } 1452 1453 CallStackFrame::~CallStackFrame() { 1454 assert(Info.CurrentCall == this && "calls retired out of order"); 1455 --Info.CallStackDepth; 1456 Info.CurrentCall = Caller; 1457 } 1458 1459 static bool isRead(AccessKinds AK) { 1460 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1461 } 1462 1463 static bool isModification(AccessKinds AK) { 1464 switch (AK) { 1465 case AK_Read: 1466 case AK_ReadObjectRepresentation: 1467 case AK_MemberCall: 1468 case AK_DynamicCast: 1469 case AK_TypeId: 1470 return false; 1471 case AK_Assign: 1472 case AK_Increment: 1473 case AK_Decrement: 1474 case AK_Construct: 1475 case AK_Destroy: 1476 return true; 1477 } 1478 llvm_unreachable("unknown access kind"); 1479 } 1480 1481 static bool isAnyAccess(AccessKinds AK) { 1482 return isRead(AK) || isModification(AK); 1483 } 1484 1485 /// Is this an access per the C++ definition? 1486 static bool isFormalAccess(AccessKinds AK) { 1487 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1488 } 1489 1490 /// Is this kind of axcess valid on an indeterminate object value? 1491 static bool isValidIndeterminateAccess(AccessKinds AK) { 1492 switch (AK) { 1493 case AK_Read: 1494 case AK_Increment: 1495 case AK_Decrement: 1496 // These need the object's value. 1497 return false; 1498 1499 case AK_ReadObjectRepresentation: 1500 case AK_Assign: 1501 case AK_Construct: 1502 case AK_Destroy: 1503 // Construction and destruction don't need the value. 1504 return true; 1505 1506 case AK_MemberCall: 1507 case AK_DynamicCast: 1508 case AK_TypeId: 1509 // These aren't really meaningful on scalars. 1510 return true; 1511 } 1512 llvm_unreachable("unknown access kind"); 1513 } 1514 1515 namespace { 1516 struct ComplexValue { 1517 private: 1518 bool IsInt; 1519 1520 public: 1521 APSInt IntReal, IntImag; 1522 APFloat FloatReal, FloatImag; 1523 1524 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1525 1526 void makeComplexFloat() { IsInt = false; } 1527 bool isComplexFloat() const { return !IsInt; } 1528 APFloat &getComplexFloatReal() { return FloatReal; } 1529 APFloat &getComplexFloatImag() { return FloatImag; } 1530 1531 void makeComplexInt() { IsInt = true; } 1532 bool isComplexInt() const { return IsInt; } 1533 APSInt &getComplexIntReal() { return IntReal; } 1534 APSInt &getComplexIntImag() { return IntImag; } 1535 1536 void moveInto(APValue &v) const { 1537 if (isComplexFloat()) 1538 v = APValue(FloatReal, FloatImag); 1539 else 1540 v = APValue(IntReal, IntImag); 1541 } 1542 void setFrom(const APValue &v) { 1543 assert(v.isComplexFloat() || v.isComplexInt()); 1544 if (v.isComplexFloat()) { 1545 makeComplexFloat(); 1546 FloatReal = v.getComplexFloatReal(); 1547 FloatImag = v.getComplexFloatImag(); 1548 } else { 1549 makeComplexInt(); 1550 IntReal = v.getComplexIntReal(); 1551 IntImag = v.getComplexIntImag(); 1552 } 1553 } 1554 }; 1555 1556 struct LValue { 1557 APValue::LValueBase Base; 1558 CharUnits Offset; 1559 SubobjectDesignator Designator; 1560 bool IsNullPtr : 1; 1561 bool InvalidBase : 1; 1562 1563 const APValue::LValueBase getLValueBase() const { return Base; } 1564 CharUnits &getLValueOffset() { return Offset; } 1565 const CharUnits &getLValueOffset() const { return Offset; } 1566 SubobjectDesignator &getLValueDesignator() { return Designator; } 1567 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1568 bool isNullPointer() const { return IsNullPtr;} 1569 1570 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1571 unsigned getLValueVersion() const { return Base.getVersion(); } 1572 1573 void moveInto(APValue &V) const { 1574 if (Designator.Invalid) 1575 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1576 else { 1577 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1578 V = APValue(Base, Offset, Designator.Entries, 1579 Designator.IsOnePastTheEnd, IsNullPtr); 1580 } 1581 } 1582 void setFrom(ASTContext &Ctx, const APValue &V) { 1583 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1584 Base = V.getLValueBase(); 1585 Offset = V.getLValueOffset(); 1586 InvalidBase = false; 1587 Designator = SubobjectDesignator(Ctx, V); 1588 IsNullPtr = V.isNullPointer(); 1589 } 1590 1591 void set(APValue::LValueBase B, bool BInvalid = false) { 1592 #ifndef NDEBUG 1593 // We only allow a few types of invalid bases. Enforce that here. 1594 if (BInvalid) { 1595 const auto *E = B.get<const Expr *>(); 1596 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1597 "Unexpected type of invalid base"); 1598 } 1599 #endif 1600 1601 Base = B; 1602 Offset = CharUnits::fromQuantity(0); 1603 InvalidBase = BInvalid; 1604 Designator = SubobjectDesignator(getType(B)); 1605 IsNullPtr = false; 1606 } 1607 1608 void setNull(ASTContext &Ctx, QualType PointerTy) { 1609 Base = (const ValueDecl *)nullptr; 1610 Offset = 1611 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1612 InvalidBase = false; 1613 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1614 IsNullPtr = true; 1615 } 1616 1617 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1618 set(B, true); 1619 } 1620 1621 std::string toString(ASTContext &Ctx, QualType T) const { 1622 APValue Printable; 1623 moveInto(Printable); 1624 return Printable.getAsString(Ctx, T); 1625 } 1626 1627 private: 1628 // Check that this LValue is not based on a null pointer. If it is, produce 1629 // a diagnostic and mark the designator as invalid. 1630 template <typename GenDiagType> 1631 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1632 if (Designator.Invalid) 1633 return false; 1634 if (IsNullPtr) { 1635 GenDiag(); 1636 Designator.setInvalid(); 1637 return false; 1638 } 1639 return true; 1640 } 1641 1642 public: 1643 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1644 CheckSubobjectKind CSK) { 1645 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1646 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1647 }); 1648 } 1649 1650 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1651 AccessKinds AK) { 1652 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1653 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1654 }); 1655 } 1656 1657 // Check this LValue refers to an object. If not, set the designator to be 1658 // invalid and emit a diagnostic. 1659 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1660 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1661 Designator.checkSubobject(Info, E, CSK); 1662 } 1663 1664 void addDecl(EvalInfo &Info, const Expr *E, 1665 const Decl *D, bool Virtual = false) { 1666 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1667 Designator.addDeclUnchecked(D, Virtual); 1668 } 1669 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1670 if (!Designator.Entries.empty()) { 1671 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1672 Designator.setInvalid(); 1673 return; 1674 } 1675 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1676 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1677 Designator.FirstEntryIsAnUnsizedArray = true; 1678 Designator.addUnsizedArrayUnchecked(ElemTy); 1679 } 1680 } 1681 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1682 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1683 Designator.addArrayUnchecked(CAT); 1684 } 1685 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1686 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1687 Designator.addComplexUnchecked(EltTy, Imag); 1688 } 1689 void clearIsNullPointer() { 1690 IsNullPtr = false; 1691 } 1692 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1693 const APSInt &Index, CharUnits ElementSize) { 1694 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1695 // but we're not required to diagnose it and it's valid in C++.) 1696 if (!Index) 1697 return; 1698 1699 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1700 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1701 // offsets. 1702 uint64_t Offset64 = Offset.getQuantity(); 1703 uint64_t ElemSize64 = ElementSize.getQuantity(); 1704 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1705 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1706 1707 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1708 Designator.adjustIndex(Info, E, Index); 1709 clearIsNullPointer(); 1710 } 1711 void adjustOffset(CharUnits N) { 1712 Offset += N; 1713 if (N.getQuantity()) 1714 clearIsNullPointer(); 1715 } 1716 }; 1717 1718 struct MemberPtr { 1719 MemberPtr() {} 1720 explicit MemberPtr(const ValueDecl *Decl) 1721 : DeclAndIsDerivedMember(Decl, false) {} 1722 1723 /// The member or (direct or indirect) field referred to by this member 1724 /// pointer, or 0 if this is a null member pointer. 1725 const ValueDecl *getDecl() const { 1726 return DeclAndIsDerivedMember.getPointer(); 1727 } 1728 /// Is this actually a member of some type derived from the relevant class? 1729 bool isDerivedMember() const { 1730 return DeclAndIsDerivedMember.getInt(); 1731 } 1732 /// Get the class which the declaration actually lives in. 1733 const CXXRecordDecl *getContainingRecord() const { 1734 return cast<CXXRecordDecl>( 1735 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1736 } 1737 1738 void moveInto(APValue &V) const { 1739 V = APValue(getDecl(), isDerivedMember(), Path); 1740 } 1741 void setFrom(const APValue &V) { 1742 assert(V.isMemberPointer()); 1743 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1744 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1745 Path.clear(); 1746 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1747 Path.insert(Path.end(), P.begin(), P.end()); 1748 } 1749 1750 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1751 /// whether the member is a member of some class derived from the class type 1752 /// of the member pointer. 1753 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1754 /// Path - The path of base/derived classes from the member declaration's 1755 /// class (exclusive) to the class type of the member pointer (inclusive). 1756 SmallVector<const CXXRecordDecl*, 4> Path; 1757 1758 /// Perform a cast towards the class of the Decl (either up or down the 1759 /// hierarchy). 1760 bool castBack(const CXXRecordDecl *Class) { 1761 assert(!Path.empty()); 1762 const CXXRecordDecl *Expected; 1763 if (Path.size() >= 2) 1764 Expected = Path[Path.size() - 2]; 1765 else 1766 Expected = getContainingRecord(); 1767 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1768 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1769 // if B does not contain the original member and is not a base or 1770 // derived class of the class containing the original member, the result 1771 // of the cast is undefined. 1772 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1773 // (D::*). We consider that to be a language defect. 1774 return false; 1775 } 1776 Path.pop_back(); 1777 return true; 1778 } 1779 /// Perform a base-to-derived member pointer cast. 1780 bool castToDerived(const CXXRecordDecl *Derived) { 1781 if (!getDecl()) 1782 return true; 1783 if (!isDerivedMember()) { 1784 Path.push_back(Derived); 1785 return true; 1786 } 1787 if (!castBack(Derived)) 1788 return false; 1789 if (Path.empty()) 1790 DeclAndIsDerivedMember.setInt(false); 1791 return true; 1792 } 1793 /// Perform a derived-to-base member pointer cast. 1794 bool castToBase(const CXXRecordDecl *Base) { 1795 if (!getDecl()) 1796 return true; 1797 if (Path.empty()) 1798 DeclAndIsDerivedMember.setInt(true); 1799 if (isDerivedMember()) { 1800 Path.push_back(Base); 1801 return true; 1802 } 1803 return castBack(Base); 1804 } 1805 }; 1806 1807 /// Compare two member pointers, which are assumed to be of the same type. 1808 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1809 if (!LHS.getDecl() || !RHS.getDecl()) 1810 return !LHS.getDecl() && !RHS.getDecl(); 1811 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1812 return false; 1813 return LHS.Path == RHS.Path; 1814 } 1815 } 1816 1817 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1818 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1819 const LValue &This, const Expr *E, 1820 bool AllowNonLiteralTypes = false); 1821 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1822 bool InvalidBaseOK = false); 1823 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1824 bool InvalidBaseOK = false); 1825 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1826 EvalInfo &Info); 1827 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1828 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1829 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1830 EvalInfo &Info); 1831 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1832 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1833 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1834 EvalInfo &Info); 1835 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1836 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1837 EvalInfo &Info); 1838 1839 /// Evaluate an integer or fixed point expression into an APResult. 1840 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1841 EvalInfo &Info); 1842 1843 /// Evaluate only a fixed point expression into an APResult. 1844 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1845 EvalInfo &Info); 1846 1847 //===----------------------------------------------------------------------===// 1848 // Misc utilities 1849 //===----------------------------------------------------------------------===// 1850 1851 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1852 /// preserving its value (by extending by up to one bit as needed). 1853 static void negateAsSigned(APSInt &Int) { 1854 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1855 Int = Int.extend(Int.getBitWidth() + 1); 1856 Int.setIsSigned(true); 1857 } 1858 Int = -Int; 1859 } 1860 1861 template<typename KeyT> 1862 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1863 ScopeKind Scope, LValue &LV) { 1864 unsigned Version = getTempVersion(); 1865 APValue::LValueBase Base(Key, Index, Version); 1866 LV.set(Base); 1867 return createLocal(Base, Key, T, Scope); 1868 } 1869 1870 /// Allocate storage for a parameter of a function call made in this frame. 1871 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1872 LValue &LV) { 1873 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1874 APValue::LValueBase Base(PVD, Index, Args.Version); 1875 LV.set(Base); 1876 // We always destroy parameters at the end of the call, even if we'd allow 1877 // them to live to the end of the full-expression at runtime, in order to 1878 // give portable results and match other compilers. 1879 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1880 } 1881 1882 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1883 QualType T, ScopeKind Scope) { 1884 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1885 unsigned Version = Base.getVersion(); 1886 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1887 assert(Result.isAbsent() && "local created multiple times"); 1888 1889 // If we're creating a local immediately in the operand of a speculative 1890 // evaluation, don't register a cleanup to be run outside the speculative 1891 // evaluation context, since we won't actually be able to initialize this 1892 // object. 1893 if (Index <= Info.SpeculativeEvaluationDepth) { 1894 if (T.isDestructedType()) 1895 Info.noteSideEffect(); 1896 } else { 1897 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1898 } 1899 return Result; 1900 } 1901 1902 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1903 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1904 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1905 return nullptr; 1906 } 1907 1908 DynamicAllocLValue DA(NumHeapAllocs++); 1909 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1910 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1911 std::forward_as_tuple(DA), std::tuple<>()); 1912 assert(Result.second && "reused a heap alloc index?"); 1913 Result.first->second.AllocExpr = E; 1914 return &Result.first->second.Value; 1915 } 1916 1917 /// Produce a string describing the given constexpr call. 1918 void CallStackFrame::describe(raw_ostream &Out) const { 1919 unsigned ArgIndex = 0; 1920 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1921 !isa<CXXConstructorDecl>(Callee) && 1922 cast<CXXMethodDecl>(Callee)->isInstance(); 1923 1924 if (!IsMemberCall) 1925 Out << *Callee << '('; 1926 1927 if (This && IsMemberCall) { 1928 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) { 1929 const Expr *Object = MCE->getImplicitObjectArgument(); 1930 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(), 1931 /*Indentation=*/0); 1932 if (Object->getType()->isPointerType()) 1933 Out << "->"; 1934 else 1935 Out << "."; 1936 } else if (const auto *OCE = 1937 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) { 1938 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, 1939 Info.Ctx.getPrintingPolicy(), 1940 /*Indentation=*/0); 1941 Out << "."; 1942 } else { 1943 APValue Val; 1944 This->moveInto(Val); 1945 Val.printPretty( 1946 Out, Info.Ctx, 1947 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType)); 1948 Out << "."; 1949 } 1950 Out << *Callee << '('; 1951 IsMemberCall = false; 1952 } 1953 1954 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1955 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1956 if (ArgIndex > (unsigned)IsMemberCall) 1957 Out << ", "; 1958 1959 const ParmVarDecl *Param = *I; 1960 APValue *V = Info.getParamSlot(Arguments, Param); 1961 if (V) 1962 V->printPretty(Out, Info.Ctx, Param->getType()); 1963 else 1964 Out << "<...>"; 1965 1966 if (ArgIndex == 0 && IsMemberCall) 1967 Out << "->" << *Callee << '('; 1968 } 1969 1970 Out << ')'; 1971 } 1972 1973 /// Evaluate an expression to see if it had side-effects, and discard its 1974 /// result. 1975 /// \return \c true if the caller should keep evaluating. 1976 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1977 assert(!E->isValueDependent()); 1978 APValue Scratch; 1979 if (!Evaluate(Scratch, Info, E)) 1980 // We don't need the value, but we might have skipped a side effect here. 1981 return Info.noteSideEffect(); 1982 return true; 1983 } 1984 1985 /// Should this call expression be treated as a no-op? 1986 static bool IsNoOpCall(const CallExpr *E) { 1987 unsigned Builtin = E->getBuiltinCallee(); 1988 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1989 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 1990 Builtin == Builtin::BI__builtin_function_start); 1991 } 1992 1993 static bool IsGlobalLValue(APValue::LValueBase B) { 1994 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1995 // constant expression of pointer type that evaluates to... 1996 1997 // ... a null pointer value, or a prvalue core constant expression of type 1998 // std::nullptr_t. 1999 if (!B) 2000 return true; 2001 2002 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 2003 // ... the address of an object with static storage duration, 2004 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 2005 return VD->hasGlobalStorage(); 2006 if (isa<TemplateParamObjectDecl>(D)) 2007 return true; 2008 // ... the address of a function, 2009 // ... the address of a GUID [MS extension], 2010 // ... the address of an unnamed global constant 2011 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D); 2012 } 2013 2014 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 2015 return true; 2016 2017 const Expr *E = B.get<const Expr*>(); 2018 switch (E->getStmtClass()) { 2019 default: 2020 return false; 2021 case Expr::CompoundLiteralExprClass: { 2022 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 2023 return CLE->isFileScope() && CLE->isLValue(); 2024 } 2025 case Expr::MaterializeTemporaryExprClass: 2026 // A materialized temporary might have been lifetime-extended to static 2027 // storage duration. 2028 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2029 // A string literal has static storage duration. 2030 case Expr::StringLiteralClass: 2031 case Expr::PredefinedExprClass: 2032 case Expr::ObjCStringLiteralClass: 2033 case Expr::ObjCEncodeExprClass: 2034 return true; 2035 case Expr::ObjCBoxedExprClass: 2036 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2037 case Expr::CallExprClass: 2038 return IsNoOpCall(cast<CallExpr>(E)); 2039 // For GCC compatibility, &&label has static storage duration. 2040 case Expr::AddrLabelExprClass: 2041 return true; 2042 // A Block literal expression may be used as the initialization value for 2043 // Block variables at global or local static scope. 2044 case Expr::BlockExprClass: 2045 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2046 // The APValue generated from a __builtin_source_location will be emitted as a 2047 // literal. 2048 case Expr::SourceLocExprClass: 2049 return true; 2050 case Expr::ImplicitValueInitExprClass: 2051 // FIXME: 2052 // We can never form an lvalue with an implicit value initialization as its 2053 // base through expression evaluation, so these only appear in one case: the 2054 // implicit variable declaration we invent when checking whether a constexpr 2055 // constructor can produce a constant expression. We must assume that such 2056 // an expression might be a global lvalue. 2057 return true; 2058 } 2059 } 2060 2061 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2062 return LVal.Base.dyn_cast<const ValueDecl*>(); 2063 } 2064 2065 static bool IsLiteralLValue(const LValue &Value) { 2066 if (Value.getLValueCallIndex()) 2067 return false; 2068 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2069 return E && !isa<MaterializeTemporaryExpr>(E); 2070 } 2071 2072 static bool IsWeakLValue(const LValue &Value) { 2073 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2074 return Decl && Decl->isWeak(); 2075 } 2076 2077 static bool isZeroSized(const LValue &Value) { 2078 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2079 if (Decl && isa<VarDecl>(Decl)) { 2080 QualType Ty = Decl->getType(); 2081 if (Ty->isArrayType()) 2082 return Ty->isIncompleteType() || 2083 Decl->getASTContext().getTypeSize(Ty) == 0; 2084 } 2085 return false; 2086 } 2087 2088 static bool HasSameBase(const LValue &A, const LValue &B) { 2089 if (!A.getLValueBase()) 2090 return !B.getLValueBase(); 2091 if (!B.getLValueBase()) 2092 return false; 2093 2094 if (A.getLValueBase().getOpaqueValue() != 2095 B.getLValueBase().getOpaqueValue()) 2096 return false; 2097 2098 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2099 A.getLValueVersion() == B.getLValueVersion(); 2100 } 2101 2102 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2103 assert(Base && "no location for a null lvalue"); 2104 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2105 2106 // For a parameter, find the corresponding call stack frame (if it still 2107 // exists), and point at the parameter of the function definition we actually 2108 // invoked. 2109 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2110 unsigned Idx = PVD->getFunctionScopeIndex(); 2111 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2112 if (F->Arguments.CallIndex == Base.getCallIndex() && 2113 F->Arguments.Version == Base.getVersion() && F->Callee && 2114 Idx < F->Callee->getNumParams()) { 2115 VD = F->Callee->getParamDecl(Idx); 2116 break; 2117 } 2118 } 2119 } 2120 2121 if (VD) 2122 Info.Note(VD->getLocation(), diag::note_declared_at); 2123 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2124 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2125 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2126 // FIXME: Produce a note for dangling pointers too. 2127 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA)) 2128 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2129 diag::note_constexpr_dynamic_alloc_here); 2130 } 2131 2132 // We have no information to show for a typeid(T) object. 2133 } 2134 2135 enum class CheckEvaluationResultKind { 2136 ConstantExpression, 2137 FullyInitialized, 2138 }; 2139 2140 /// Materialized temporaries that we've already checked to determine if they're 2141 /// initializsed by a constant expression. 2142 using CheckedTemporaries = 2143 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2144 2145 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2146 EvalInfo &Info, SourceLocation DiagLoc, 2147 QualType Type, const APValue &Value, 2148 ConstantExprKind Kind, 2149 const FieldDecl *SubobjectDecl, 2150 CheckedTemporaries &CheckedTemps); 2151 2152 /// Check that this reference or pointer core constant expression is a valid 2153 /// value for an address or reference constant expression. Return true if we 2154 /// can fold this expression, whether or not it's a constant expression. 2155 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2156 QualType Type, const LValue &LVal, 2157 ConstantExprKind Kind, 2158 CheckedTemporaries &CheckedTemps) { 2159 bool IsReferenceType = Type->isReferenceType(); 2160 2161 APValue::LValueBase Base = LVal.getLValueBase(); 2162 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2163 2164 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2165 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2166 2167 // Additional restrictions apply in a template argument. We only enforce the 2168 // C++20 restrictions here; additional syntactic and semantic restrictions 2169 // are applied elsewhere. 2170 if (isTemplateArgument(Kind)) { 2171 int InvalidBaseKind = -1; 2172 StringRef Ident; 2173 if (Base.is<TypeInfoLValue>()) 2174 InvalidBaseKind = 0; 2175 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2176 InvalidBaseKind = 1; 2177 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2178 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2179 InvalidBaseKind = 2; 2180 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2181 InvalidBaseKind = 3; 2182 Ident = PE->getIdentKindName(); 2183 } 2184 2185 if (InvalidBaseKind != -1) { 2186 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2187 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2188 << Ident; 2189 return false; 2190 } 2191 } 2192 2193 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD); 2194 FD && FD->isImmediateFunction()) { 2195 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2196 << !Type->isAnyPointerType(); 2197 Info.Note(FD->getLocation(), diag::note_declared_at); 2198 return false; 2199 } 2200 2201 // Check that the object is a global. Note that the fake 'this' object we 2202 // manufacture when checking potential constant expressions is conservatively 2203 // assumed to be global here. 2204 if (!IsGlobalLValue(Base)) { 2205 if (Info.getLangOpts().CPlusPlus11) { 2206 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2207 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD 2208 << BaseVD; 2209 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD); 2210 if (VarD && VarD->isConstexpr()) { 2211 // Non-static local constexpr variables have unintuitive semantics: 2212 // constexpr int a = 1; 2213 // constexpr const int *p = &a; 2214 // ... is invalid because the address of 'a' is not constant. Suggest 2215 // adding a 'static' in this case. 2216 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2217 << VarD 2218 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2219 } else { 2220 NoteLValueLocation(Info, Base); 2221 } 2222 } else { 2223 Info.FFDiag(Loc); 2224 } 2225 // Don't allow references to temporaries to escape. 2226 return false; 2227 } 2228 assert((Info.checkingPotentialConstantExpression() || 2229 LVal.getLValueCallIndex() == 0) && 2230 "have call index for global lvalue"); 2231 2232 if (Base.is<DynamicAllocLValue>()) { 2233 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2234 << IsReferenceType << !Designator.Entries.empty(); 2235 NoteLValueLocation(Info, Base); 2236 return false; 2237 } 2238 2239 if (BaseVD) { 2240 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2241 // Check if this is a thread-local variable. 2242 if (Var->getTLSKind()) 2243 // FIXME: Diagnostic! 2244 return false; 2245 2246 // A dllimport variable never acts like a constant, unless we're 2247 // evaluating a value for use only in name mangling. 2248 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2249 // FIXME: Diagnostic! 2250 return false; 2251 2252 // In CUDA/HIP device compilation, only device side variables have 2253 // constant addresses. 2254 if (Info.getCtx().getLangOpts().CUDA && 2255 Info.getCtx().getLangOpts().CUDAIsDevice && 2256 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { 2257 if ((!Var->hasAttr<CUDADeviceAttr>() && 2258 !Var->hasAttr<CUDAConstantAttr>() && 2259 !Var->getType()->isCUDADeviceBuiltinSurfaceType() && 2260 !Var->getType()->isCUDADeviceBuiltinTextureType()) || 2261 Var->hasAttr<HIPManagedAttr>()) 2262 return false; 2263 } 2264 } 2265 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2266 // __declspec(dllimport) must be handled very carefully: 2267 // We must never initialize an expression with the thunk in C++. 2268 // Doing otherwise would allow the same id-expression to yield 2269 // different addresses for the same function in different translation 2270 // units. However, this means that we must dynamically initialize the 2271 // expression with the contents of the import address table at runtime. 2272 // 2273 // The C language has no notion of ODR; furthermore, it has no notion of 2274 // dynamic initialization. This means that we are permitted to 2275 // perform initialization with the address of the thunk. 2276 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2277 FD->hasAttr<DLLImportAttr>()) 2278 // FIXME: Diagnostic! 2279 return false; 2280 } 2281 } else if (const auto *MTE = 2282 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2283 if (CheckedTemps.insert(MTE).second) { 2284 QualType TempType = getType(Base); 2285 if (TempType.isDestructedType()) { 2286 Info.FFDiag(MTE->getExprLoc(), 2287 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2288 << TempType; 2289 return false; 2290 } 2291 2292 APValue *V = MTE->getOrCreateValue(false); 2293 assert(V && "evasluation result refers to uninitialised temporary"); 2294 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2295 Info, MTE->getExprLoc(), TempType, *V, Kind, 2296 /*SubobjectDecl=*/nullptr, CheckedTemps)) 2297 return false; 2298 } 2299 } 2300 2301 // Allow address constant expressions to be past-the-end pointers. This is 2302 // an extension: the standard requires them to point to an object. 2303 if (!IsReferenceType) 2304 return true; 2305 2306 // A reference constant expression must refer to an object. 2307 if (!Base) { 2308 // FIXME: diagnostic 2309 Info.CCEDiag(Loc); 2310 return true; 2311 } 2312 2313 // Does this refer one past the end of some object? 2314 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2315 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2316 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2317 NoteLValueLocation(Info, Base); 2318 } 2319 2320 return true; 2321 } 2322 2323 /// Member pointers are constant expressions unless they point to a 2324 /// non-virtual dllimport member function. 2325 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2326 SourceLocation Loc, 2327 QualType Type, 2328 const APValue &Value, 2329 ConstantExprKind Kind) { 2330 const ValueDecl *Member = Value.getMemberPointerDecl(); 2331 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2332 if (!FD) 2333 return true; 2334 if (FD->isImmediateFunction()) { 2335 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2336 Info.Note(FD->getLocation(), diag::note_declared_at); 2337 return false; 2338 } 2339 return isForManglingOnly(Kind) || FD->isVirtual() || 2340 !FD->hasAttr<DLLImportAttr>(); 2341 } 2342 2343 /// Check that this core constant expression is of literal type, and if not, 2344 /// produce an appropriate diagnostic. 2345 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2346 const LValue *This = nullptr) { 2347 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2348 return true; 2349 2350 // C++1y: A constant initializer for an object o [...] may also invoke 2351 // constexpr constructors for o and its subobjects even if those objects 2352 // are of non-literal class types. 2353 // 2354 // C++11 missed this detail for aggregates, so classes like this: 2355 // struct foo_t { union { int i; volatile int j; } u; }; 2356 // are not (obviously) initializable like so: 2357 // __attribute__((__require_constant_initialization__)) 2358 // static const foo_t x = {{0}}; 2359 // because "i" is a subobject with non-literal initialization (due to the 2360 // volatile member of the union). See: 2361 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2362 // Therefore, we use the C++1y behavior. 2363 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2364 return true; 2365 2366 // Prvalue constant expressions must be of literal types. 2367 if (Info.getLangOpts().CPlusPlus11) 2368 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2369 << E->getType(); 2370 else 2371 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2372 return false; 2373 } 2374 2375 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2376 EvalInfo &Info, SourceLocation DiagLoc, 2377 QualType Type, const APValue &Value, 2378 ConstantExprKind Kind, 2379 const FieldDecl *SubobjectDecl, 2380 CheckedTemporaries &CheckedTemps) { 2381 if (!Value.hasValue()) { 2382 assert(SubobjectDecl && "SubobjectDecl shall be non-null"); 2383 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl; 2384 Info.Note(SubobjectDecl->getLocation(), 2385 diag::note_constexpr_subobject_declared_here); 2386 return false; 2387 } 2388 2389 // We allow _Atomic(T) to be initialized from anything that T can be 2390 // initialized from. 2391 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2392 Type = AT->getValueType(); 2393 2394 // Core issue 1454: For a literal constant expression of array or class type, 2395 // each subobject of its value shall have been initialized by a constant 2396 // expression. 2397 if (Value.isArray()) { 2398 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2399 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2400 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2401 Value.getArrayInitializedElt(I), Kind, 2402 SubobjectDecl, CheckedTemps)) 2403 return false; 2404 } 2405 if (!Value.hasArrayFiller()) 2406 return true; 2407 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2408 Value.getArrayFiller(), Kind, SubobjectDecl, 2409 CheckedTemps); 2410 } 2411 if (Value.isUnion() && Value.getUnionField()) { 2412 return CheckEvaluationResult( 2413 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2414 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps); 2415 } 2416 if (Value.isStruct()) { 2417 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2418 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2419 unsigned BaseIndex = 0; 2420 for (const CXXBaseSpecifier &BS : CD->bases()) { 2421 const APValue &BaseValue = Value.getStructBase(BaseIndex); 2422 if (!BaseValue.hasValue()) { 2423 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc(); 2424 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base) 2425 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc()); 2426 return false; 2427 } 2428 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue, 2429 Kind, /*SubobjectDecl=*/nullptr, 2430 CheckedTemps)) 2431 return false; 2432 ++BaseIndex; 2433 } 2434 } 2435 for (const auto *I : RD->fields()) { 2436 if (I->isUnnamedBitfield()) 2437 continue; 2438 2439 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2440 Value.getStructField(I->getFieldIndex()), Kind, 2441 I, CheckedTemps)) 2442 return false; 2443 } 2444 } 2445 2446 if (Value.isLValue() && 2447 CERK == CheckEvaluationResultKind::ConstantExpression) { 2448 LValue LVal; 2449 LVal.setFrom(Info.Ctx, Value); 2450 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2451 CheckedTemps); 2452 } 2453 2454 if (Value.isMemberPointer() && 2455 CERK == CheckEvaluationResultKind::ConstantExpression) 2456 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2457 2458 // Everything else is fine. 2459 return true; 2460 } 2461 2462 /// Check that this core constant expression value is a valid value for a 2463 /// constant expression. If not, report an appropriate diagnostic. Does not 2464 /// check that the expression is of literal type. 2465 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2466 QualType Type, const APValue &Value, 2467 ConstantExprKind Kind) { 2468 // Nothing to check for a constant expression of type 'cv void'. 2469 if (Type->isVoidType()) 2470 return true; 2471 2472 CheckedTemporaries CheckedTemps; 2473 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2474 Info, DiagLoc, Type, Value, Kind, 2475 /*SubobjectDecl=*/nullptr, CheckedTemps); 2476 } 2477 2478 /// Check that this evaluated value is fully-initialized and can be loaded by 2479 /// an lvalue-to-rvalue conversion. 2480 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2481 QualType Type, const APValue &Value) { 2482 CheckedTemporaries CheckedTemps; 2483 return CheckEvaluationResult( 2484 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2485 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps); 2486 } 2487 2488 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2489 /// "the allocated storage is deallocated within the evaluation". 2490 static bool CheckMemoryLeaks(EvalInfo &Info) { 2491 if (!Info.HeapAllocs.empty()) { 2492 // We can still fold to a constant despite a compile-time memory leak, 2493 // so long as the heap allocation isn't referenced in the result (we check 2494 // that in CheckConstantExpression). 2495 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2496 diag::note_constexpr_memory_leak) 2497 << unsigned(Info.HeapAllocs.size() - 1); 2498 } 2499 return true; 2500 } 2501 2502 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2503 // A null base expression indicates a null pointer. These are always 2504 // evaluatable, and they are false unless the offset is zero. 2505 if (!Value.getLValueBase()) { 2506 // TODO: Should a non-null pointer with an offset of zero evaluate to true? 2507 Result = !Value.getLValueOffset().isZero(); 2508 return true; 2509 } 2510 2511 // We have a non-null base. These are generally known to be true, but if it's 2512 // a weak declaration it can be null at runtime. 2513 Result = true; 2514 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2515 return !Decl || !Decl->isWeak(); 2516 } 2517 2518 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2519 // TODO: This function should produce notes if it fails. 2520 switch (Val.getKind()) { 2521 case APValue::None: 2522 case APValue::Indeterminate: 2523 return false; 2524 case APValue::Int: 2525 Result = Val.getInt().getBoolValue(); 2526 return true; 2527 case APValue::FixedPoint: 2528 Result = Val.getFixedPoint().getBoolValue(); 2529 return true; 2530 case APValue::Float: 2531 Result = !Val.getFloat().isZero(); 2532 return true; 2533 case APValue::ComplexInt: 2534 Result = Val.getComplexIntReal().getBoolValue() || 2535 Val.getComplexIntImag().getBoolValue(); 2536 return true; 2537 case APValue::ComplexFloat: 2538 Result = !Val.getComplexFloatReal().isZero() || 2539 !Val.getComplexFloatImag().isZero(); 2540 return true; 2541 case APValue::LValue: 2542 return EvalPointerValueAsBool(Val, Result); 2543 case APValue::MemberPointer: 2544 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) { 2545 return false; 2546 } 2547 Result = Val.getMemberPointerDecl(); 2548 return true; 2549 case APValue::Vector: 2550 case APValue::Array: 2551 case APValue::Struct: 2552 case APValue::Union: 2553 case APValue::AddrLabelDiff: 2554 return false; 2555 } 2556 2557 llvm_unreachable("unknown APValue kind"); 2558 } 2559 2560 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2561 EvalInfo &Info) { 2562 assert(!E->isValueDependent()); 2563 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2564 APValue Val; 2565 if (!Evaluate(Val, Info, E)) 2566 return false; 2567 return HandleConversionToBool(Val, Result); 2568 } 2569 2570 template<typename T> 2571 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2572 const T &SrcValue, QualType DestType) { 2573 Info.CCEDiag(E, diag::note_constexpr_overflow) 2574 << SrcValue << DestType; 2575 return Info.noteUndefinedBehavior(); 2576 } 2577 2578 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2579 QualType SrcType, const APFloat &Value, 2580 QualType DestType, APSInt &Result) { 2581 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2582 // Determine whether we are converting to unsigned or signed. 2583 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2584 2585 Result = APSInt(DestWidth, !DestSigned); 2586 bool ignored; 2587 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2588 & APFloat::opInvalidOp) 2589 return HandleOverflow(Info, E, Value, DestType); 2590 return true; 2591 } 2592 2593 /// Get rounding mode to use in evaluation of the specified expression. 2594 /// 2595 /// If rounding mode is unknown at compile time, still try to evaluate the 2596 /// expression. If the result is exact, it does not depend on rounding mode. 2597 /// So return "tonearest" mode instead of "dynamic". 2598 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) { 2599 llvm::RoundingMode RM = 2600 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2601 if (RM == llvm::RoundingMode::Dynamic) 2602 RM = llvm::RoundingMode::NearestTiesToEven; 2603 return RM; 2604 } 2605 2606 /// Check if the given evaluation result is allowed for constant evaluation. 2607 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2608 APFloat::opStatus St) { 2609 // In a constant context, assume that any dynamic rounding mode or FP 2610 // exception state matches the default floating-point environment. 2611 if (Info.InConstantContext) 2612 return true; 2613 2614 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2615 if ((St & APFloat::opInexact) && 2616 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2617 // Inexact result means that it depends on rounding mode. If the requested 2618 // mode is dynamic, the evaluation cannot be made in compile time. 2619 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2620 return false; 2621 } 2622 2623 if ((St != APFloat::opOK) && 2624 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2625 FPO.getExceptionMode() != LangOptions::FPE_Ignore || 2626 FPO.getAllowFEnvAccess())) { 2627 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2628 return false; 2629 } 2630 2631 if ((St & APFloat::opStatus::opInvalidOp) && 2632 FPO.getExceptionMode() != LangOptions::FPE_Ignore) { 2633 // There is no usefully definable result. 2634 Info.FFDiag(E); 2635 return false; 2636 } 2637 2638 // FIXME: if: 2639 // - evaluation triggered other FP exception, and 2640 // - exception mode is not "ignore", and 2641 // - the expression being evaluated is not a part of global variable 2642 // initializer, 2643 // the evaluation probably need to be rejected. 2644 return true; 2645 } 2646 2647 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2648 QualType SrcType, QualType DestType, 2649 APFloat &Result) { 2650 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2651 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2652 APFloat::opStatus St; 2653 APFloat Value = Result; 2654 bool ignored; 2655 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2656 return checkFloatingPointResult(Info, E, St); 2657 } 2658 2659 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2660 QualType DestType, QualType SrcType, 2661 const APSInt &Value) { 2662 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2663 // Figure out if this is a truncate, extend or noop cast. 2664 // If the input is signed, do a sign extend, noop, or truncate. 2665 APSInt Result = Value.extOrTrunc(DestWidth); 2666 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2667 if (DestType->isBooleanType()) 2668 Result = Value.getBoolValue(); 2669 return Result; 2670 } 2671 2672 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2673 const FPOptions FPO, 2674 QualType SrcType, const APSInt &Value, 2675 QualType DestType, APFloat &Result) { 2676 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2677 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2678 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM); 2679 return checkFloatingPointResult(Info, E, St); 2680 } 2681 2682 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2683 APValue &Value, const FieldDecl *FD) { 2684 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2685 2686 if (!Value.isInt()) { 2687 // Trying to store a pointer-cast-to-integer into a bitfield. 2688 // FIXME: In this case, we should provide the diagnostic for casting 2689 // a pointer to an integer. 2690 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2691 Info.FFDiag(E); 2692 return false; 2693 } 2694 2695 APSInt &Int = Value.getInt(); 2696 unsigned OldBitWidth = Int.getBitWidth(); 2697 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2698 if (NewBitWidth < OldBitWidth) 2699 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2700 return true; 2701 } 2702 2703 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2704 llvm::APInt &Res) { 2705 APValue SVal; 2706 if (!Evaluate(SVal, Info, E)) 2707 return false; 2708 if (SVal.isInt()) { 2709 Res = SVal.getInt(); 2710 return true; 2711 } 2712 if (SVal.isFloat()) { 2713 Res = SVal.getFloat().bitcastToAPInt(); 2714 return true; 2715 } 2716 if (SVal.isVector()) { 2717 QualType VecTy = E->getType(); 2718 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2719 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2720 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2721 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2722 Res = llvm::APInt::getZero(VecSize); 2723 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2724 APValue &Elt = SVal.getVectorElt(i); 2725 llvm::APInt EltAsInt; 2726 if (Elt.isInt()) { 2727 EltAsInt = Elt.getInt(); 2728 } else if (Elt.isFloat()) { 2729 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2730 } else { 2731 // Don't try to handle vectors of anything other than int or float 2732 // (not sure if it's possible to hit this case). 2733 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2734 return false; 2735 } 2736 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2737 if (BigEndian) 2738 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2739 else 2740 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2741 } 2742 return true; 2743 } 2744 // Give up if the input isn't an int, float, or vector. For example, we 2745 // reject "(v4i16)(intptr_t)&a". 2746 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2747 return false; 2748 } 2749 2750 /// Perform the given integer operation, which is known to need at most BitWidth 2751 /// bits, and check for overflow in the original type (if that type was not an 2752 /// unsigned type). 2753 template<typename Operation> 2754 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2755 const APSInt &LHS, const APSInt &RHS, 2756 unsigned BitWidth, Operation Op, 2757 APSInt &Result) { 2758 if (LHS.isUnsigned()) { 2759 Result = Op(LHS, RHS); 2760 return true; 2761 } 2762 2763 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2764 Result = Value.trunc(LHS.getBitWidth()); 2765 if (Result.extend(BitWidth) != Value) { 2766 if (Info.checkingForUndefinedBehavior()) 2767 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2768 diag::warn_integer_constant_overflow) 2769 << toString(Result, 10) << E->getType(); 2770 return HandleOverflow(Info, E, Value, E->getType()); 2771 } 2772 return true; 2773 } 2774 2775 /// Perform the given binary integer operation. 2776 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2777 BinaryOperatorKind Opcode, APSInt RHS, 2778 APSInt &Result) { 2779 bool HandleOverflowResult = true; 2780 switch (Opcode) { 2781 default: 2782 Info.FFDiag(E); 2783 return false; 2784 case BO_Mul: 2785 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2786 std::multiplies<APSInt>(), Result); 2787 case BO_Add: 2788 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2789 std::plus<APSInt>(), Result); 2790 case BO_Sub: 2791 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2792 std::minus<APSInt>(), Result); 2793 case BO_And: Result = LHS & RHS; return true; 2794 case BO_Xor: Result = LHS ^ RHS; return true; 2795 case BO_Or: Result = LHS | RHS; return true; 2796 case BO_Div: 2797 case BO_Rem: 2798 if (RHS == 0) { 2799 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2800 return false; 2801 } 2802 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2803 // this operation and gives the two's complement result. 2804 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2805 LHS.isMinSignedValue()) 2806 HandleOverflowResult = HandleOverflow( 2807 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType()); 2808 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2809 return HandleOverflowResult; 2810 case BO_Shl: { 2811 if (Info.getLangOpts().OpenCL) 2812 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2813 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2814 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2815 RHS.isUnsigned()); 2816 else if (RHS.isSigned() && RHS.isNegative()) { 2817 // During constant-folding, a negative shift is an opposite shift. Such 2818 // a shift is not a constant expression. 2819 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2820 RHS = -RHS; 2821 goto shift_right; 2822 } 2823 shift_left: 2824 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2825 // the shifted type. 2826 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2827 if (SA != RHS) { 2828 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2829 << RHS << E->getType() << LHS.getBitWidth(); 2830 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2831 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2832 // operand, and must not overflow the corresponding unsigned type. 2833 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2834 // E1 x 2^E2 module 2^N. 2835 if (LHS.isNegative()) 2836 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2837 else if (LHS.countl_zero() < SA) 2838 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2839 } 2840 Result = LHS << SA; 2841 return true; 2842 } 2843 case BO_Shr: { 2844 if (Info.getLangOpts().OpenCL) 2845 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2846 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2847 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2848 RHS.isUnsigned()); 2849 else if (RHS.isSigned() && RHS.isNegative()) { 2850 // During constant-folding, a negative shift is an opposite shift. Such a 2851 // shift is not a constant expression. 2852 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2853 RHS = -RHS; 2854 goto shift_left; 2855 } 2856 shift_right: 2857 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2858 // shifted type. 2859 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2860 if (SA != RHS) 2861 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2862 << RHS << E->getType() << LHS.getBitWidth(); 2863 Result = LHS >> SA; 2864 return true; 2865 } 2866 2867 case BO_LT: Result = LHS < RHS; return true; 2868 case BO_GT: Result = LHS > RHS; return true; 2869 case BO_LE: Result = LHS <= RHS; return true; 2870 case BO_GE: Result = LHS >= RHS; return true; 2871 case BO_EQ: Result = LHS == RHS; return true; 2872 case BO_NE: Result = LHS != RHS; return true; 2873 case BO_Cmp: 2874 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2875 } 2876 } 2877 2878 /// Perform the given binary floating-point operation, in-place, on LHS. 2879 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2880 APFloat &LHS, BinaryOperatorKind Opcode, 2881 const APFloat &RHS) { 2882 llvm::RoundingMode RM = getActiveRoundingMode(Info, E); 2883 APFloat::opStatus St; 2884 switch (Opcode) { 2885 default: 2886 Info.FFDiag(E); 2887 return false; 2888 case BO_Mul: 2889 St = LHS.multiply(RHS, RM); 2890 break; 2891 case BO_Add: 2892 St = LHS.add(RHS, RM); 2893 break; 2894 case BO_Sub: 2895 St = LHS.subtract(RHS, RM); 2896 break; 2897 case BO_Div: 2898 // [expr.mul]p4: 2899 // If the second operand of / or % is zero the behavior is undefined. 2900 if (RHS.isZero()) 2901 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2902 St = LHS.divide(RHS, RM); 2903 break; 2904 } 2905 2906 // [expr.pre]p4: 2907 // If during the evaluation of an expression, the result is not 2908 // mathematically defined [...], the behavior is undefined. 2909 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2910 if (LHS.isNaN()) { 2911 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2912 return Info.noteUndefinedBehavior(); 2913 } 2914 2915 return checkFloatingPointResult(Info, E, St); 2916 } 2917 2918 static bool handleLogicalOpForVector(const APInt &LHSValue, 2919 BinaryOperatorKind Opcode, 2920 const APInt &RHSValue, APInt &Result) { 2921 bool LHS = (LHSValue != 0); 2922 bool RHS = (RHSValue != 0); 2923 2924 if (Opcode == BO_LAnd) 2925 Result = LHS && RHS; 2926 else 2927 Result = LHS || RHS; 2928 return true; 2929 } 2930 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2931 BinaryOperatorKind Opcode, 2932 const APFloat &RHSValue, APInt &Result) { 2933 bool LHS = !LHSValue.isZero(); 2934 bool RHS = !RHSValue.isZero(); 2935 2936 if (Opcode == BO_LAnd) 2937 Result = LHS && RHS; 2938 else 2939 Result = LHS || RHS; 2940 return true; 2941 } 2942 2943 static bool handleLogicalOpForVector(const APValue &LHSValue, 2944 BinaryOperatorKind Opcode, 2945 const APValue &RHSValue, APInt &Result) { 2946 // The result is always an int type, however operands match the first. 2947 if (LHSValue.getKind() == APValue::Int) 2948 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2949 RHSValue.getInt(), Result); 2950 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2951 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2952 RHSValue.getFloat(), Result); 2953 } 2954 2955 template <typename APTy> 2956 static bool 2957 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2958 const APTy &RHSValue, APInt &Result) { 2959 switch (Opcode) { 2960 default: 2961 llvm_unreachable("unsupported binary operator"); 2962 case BO_EQ: 2963 Result = (LHSValue == RHSValue); 2964 break; 2965 case BO_NE: 2966 Result = (LHSValue != RHSValue); 2967 break; 2968 case BO_LT: 2969 Result = (LHSValue < RHSValue); 2970 break; 2971 case BO_GT: 2972 Result = (LHSValue > RHSValue); 2973 break; 2974 case BO_LE: 2975 Result = (LHSValue <= RHSValue); 2976 break; 2977 case BO_GE: 2978 Result = (LHSValue >= RHSValue); 2979 break; 2980 } 2981 2982 // The boolean operations on these vector types use an instruction that 2983 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2984 // to -1 to make sure that we produce the correct value. 2985 Result.negate(); 2986 2987 return true; 2988 } 2989 2990 static bool handleCompareOpForVector(const APValue &LHSValue, 2991 BinaryOperatorKind Opcode, 2992 const APValue &RHSValue, APInt &Result) { 2993 // The result is always an int type, however operands match the first. 2994 if (LHSValue.getKind() == APValue::Int) 2995 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2996 RHSValue.getInt(), Result); 2997 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2998 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2999 RHSValue.getFloat(), Result); 3000 } 3001 3002 // Perform binary operations for vector types, in place on the LHS. 3003 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 3004 BinaryOperatorKind Opcode, 3005 APValue &LHSValue, 3006 const APValue &RHSValue) { 3007 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 3008 "Operation not supported on vector types"); 3009 3010 const auto *VT = E->getType()->castAs<VectorType>(); 3011 unsigned NumElements = VT->getNumElements(); 3012 QualType EltTy = VT->getElementType(); 3013 3014 // In the cases (typically C as I've observed) where we aren't evaluating 3015 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 3016 // just give up. 3017 if (!LHSValue.isVector()) { 3018 assert(LHSValue.isLValue() && 3019 "A vector result that isn't a vector OR uncalculated LValue"); 3020 Info.FFDiag(E); 3021 return false; 3022 } 3023 3024 assert(LHSValue.getVectorLength() == NumElements && 3025 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 3026 3027 SmallVector<APValue, 4> ResultElements; 3028 3029 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 3030 APValue LHSElt = LHSValue.getVectorElt(EltNum); 3031 APValue RHSElt = RHSValue.getVectorElt(EltNum); 3032 3033 if (EltTy->isIntegerType()) { 3034 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 3035 EltTy->isUnsignedIntegerType()}; 3036 bool Success = true; 3037 3038 if (BinaryOperator::isLogicalOp(Opcode)) 3039 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3040 else if (BinaryOperator::isComparisonOp(Opcode)) 3041 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3042 else 3043 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3044 RHSElt.getInt(), EltResult); 3045 3046 if (!Success) { 3047 Info.FFDiag(E); 3048 return false; 3049 } 3050 ResultElements.emplace_back(EltResult); 3051 3052 } else if (EltTy->isFloatingType()) { 3053 assert(LHSElt.getKind() == APValue::Float && 3054 RHSElt.getKind() == APValue::Float && 3055 "Mismatched LHS/RHS/Result Type"); 3056 APFloat LHSFloat = LHSElt.getFloat(); 3057 3058 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3059 RHSElt.getFloat())) { 3060 Info.FFDiag(E); 3061 return false; 3062 } 3063 3064 ResultElements.emplace_back(LHSFloat); 3065 } 3066 } 3067 3068 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3069 return true; 3070 } 3071 3072 /// Cast an lvalue referring to a base subobject to a derived class, by 3073 /// truncating the lvalue's path to the given length. 3074 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3075 const RecordDecl *TruncatedType, 3076 unsigned TruncatedElements) { 3077 SubobjectDesignator &D = Result.Designator; 3078 3079 // Check we actually point to a derived class object. 3080 if (TruncatedElements == D.Entries.size()) 3081 return true; 3082 assert(TruncatedElements >= D.MostDerivedPathLength && 3083 "not casting to a derived class"); 3084 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3085 return false; 3086 3087 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3088 const RecordDecl *RD = TruncatedType; 3089 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3090 if (RD->isInvalidDecl()) return false; 3091 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3092 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3093 if (isVirtualBaseClass(D.Entries[I])) 3094 Result.Offset -= Layout.getVBaseClassOffset(Base); 3095 else 3096 Result.Offset -= Layout.getBaseClassOffset(Base); 3097 RD = Base; 3098 } 3099 D.Entries.resize(TruncatedElements); 3100 return true; 3101 } 3102 3103 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3104 const CXXRecordDecl *Derived, 3105 const CXXRecordDecl *Base, 3106 const ASTRecordLayout *RL = nullptr) { 3107 if (!RL) { 3108 if (Derived->isInvalidDecl()) return false; 3109 RL = &Info.Ctx.getASTRecordLayout(Derived); 3110 } 3111 3112 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3113 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3114 return true; 3115 } 3116 3117 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3118 const CXXRecordDecl *DerivedDecl, 3119 const CXXBaseSpecifier *Base) { 3120 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3121 3122 if (!Base->isVirtual()) 3123 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3124 3125 SubobjectDesignator &D = Obj.Designator; 3126 if (D.Invalid) 3127 return false; 3128 3129 // Extract most-derived object and corresponding type. 3130 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3131 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3132 return false; 3133 3134 // Find the virtual base class. 3135 if (DerivedDecl->isInvalidDecl()) return false; 3136 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3137 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3138 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3139 return true; 3140 } 3141 3142 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3143 QualType Type, LValue &Result) { 3144 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3145 PathE = E->path_end(); 3146 PathI != PathE; ++PathI) { 3147 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3148 *PathI)) 3149 return false; 3150 Type = (*PathI)->getType(); 3151 } 3152 return true; 3153 } 3154 3155 /// Cast an lvalue referring to a derived class to a known base subobject. 3156 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3157 const CXXRecordDecl *DerivedRD, 3158 const CXXRecordDecl *BaseRD) { 3159 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3160 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3161 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3162 llvm_unreachable("Class must be derived from the passed in base class!"); 3163 3164 for (CXXBasePathElement &Elem : Paths.front()) 3165 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3166 return false; 3167 return true; 3168 } 3169 3170 /// Update LVal to refer to the given field, which must be a member of the type 3171 /// currently described by LVal. 3172 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3173 const FieldDecl *FD, 3174 const ASTRecordLayout *RL = nullptr) { 3175 if (!RL) { 3176 if (FD->getParent()->isInvalidDecl()) return false; 3177 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3178 } 3179 3180 unsigned I = FD->getFieldIndex(); 3181 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3182 LVal.addDecl(Info, E, FD); 3183 return true; 3184 } 3185 3186 /// Update LVal to refer to the given indirect field. 3187 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3188 LValue &LVal, 3189 const IndirectFieldDecl *IFD) { 3190 for (const auto *C : IFD->chain()) 3191 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3192 return false; 3193 return true; 3194 } 3195 3196 /// Get the size of the given type in char units. 3197 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3198 QualType Type, CharUnits &Size) { 3199 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3200 // extension. 3201 if (Type->isVoidType() || Type->isFunctionType()) { 3202 Size = CharUnits::One(); 3203 return true; 3204 } 3205 3206 if (Type->isDependentType()) { 3207 Info.FFDiag(Loc); 3208 return false; 3209 } 3210 3211 if (!Type->isConstantSizeType()) { 3212 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3213 // FIXME: Better diagnostic. 3214 Info.FFDiag(Loc); 3215 return false; 3216 } 3217 3218 Size = Info.Ctx.getTypeSizeInChars(Type); 3219 return true; 3220 } 3221 3222 /// Update a pointer value to model pointer arithmetic. 3223 /// \param Info - Information about the ongoing evaluation. 3224 /// \param E - The expression being evaluated, for diagnostic purposes. 3225 /// \param LVal - The pointer value to be updated. 3226 /// \param EltTy - The pointee type represented by LVal. 3227 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3228 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3229 LValue &LVal, QualType EltTy, 3230 APSInt Adjustment) { 3231 CharUnits SizeOfPointee; 3232 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3233 return false; 3234 3235 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3236 return true; 3237 } 3238 3239 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3240 LValue &LVal, QualType EltTy, 3241 int64_t Adjustment) { 3242 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3243 APSInt::get(Adjustment)); 3244 } 3245 3246 /// Update an lvalue to refer to a component of a complex number. 3247 /// \param Info - Information about the ongoing evaluation. 3248 /// \param LVal - The lvalue to be updated. 3249 /// \param EltTy - The complex number's component type. 3250 /// \param Imag - False for the real component, true for the imaginary. 3251 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3252 LValue &LVal, QualType EltTy, 3253 bool Imag) { 3254 if (Imag) { 3255 CharUnits SizeOfComponent; 3256 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3257 return false; 3258 LVal.Offset += SizeOfComponent; 3259 } 3260 LVal.addComplex(Info, E, EltTy, Imag); 3261 return true; 3262 } 3263 3264 /// Try to evaluate the initializer for a variable declaration. 3265 /// 3266 /// \param Info Information about the ongoing evaluation. 3267 /// \param E An expression to be used when printing diagnostics. 3268 /// \param VD The variable whose initializer should be obtained. 3269 /// \param Version The version of the variable within the frame. 3270 /// \param Frame The frame in which the variable was created. Must be null 3271 /// if this variable is not local to the evaluation. 3272 /// \param Result Filled in with a pointer to the value of the variable. 3273 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3274 const VarDecl *VD, CallStackFrame *Frame, 3275 unsigned Version, APValue *&Result) { 3276 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3277 3278 // If this is a local variable, dig out its value. 3279 if (Frame) { 3280 Result = Frame->getTemporary(VD, Version); 3281 if (Result) 3282 return true; 3283 3284 if (!isa<ParmVarDecl>(VD)) { 3285 // Assume variables referenced within a lambda's call operator that were 3286 // not declared within the call operator are captures and during checking 3287 // of a potential constant expression, assume they are unknown constant 3288 // expressions. 3289 assert(isLambdaCallOperator(Frame->Callee) && 3290 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3291 "missing value for local variable"); 3292 if (Info.checkingPotentialConstantExpression()) 3293 return false; 3294 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3295 // still reachable at all? 3296 Info.FFDiag(E->getBeginLoc(), 3297 diag::note_unimplemented_constexpr_lambda_feature_ast) 3298 << "captures not currently allowed"; 3299 return false; 3300 } 3301 } 3302 3303 // If we're currently evaluating the initializer of this declaration, use that 3304 // in-flight value. 3305 if (Info.EvaluatingDecl == Base) { 3306 Result = Info.EvaluatingDeclValue; 3307 return true; 3308 } 3309 3310 if (isa<ParmVarDecl>(VD)) { 3311 // Assume parameters of a potential constant expression are usable in 3312 // constant expressions. 3313 if (!Info.checkingPotentialConstantExpression() || 3314 !Info.CurrentCall->Callee || 3315 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3316 if (Info.getLangOpts().CPlusPlus11) { 3317 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3318 << VD; 3319 NoteLValueLocation(Info, Base); 3320 } else { 3321 Info.FFDiag(E); 3322 } 3323 } 3324 return false; 3325 } 3326 3327 // Dig out the initializer, and use the declaration which it's attached to. 3328 // FIXME: We should eventually check whether the variable has a reachable 3329 // initializing declaration. 3330 const Expr *Init = VD->getAnyInitializer(VD); 3331 if (!Init) { 3332 // Don't diagnose during potential constant expression checking; an 3333 // initializer might be added later. 3334 if (!Info.checkingPotentialConstantExpression()) { 3335 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3336 << VD; 3337 NoteLValueLocation(Info, Base); 3338 } 3339 return false; 3340 } 3341 3342 if (Init->isValueDependent()) { 3343 // The DeclRefExpr is not value-dependent, but the variable it refers to 3344 // has a value-dependent initializer. This should only happen in 3345 // constant-folding cases, where the variable is not actually of a suitable 3346 // type for use in a constant expression (otherwise the DeclRefExpr would 3347 // have been value-dependent too), so diagnose that. 3348 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3349 if (!Info.checkingPotentialConstantExpression()) { 3350 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3351 ? diag::note_constexpr_ltor_non_constexpr 3352 : diag::note_constexpr_ltor_non_integral, 1) 3353 << VD << VD->getType(); 3354 NoteLValueLocation(Info, Base); 3355 } 3356 return false; 3357 } 3358 3359 // Check that we can fold the initializer. In C++, we will have already done 3360 // this in the cases where it matters for conformance. 3361 if (!VD->evaluateValue()) { 3362 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3363 NoteLValueLocation(Info, Base); 3364 return false; 3365 } 3366 3367 // Check that the variable is actually usable in constant expressions. For a 3368 // const integral variable or a reference, we might have a non-constant 3369 // initializer that we can nonetheless evaluate the initializer for. Such 3370 // variables are not usable in constant expressions. In C++98, the 3371 // initializer also syntactically needs to be an ICE. 3372 // 3373 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3374 // expressions here; doing so would regress diagnostics for things like 3375 // reading from a volatile constexpr variable. 3376 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3377 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3378 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3379 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3380 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3381 NoteLValueLocation(Info, Base); 3382 } 3383 3384 // Never use the initializer of a weak variable, not even for constant 3385 // folding. We can't be sure that this is the definition that will be used. 3386 if (VD->isWeak()) { 3387 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3388 NoteLValueLocation(Info, Base); 3389 return false; 3390 } 3391 3392 Result = VD->getEvaluatedValue(); 3393 return true; 3394 } 3395 3396 /// Get the base index of the given base class within an APValue representing 3397 /// the given derived class. 3398 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3399 const CXXRecordDecl *Base) { 3400 Base = Base->getCanonicalDecl(); 3401 unsigned Index = 0; 3402 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3403 E = Derived->bases_end(); I != E; ++I, ++Index) { 3404 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3405 return Index; 3406 } 3407 3408 llvm_unreachable("base class missing from derived class's bases list"); 3409 } 3410 3411 /// Extract the value of a character from a string literal. 3412 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3413 uint64_t Index) { 3414 assert(!isa<SourceLocExpr>(Lit) && 3415 "SourceLocExpr should have already been converted to a StringLiteral"); 3416 3417 // FIXME: Support MakeStringConstant 3418 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3419 std::string Str; 3420 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3421 assert(Index <= Str.size() && "Index too large"); 3422 return APSInt::getUnsigned(Str.c_str()[Index]); 3423 } 3424 3425 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3426 Lit = PE->getFunctionName(); 3427 const StringLiteral *S = cast<StringLiteral>(Lit); 3428 const ConstantArrayType *CAT = 3429 Info.Ctx.getAsConstantArrayType(S->getType()); 3430 assert(CAT && "string literal isn't an array"); 3431 QualType CharType = CAT->getElementType(); 3432 assert(CharType->isIntegerType() && "unexpected character type"); 3433 3434 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3435 CharType->isUnsignedIntegerType()); 3436 if (Index < S->getLength()) 3437 Value = S->getCodeUnit(Index); 3438 return Value; 3439 } 3440 3441 // Expand a string literal into an array of characters. 3442 // 3443 // FIXME: This is inefficient; we should probably introduce something similar 3444 // to the LLVM ConstantDataArray to make this cheaper. 3445 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3446 APValue &Result, 3447 QualType AllocType = QualType()) { 3448 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3449 AllocType.isNull() ? S->getType() : AllocType); 3450 assert(CAT && "string literal isn't an array"); 3451 QualType CharType = CAT->getElementType(); 3452 assert(CharType->isIntegerType() && "unexpected character type"); 3453 3454 unsigned Elts = CAT->getSize().getZExtValue(); 3455 Result = APValue(APValue::UninitArray(), 3456 std::min(S->getLength(), Elts), Elts); 3457 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3458 CharType->isUnsignedIntegerType()); 3459 if (Result.hasArrayFiller()) 3460 Result.getArrayFiller() = APValue(Value); 3461 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3462 Value = S->getCodeUnit(I); 3463 Result.getArrayInitializedElt(I) = APValue(Value); 3464 } 3465 } 3466 3467 // Expand an array so that it has more than Index filled elements. 3468 static void expandArray(APValue &Array, unsigned Index) { 3469 unsigned Size = Array.getArraySize(); 3470 assert(Index < Size); 3471 3472 // Always at least double the number of elements for which we store a value. 3473 unsigned OldElts = Array.getArrayInitializedElts(); 3474 unsigned NewElts = std::max(Index+1, OldElts * 2); 3475 NewElts = std::min(Size, std::max(NewElts, 8u)); 3476 3477 // Copy the data across. 3478 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3479 for (unsigned I = 0; I != OldElts; ++I) 3480 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3481 for (unsigned I = OldElts; I != NewElts; ++I) 3482 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3483 if (NewValue.hasArrayFiller()) 3484 NewValue.getArrayFiller() = Array.getArrayFiller(); 3485 Array.swap(NewValue); 3486 } 3487 3488 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3489 /// conversion. If it's of class type, we may assume that the copy operation 3490 /// is trivial. Note that this is never true for a union type with fields 3491 /// (because the copy always "reads" the active member) and always true for 3492 /// a non-class type. 3493 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3494 static bool isReadByLvalueToRvalueConversion(QualType T) { 3495 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3496 return !RD || isReadByLvalueToRvalueConversion(RD); 3497 } 3498 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3499 // FIXME: A trivial copy of a union copies the object representation, even if 3500 // the union is empty. 3501 if (RD->isUnion()) 3502 return !RD->field_empty(); 3503 if (RD->isEmpty()) 3504 return false; 3505 3506 for (auto *Field : RD->fields()) 3507 if (!Field->isUnnamedBitfield() && 3508 isReadByLvalueToRvalueConversion(Field->getType())) 3509 return true; 3510 3511 for (auto &BaseSpec : RD->bases()) 3512 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3513 return true; 3514 3515 return false; 3516 } 3517 3518 /// Diagnose an attempt to read from any unreadable field within the specified 3519 /// type, which might be a class type. 3520 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3521 QualType T) { 3522 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3523 if (!RD) 3524 return false; 3525 3526 if (!RD->hasMutableFields()) 3527 return false; 3528 3529 for (auto *Field : RD->fields()) { 3530 // If we're actually going to read this field in some way, then it can't 3531 // be mutable. If we're in a union, then assigning to a mutable field 3532 // (even an empty one) can change the active member, so that's not OK. 3533 // FIXME: Add core issue number for the union case. 3534 if (Field->isMutable() && 3535 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3536 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3537 Info.Note(Field->getLocation(), diag::note_declared_at); 3538 return true; 3539 } 3540 3541 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3542 return true; 3543 } 3544 3545 for (auto &BaseSpec : RD->bases()) 3546 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3547 return true; 3548 3549 // All mutable fields were empty, and thus not actually read. 3550 return false; 3551 } 3552 3553 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3554 APValue::LValueBase Base, 3555 bool MutableSubobject = false) { 3556 // A temporary or transient heap allocation we created. 3557 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3558 return true; 3559 3560 switch (Info.IsEvaluatingDecl) { 3561 case EvalInfo::EvaluatingDeclKind::None: 3562 return false; 3563 3564 case EvalInfo::EvaluatingDeclKind::Ctor: 3565 // The variable whose initializer we're evaluating. 3566 if (Info.EvaluatingDecl == Base) 3567 return true; 3568 3569 // A temporary lifetime-extended by the variable whose initializer we're 3570 // evaluating. 3571 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3572 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3573 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3574 return false; 3575 3576 case EvalInfo::EvaluatingDeclKind::Dtor: 3577 // C++2a [expr.const]p6: 3578 // [during constant destruction] the lifetime of a and its non-mutable 3579 // subobjects (but not its mutable subobjects) [are] considered to start 3580 // within e. 3581 if (MutableSubobject || Base != Info.EvaluatingDecl) 3582 return false; 3583 // FIXME: We can meaningfully extend this to cover non-const objects, but 3584 // we will need special handling: we should be able to access only 3585 // subobjects of such objects that are themselves declared const. 3586 QualType T = getType(Base); 3587 return T.isConstQualified() || T->isReferenceType(); 3588 } 3589 3590 llvm_unreachable("unknown evaluating decl kind"); 3591 } 3592 3593 namespace { 3594 /// A handle to a complete object (an object that is not a subobject of 3595 /// another object). 3596 struct CompleteObject { 3597 /// The identity of the object. 3598 APValue::LValueBase Base; 3599 /// The value of the complete object. 3600 APValue *Value; 3601 /// The type of the complete object. 3602 QualType Type; 3603 3604 CompleteObject() : Value(nullptr) {} 3605 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3606 : Base(Base), Value(Value), Type(Type) {} 3607 3608 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3609 // If this isn't a "real" access (eg, if it's just accessing the type 3610 // info), allow it. We assume the type doesn't change dynamically for 3611 // subobjects of constexpr objects (even though we'd hit UB here if it 3612 // did). FIXME: Is this right? 3613 if (!isAnyAccess(AK)) 3614 return true; 3615 3616 // In C++14 onwards, it is permitted to read a mutable member whose 3617 // lifetime began within the evaluation. 3618 // FIXME: Should we also allow this in C++11? 3619 if (!Info.getLangOpts().CPlusPlus14) 3620 return false; 3621 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3622 } 3623 3624 explicit operator bool() const { return !Type.isNull(); } 3625 }; 3626 } // end anonymous namespace 3627 3628 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3629 bool IsMutable = false) { 3630 // C++ [basic.type.qualifier]p1: 3631 // - A const object is an object of type const T or a non-mutable subobject 3632 // of a const object. 3633 if (ObjType.isConstQualified() && !IsMutable) 3634 SubobjType.addConst(); 3635 // - A volatile object is an object of type const T or a subobject of a 3636 // volatile object. 3637 if (ObjType.isVolatileQualified()) 3638 SubobjType.addVolatile(); 3639 return SubobjType; 3640 } 3641 3642 /// Find the designated sub-object of an rvalue. 3643 template<typename SubobjectHandler> 3644 typename SubobjectHandler::result_type 3645 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3646 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3647 if (Sub.Invalid) 3648 // A diagnostic will have already been produced. 3649 return handler.failed(); 3650 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3651 if (Info.getLangOpts().CPlusPlus11) 3652 Info.FFDiag(E, Sub.isOnePastTheEnd() 3653 ? diag::note_constexpr_access_past_end 3654 : diag::note_constexpr_access_unsized_array) 3655 << handler.AccessKind; 3656 else 3657 Info.FFDiag(E); 3658 return handler.failed(); 3659 } 3660 3661 APValue *O = Obj.Value; 3662 QualType ObjType = Obj.Type; 3663 const FieldDecl *LastField = nullptr; 3664 const FieldDecl *VolatileField = nullptr; 3665 3666 // Walk the designator's path to find the subobject. 3667 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3668 // Reading an indeterminate value is undefined, but assigning over one is OK. 3669 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3670 (O->isIndeterminate() && 3671 !isValidIndeterminateAccess(handler.AccessKind))) { 3672 if (!Info.checkingPotentialConstantExpression()) 3673 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3674 << handler.AccessKind << O->isIndeterminate(); 3675 return handler.failed(); 3676 } 3677 3678 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3679 // const and volatile semantics are not applied on an object under 3680 // {con,de}struction. 3681 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3682 ObjType->isRecordType() && 3683 Info.isEvaluatingCtorDtor( 3684 Obj.Base, 3685 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) != 3686 ConstructionPhase::None) { 3687 ObjType = Info.Ctx.getCanonicalType(ObjType); 3688 ObjType.removeLocalConst(); 3689 ObjType.removeLocalVolatile(); 3690 } 3691 3692 // If this is our last pass, check that the final object type is OK. 3693 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3694 // Accesses to volatile objects are prohibited. 3695 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3696 if (Info.getLangOpts().CPlusPlus) { 3697 int DiagKind; 3698 SourceLocation Loc; 3699 const NamedDecl *Decl = nullptr; 3700 if (VolatileField) { 3701 DiagKind = 2; 3702 Loc = VolatileField->getLocation(); 3703 Decl = VolatileField; 3704 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3705 DiagKind = 1; 3706 Loc = VD->getLocation(); 3707 Decl = VD; 3708 } else { 3709 DiagKind = 0; 3710 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3711 Loc = E->getExprLoc(); 3712 } 3713 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3714 << handler.AccessKind << DiagKind << Decl; 3715 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3716 } else { 3717 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3718 } 3719 return handler.failed(); 3720 } 3721 3722 // If we are reading an object of class type, there may still be more 3723 // things we need to check: if there are any mutable subobjects, we 3724 // cannot perform this read. (This only happens when performing a trivial 3725 // copy or assignment.) 3726 if (ObjType->isRecordType() && 3727 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3728 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3729 return handler.failed(); 3730 } 3731 3732 if (I == N) { 3733 if (!handler.found(*O, ObjType)) 3734 return false; 3735 3736 // If we modified a bit-field, truncate it to the right width. 3737 if (isModification(handler.AccessKind) && 3738 LastField && LastField->isBitField() && 3739 !truncateBitfieldValue(Info, E, *O, LastField)) 3740 return false; 3741 3742 return true; 3743 } 3744 3745 LastField = nullptr; 3746 if (ObjType->isArrayType()) { 3747 // Next subobject is an array element. 3748 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3749 assert(CAT && "vla in literal type?"); 3750 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3751 if (CAT->getSize().ule(Index)) { 3752 // Note, it should not be possible to form a pointer with a valid 3753 // designator which points more than one past the end of the array. 3754 if (Info.getLangOpts().CPlusPlus11) 3755 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3756 << handler.AccessKind; 3757 else 3758 Info.FFDiag(E); 3759 return handler.failed(); 3760 } 3761 3762 ObjType = CAT->getElementType(); 3763 3764 if (O->getArrayInitializedElts() > Index) 3765 O = &O->getArrayInitializedElt(Index); 3766 else if (!isRead(handler.AccessKind)) { 3767 expandArray(*O, Index); 3768 O = &O->getArrayInitializedElt(Index); 3769 } else 3770 O = &O->getArrayFiller(); 3771 } else if (ObjType->isAnyComplexType()) { 3772 // Next subobject is a complex number. 3773 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3774 if (Index > 1) { 3775 if (Info.getLangOpts().CPlusPlus11) 3776 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3777 << handler.AccessKind; 3778 else 3779 Info.FFDiag(E); 3780 return handler.failed(); 3781 } 3782 3783 ObjType = getSubobjectType( 3784 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3785 3786 assert(I == N - 1 && "extracting subobject of scalar?"); 3787 if (O->isComplexInt()) { 3788 return handler.found(Index ? O->getComplexIntImag() 3789 : O->getComplexIntReal(), ObjType); 3790 } else { 3791 assert(O->isComplexFloat()); 3792 return handler.found(Index ? O->getComplexFloatImag() 3793 : O->getComplexFloatReal(), ObjType); 3794 } 3795 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3796 if (Field->isMutable() && 3797 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3798 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3799 << handler.AccessKind << Field; 3800 Info.Note(Field->getLocation(), diag::note_declared_at); 3801 return handler.failed(); 3802 } 3803 3804 // Next subobject is a class, struct or union field. 3805 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3806 if (RD->isUnion()) { 3807 const FieldDecl *UnionField = O->getUnionField(); 3808 if (!UnionField || 3809 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3810 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3811 // Placement new onto an inactive union member makes it active. 3812 O->setUnion(Field, APValue()); 3813 } else { 3814 // FIXME: If O->getUnionValue() is absent, report that there's no 3815 // active union member rather than reporting the prior active union 3816 // member. We'll need to fix nullptr_t to not use APValue() as its 3817 // representation first. 3818 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3819 << handler.AccessKind << Field << !UnionField << UnionField; 3820 return handler.failed(); 3821 } 3822 } 3823 O = &O->getUnionValue(); 3824 } else 3825 O = &O->getStructField(Field->getFieldIndex()); 3826 3827 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3828 LastField = Field; 3829 if (Field->getType().isVolatileQualified()) 3830 VolatileField = Field; 3831 } else { 3832 // Next subobject is a base class. 3833 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3834 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3835 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3836 3837 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3838 } 3839 } 3840 } 3841 3842 namespace { 3843 struct ExtractSubobjectHandler { 3844 EvalInfo &Info; 3845 const Expr *E; 3846 APValue &Result; 3847 const AccessKinds AccessKind; 3848 3849 typedef bool result_type; 3850 bool failed() { return false; } 3851 bool found(APValue &Subobj, QualType SubobjType) { 3852 Result = Subobj; 3853 if (AccessKind == AK_ReadObjectRepresentation) 3854 return true; 3855 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3856 } 3857 bool found(APSInt &Value, QualType SubobjType) { 3858 Result = APValue(Value); 3859 return true; 3860 } 3861 bool found(APFloat &Value, QualType SubobjType) { 3862 Result = APValue(Value); 3863 return true; 3864 } 3865 }; 3866 } // end anonymous namespace 3867 3868 /// Extract the designated sub-object of an rvalue. 3869 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3870 const CompleteObject &Obj, 3871 const SubobjectDesignator &Sub, APValue &Result, 3872 AccessKinds AK = AK_Read) { 3873 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3874 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3875 return findSubobject(Info, E, Obj, Sub, Handler); 3876 } 3877 3878 namespace { 3879 struct ModifySubobjectHandler { 3880 EvalInfo &Info; 3881 APValue &NewVal; 3882 const Expr *E; 3883 3884 typedef bool result_type; 3885 static const AccessKinds AccessKind = AK_Assign; 3886 3887 bool checkConst(QualType QT) { 3888 // Assigning to a const object has undefined behavior. 3889 if (QT.isConstQualified()) { 3890 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3891 return false; 3892 } 3893 return true; 3894 } 3895 3896 bool failed() { return false; } 3897 bool found(APValue &Subobj, QualType SubobjType) { 3898 if (!checkConst(SubobjType)) 3899 return false; 3900 // We've been given ownership of NewVal, so just swap it in. 3901 Subobj.swap(NewVal); 3902 return true; 3903 } 3904 bool found(APSInt &Value, QualType SubobjType) { 3905 if (!checkConst(SubobjType)) 3906 return false; 3907 if (!NewVal.isInt()) { 3908 // Maybe trying to write a cast pointer value into a complex? 3909 Info.FFDiag(E); 3910 return false; 3911 } 3912 Value = NewVal.getInt(); 3913 return true; 3914 } 3915 bool found(APFloat &Value, QualType SubobjType) { 3916 if (!checkConst(SubobjType)) 3917 return false; 3918 Value = NewVal.getFloat(); 3919 return true; 3920 } 3921 }; 3922 } // end anonymous namespace 3923 3924 const AccessKinds ModifySubobjectHandler::AccessKind; 3925 3926 /// Update the designated sub-object of an rvalue to the given value. 3927 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3928 const CompleteObject &Obj, 3929 const SubobjectDesignator &Sub, 3930 APValue &NewVal) { 3931 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3932 return findSubobject(Info, E, Obj, Sub, Handler); 3933 } 3934 3935 /// Find the position where two subobject designators diverge, or equivalently 3936 /// the length of the common initial subsequence. 3937 static unsigned FindDesignatorMismatch(QualType ObjType, 3938 const SubobjectDesignator &A, 3939 const SubobjectDesignator &B, 3940 bool &WasArrayIndex) { 3941 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3942 for (/**/; I != N; ++I) { 3943 if (!ObjType.isNull() && 3944 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3945 // Next subobject is an array element. 3946 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3947 WasArrayIndex = true; 3948 return I; 3949 } 3950 if (ObjType->isAnyComplexType()) 3951 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3952 else 3953 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3954 } else { 3955 if (A.Entries[I].getAsBaseOrMember() != 3956 B.Entries[I].getAsBaseOrMember()) { 3957 WasArrayIndex = false; 3958 return I; 3959 } 3960 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3961 // Next subobject is a field. 3962 ObjType = FD->getType(); 3963 else 3964 // Next subobject is a base class. 3965 ObjType = QualType(); 3966 } 3967 } 3968 WasArrayIndex = false; 3969 return I; 3970 } 3971 3972 /// Determine whether the given subobject designators refer to elements of the 3973 /// same array object. 3974 static bool AreElementsOfSameArray(QualType ObjType, 3975 const SubobjectDesignator &A, 3976 const SubobjectDesignator &B) { 3977 if (A.Entries.size() != B.Entries.size()) 3978 return false; 3979 3980 bool IsArray = A.MostDerivedIsArrayElement; 3981 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3982 // A is a subobject of the array element. 3983 return false; 3984 3985 // If A (and B) designates an array element, the last entry will be the array 3986 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3987 // of length 1' case, and the entire path must match. 3988 bool WasArrayIndex; 3989 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3990 return CommonLength >= A.Entries.size() - IsArray; 3991 } 3992 3993 /// Find the complete object to which an LValue refers. 3994 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3995 AccessKinds AK, const LValue &LVal, 3996 QualType LValType) { 3997 if (LVal.InvalidBase) { 3998 Info.FFDiag(E); 3999 return CompleteObject(); 4000 } 4001 4002 if (!LVal.Base) { 4003 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 4004 return CompleteObject(); 4005 } 4006 4007 CallStackFrame *Frame = nullptr; 4008 unsigned Depth = 0; 4009 if (LVal.getLValueCallIndex()) { 4010 std::tie(Frame, Depth) = 4011 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 4012 if (!Frame) { 4013 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 4014 << AK << LVal.Base.is<const ValueDecl*>(); 4015 NoteLValueLocation(Info, LVal.Base); 4016 return CompleteObject(); 4017 } 4018 } 4019 4020 bool IsAccess = isAnyAccess(AK); 4021 4022 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 4023 // is not a constant expression (even if the object is non-volatile). We also 4024 // apply this rule to C++98, in order to conform to the expected 'volatile' 4025 // semantics. 4026 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 4027 if (Info.getLangOpts().CPlusPlus) 4028 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 4029 << AK << LValType; 4030 else 4031 Info.FFDiag(E); 4032 return CompleteObject(); 4033 } 4034 4035 // Compute value storage location and type of base object. 4036 APValue *BaseVal = nullptr; 4037 QualType BaseType = getType(LVal.Base); 4038 4039 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4040 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4041 // This is the object whose initializer we're evaluating, so its lifetime 4042 // started in the current evaluation. 4043 BaseVal = Info.EvaluatingDeclValue; 4044 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4045 // Allow reading from a GUID declaration. 4046 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4047 if (isModification(AK)) { 4048 // All the remaining cases do not permit modification of the object. 4049 Info.FFDiag(E, diag::note_constexpr_modify_global); 4050 return CompleteObject(); 4051 } 4052 APValue &V = GD->getAsAPValue(); 4053 if (V.isAbsent()) { 4054 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4055 << GD->getType(); 4056 return CompleteObject(); 4057 } 4058 return CompleteObject(LVal.Base, &V, GD->getType()); 4059 } 4060 4061 // Allow reading the APValue from an UnnamedGlobalConstantDecl. 4062 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) { 4063 if (isModification(AK)) { 4064 Info.FFDiag(E, diag::note_constexpr_modify_global); 4065 return CompleteObject(); 4066 } 4067 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), 4068 GCD->getType()); 4069 } 4070 4071 // Allow reading from template parameter objects. 4072 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4073 if (isModification(AK)) { 4074 Info.FFDiag(E, diag::note_constexpr_modify_global); 4075 return CompleteObject(); 4076 } 4077 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4078 TPO->getType()); 4079 } 4080 4081 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4082 // In C++11, constexpr, non-volatile variables initialized with constant 4083 // expressions are constant expressions too. Inside constexpr functions, 4084 // parameters are constant expressions even if they're non-const. 4085 // In C++1y, objects local to a constant expression (those with a Frame) are 4086 // both readable and writable inside constant expressions. 4087 // In C, such things can also be folded, although they are not ICEs. 4088 const VarDecl *VD = dyn_cast<VarDecl>(D); 4089 if (VD) { 4090 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4091 VD = VDef; 4092 } 4093 if (!VD || VD->isInvalidDecl()) { 4094 Info.FFDiag(E); 4095 return CompleteObject(); 4096 } 4097 4098 bool IsConstant = BaseType.isConstant(Info.Ctx); 4099 4100 // Unless we're looking at a local variable or argument in a constexpr call, 4101 // the variable we're reading must be const. 4102 if (!Frame) { 4103 if (IsAccess && isa<ParmVarDecl>(VD)) { 4104 // Access of a parameter that's not associated with a frame isn't going 4105 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4106 // suitable diagnostic. 4107 } else if (Info.getLangOpts().CPlusPlus14 && 4108 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4109 // OK, we can read and modify an object if we're in the process of 4110 // evaluating its initializer, because its lifetime began in this 4111 // evaluation. 4112 } else if (isModification(AK)) { 4113 // All the remaining cases do not permit modification of the object. 4114 Info.FFDiag(E, diag::note_constexpr_modify_global); 4115 return CompleteObject(); 4116 } else if (VD->isConstexpr()) { 4117 // OK, we can read this variable. 4118 } else if (BaseType->isIntegralOrEnumerationType()) { 4119 if (!IsConstant) { 4120 if (!IsAccess) 4121 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4122 if (Info.getLangOpts().CPlusPlus) { 4123 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4124 Info.Note(VD->getLocation(), diag::note_declared_at); 4125 } else { 4126 Info.FFDiag(E); 4127 } 4128 return CompleteObject(); 4129 } 4130 } else if (!IsAccess) { 4131 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4132 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4133 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4134 // This variable might end up being constexpr. Don't diagnose it yet. 4135 } else if (IsConstant) { 4136 // Keep evaluating to see what we can do. In particular, we support 4137 // folding of const floating-point types, in order to make static const 4138 // data members of such types (supported as an extension) more useful. 4139 if (Info.getLangOpts().CPlusPlus) { 4140 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4141 ? diag::note_constexpr_ltor_non_constexpr 4142 : diag::note_constexpr_ltor_non_integral, 1) 4143 << VD << BaseType; 4144 Info.Note(VD->getLocation(), diag::note_declared_at); 4145 } else { 4146 Info.CCEDiag(E); 4147 } 4148 } else { 4149 // Never allow reading a non-const value. 4150 if (Info.getLangOpts().CPlusPlus) { 4151 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4152 ? diag::note_constexpr_ltor_non_constexpr 4153 : diag::note_constexpr_ltor_non_integral, 1) 4154 << VD << BaseType; 4155 Info.Note(VD->getLocation(), diag::note_declared_at); 4156 } else { 4157 Info.FFDiag(E); 4158 } 4159 return CompleteObject(); 4160 } 4161 } 4162 4163 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4164 return CompleteObject(); 4165 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4166 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 4167 if (!Alloc) { 4168 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4169 return CompleteObject(); 4170 } 4171 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4172 LVal.Base.getDynamicAllocType()); 4173 } else { 4174 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4175 4176 if (!Frame) { 4177 if (const MaterializeTemporaryExpr *MTE = 4178 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4179 assert(MTE->getStorageDuration() == SD_Static && 4180 "should have a frame for a non-global materialized temporary"); 4181 4182 // C++20 [expr.const]p4: [DR2126] 4183 // An object or reference is usable in constant expressions if it is 4184 // - a temporary object of non-volatile const-qualified literal type 4185 // whose lifetime is extended to that of a variable that is usable 4186 // in constant expressions 4187 // 4188 // C++20 [expr.const]p5: 4189 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4190 // - a non-volatile glvalue that refers to an object that is usable 4191 // in constant expressions, or 4192 // - a non-volatile glvalue of literal type that refers to a 4193 // non-volatile object whose lifetime began within the evaluation 4194 // of E; 4195 // 4196 // C++11 misses the 'began within the evaluation of e' check and 4197 // instead allows all temporaries, including things like: 4198 // int &&r = 1; 4199 // int x = ++r; 4200 // constexpr int k = r; 4201 // Therefore we use the C++14-onwards rules in C++11 too. 4202 // 4203 // Note that temporaries whose lifetimes began while evaluating a 4204 // variable's constructor are not usable while evaluating the 4205 // corresponding destructor, not even if they're of const-qualified 4206 // types. 4207 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4208 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4209 if (!IsAccess) 4210 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4211 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4212 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4213 return CompleteObject(); 4214 } 4215 4216 BaseVal = MTE->getOrCreateValue(false); 4217 assert(BaseVal && "got reference to unevaluated temporary"); 4218 } else { 4219 if (!IsAccess) 4220 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4221 APValue Val; 4222 LVal.moveInto(Val); 4223 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4224 << AK 4225 << Val.getAsString(Info.Ctx, 4226 Info.Ctx.getLValueReferenceType(LValType)); 4227 NoteLValueLocation(Info, LVal.Base); 4228 return CompleteObject(); 4229 } 4230 } else { 4231 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4232 assert(BaseVal && "missing value for temporary"); 4233 } 4234 } 4235 4236 // In C++14, we can't safely access any mutable state when we might be 4237 // evaluating after an unmodeled side effect. Parameters are modeled as state 4238 // in the caller, but aren't visible once the call returns, so they can be 4239 // modified in a speculatively-evaluated call. 4240 // 4241 // FIXME: Not all local state is mutable. Allow local constant subobjects 4242 // to be read here (but take care with 'mutable' fields). 4243 unsigned VisibleDepth = Depth; 4244 if (llvm::isa_and_nonnull<ParmVarDecl>( 4245 LVal.Base.dyn_cast<const ValueDecl *>())) 4246 ++VisibleDepth; 4247 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4248 Info.EvalStatus.HasSideEffects) || 4249 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4250 return CompleteObject(); 4251 4252 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4253 } 4254 4255 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4256 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4257 /// glvalue referred to by an entity of reference type. 4258 /// 4259 /// \param Info - Information about the ongoing evaluation. 4260 /// \param Conv - The expression for which we are performing the conversion. 4261 /// Used for diagnostics. 4262 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4263 /// case of a non-class type). 4264 /// \param LVal - The glvalue on which we are attempting to perform this action. 4265 /// \param RVal - The produced value will be placed here. 4266 /// \param WantObjectRepresentation - If true, we're looking for the object 4267 /// representation rather than the value, and in particular, 4268 /// there is no requirement that the result be fully initialized. 4269 static bool 4270 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4271 const LValue &LVal, APValue &RVal, 4272 bool WantObjectRepresentation = false) { 4273 if (LVal.Designator.Invalid) 4274 return false; 4275 4276 // Check for special cases where there is no existing APValue to look at. 4277 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4278 4279 AccessKinds AK = 4280 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4281 4282 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4283 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4284 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4285 // initializer until now for such expressions. Such an expression can't be 4286 // an ICE in C, so this only matters for fold. 4287 if (Type.isVolatileQualified()) { 4288 Info.FFDiag(Conv); 4289 return false; 4290 } 4291 4292 APValue Lit; 4293 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4294 return false; 4295 4296 // According to GCC info page: 4297 // 4298 // 6.28 Compound Literals 4299 // 4300 // As an optimization, G++ sometimes gives array compound literals longer 4301 // lifetimes: when the array either appears outside a function or has a 4302 // const-qualified type. If foo and its initializer had elements of type 4303 // char *const rather than char *, or if foo were a global variable, the 4304 // array would have static storage duration. But it is probably safest 4305 // just to avoid the use of array compound literals in C++ code. 4306 // 4307 // Obey that rule by checking constness for converted array types. 4308 4309 QualType CLETy = CLE->getType(); 4310 if (CLETy->isArrayType() && !Type->isArrayType()) { 4311 if (!CLETy.isConstant(Info.Ctx)) { 4312 Info.FFDiag(Conv); 4313 Info.Note(CLE->getExprLoc(), diag::note_declared_at); 4314 return false; 4315 } 4316 } 4317 4318 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4319 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4320 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4321 // Special-case character extraction so we don't have to construct an 4322 // APValue for the whole string. 4323 assert(LVal.Designator.Entries.size() <= 1 && 4324 "Can only read characters from string literals"); 4325 if (LVal.Designator.Entries.empty()) { 4326 // Fail for now for LValue to RValue conversion of an array. 4327 // (This shouldn't show up in C/C++, but it could be triggered by a 4328 // weird EvaluateAsRValue call from a tool.) 4329 Info.FFDiag(Conv); 4330 return false; 4331 } 4332 if (LVal.Designator.isOnePastTheEnd()) { 4333 if (Info.getLangOpts().CPlusPlus11) 4334 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4335 else 4336 Info.FFDiag(Conv); 4337 return false; 4338 } 4339 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4340 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4341 return true; 4342 } 4343 } 4344 4345 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4346 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4347 } 4348 4349 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4350 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4351 QualType LValType, APValue &Val) { 4352 if (LVal.Designator.Invalid) 4353 return false; 4354 4355 if (!Info.getLangOpts().CPlusPlus14) { 4356 Info.FFDiag(E); 4357 return false; 4358 } 4359 4360 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4361 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4362 } 4363 4364 namespace { 4365 struct CompoundAssignSubobjectHandler { 4366 EvalInfo &Info; 4367 const CompoundAssignOperator *E; 4368 QualType PromotedLHSType; 4369 BinaryOperatorKind Opcode; 4370 const APValue &RHS; 4371 4372 static const AccessKinds AccessKind = AK_Assign; 4373 4374 typedef bool result_type; 4375 4376 bool checkConst(QualType QT) { 4377 // Assigning to a const object has undefined behavior. 4378 if (QT.isConstQualified()) { 4379 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4380 return false; 4381 } 4382 return true; 4383 } 4384 4385 bool failed() { return false; } 4386 bool found(APValue &Subobj, QualType SubobjType) { 4387 switch (Subobj.getKind()) { 4388 case APValue::Int: 4389 return found(Subobj.getInt(), SubobjType); 4390 case APValue::Float: 4391 return found(Subobj.getFloat(), SubobjType); 4392 case APValue::ComplexInt: 4393 case APValue::ComplexFloat: 4394 // FIXME: Implement complex compound assignment. 4395 Info.FFDiag(E); 4396 return false; 4397 case APValue::LValue: 4398 return foundPointer(Subobj, SubobjType); 4399 case APValue::Vector: 4400 return foundVector(Subobj, SubobjType); 4401 default: 4402 // FIXME: can this happen? 4403 Info.FFDiag(E); 4404 return false; 4405 } 4406 } 4407 4408 bool foundVector(APValue &Value, QualType SubobjType) { 4409 if (!checkConst(SubobjType)) 4410 return false; 4411 4412 if (!SubobjType->isVectorType()) { 4413 Info.FFDiag(E); 4414 return false; 4415 } 4416 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4417 } 4418 4419 bool found(APSInt &Value, QualType SubobjType) { 4420 if (!checkConst(SubobjType)) 4421 return false; 4422 4423 if (!SubobjType->isIntegerType()) { 4424 // We don't support compound assignment on integer-cast-to-pointer 4425 // values. 4426 Info.FFDiag(E); 4427 return false; 4428 } 4429 4430 if (RHS.isInt()) { 4431 APSInt LHS = 4432 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4433 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4434 return false; 4435 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4436 return true; 4437 } else if (RHS.isFloat()) { 4438 const FPOptions FPO = E->getFPFeaturesInEffect( 4439 Info.Ctx.getLangOpts()); 4440 APFloat FValue(0.0); 4441 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4442 PromotedLHSType, FValue) && 4443 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4444 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4445 Value); 4446 } 4447 4448 Info.FFDiag(E); 4449 return false; 4450 } 4451 bool found(APFloat &Value, QualType SubobjType) { 4452 return checkConst(SubobjType) && 4453 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4454 Value) && 4455 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4456 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4457 } 4458 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4459 if (!checkConst(SubobjType)) 4460 return false; 4461 4462 QualType PointeeType; 4463 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4464 PointeeType = PT->getPointeeType(); 4465 4466 if (PointeeType.isNull() || !RHS.isInt() || 4467 (Opcode != BO_Add && Opcode != BO_Sub)) { 4468 Info.FFDiag(E); 4469 return false; 4470 } 4471 4472 APSInt Offset = RHS.getInt(); 4473 if (Opcode == BO_Sub) 4474 negateAsSigned(Offset); 4475 4476 LValue LVal; 4477 LVal.setFrom(Info.Ctx, Subobj); 4478 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4479 return false; 4480 LVal.moveInto(Subobj); 4481 return true; 4482 } 4483 }; 4484 } // end anonymous namespace 4485 4486 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4487 4488 /// Perform a compound assignment of LVal <op>= RVal. 4489 static bool handleCompoundAssignment(EvalInfo &Info, 4490 const CompoundAssignOperator *E, 4491 const LValue &LVal, QualType LValType, 4492 QualType PromotedLValType, 4493 BinaryOperatorKind Opcode, 4494 const APValue &RVal) { 4495 if (LVal.Designator.Invalid) 4496 return false; 4497 4498 if (!Info.getLangOpts().CPlusPlus14) { 4499 Info.FFDiag(E); 4500 return false; 4501 } 4502 4503 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4504 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4505 RVal }; 4506 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4507 } 4508 4509 namespace { 4510 struct IncDecSubobjectHandler { 4511 EvalInfo &Info; 4512 const UnaryOperator *E; 4513 AccessKinds AccessKind; 4514 APValue *Old; 4515 4516 typedef bool result_type; 4517 4518 bool checkConst(QualType QT) { 4519 // Assigning to a const object has undefined behavior. 4520 if (QT.isConstQualified()) { 4521 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4522 return false; 4523 } 4524 return true; 4525 } 4526 4527 bool failed() { return false; } 4528 bool found(APValue &Subobj, QualType SubobjType) { 4529 // Stash the old value. Also clear Old, so we don't clobber it later 4530 // if we're post-incrementing a complex. 4531 if (Old) { 4532 *Old = Subobj; 4533 Old = nullptr; 4534 } 4535 4536 switch (Subobj.getKind()) { 4537 case APValue::Int: 4538 return found(Subobj.getInt(), SubobjType); 4539 case APValue::Float: 4540 return found(Subobj.getFloat(), SubobjType); 4541 case APValue::ComplexInt: 4542 return found(Subobj.getComplexIntReal(), 4543 SubobjType->castAs<ComplexType>()->getElementType() 4544 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4545 case APValue::ComplexFloat: 4546 return found(Subobj.getComplexFloatReal(), 4547 SubobjType->castAs<ComplexType>()->getElementType() 4548 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4549 case APValue::LValue: 4550 return foundPointer(Subobj, SubobjType); 4551 default: 4552 // FIXME: can this happen? 4553 Info.FFDiag(E); 4554 return false; 4555 } 4556 } 4557 bool found(APSInt &Value, QualType SubobjType) { 4558 if (!checkConst(SubobjType)) 4559 return false; 4560 4561 if (!SubobjType->isIntegerType()) { 4562 // We don't support increment / decrement on integer-cast-to-pointer 4563 // values. 4564 Info.FFDiag(E); 4565 return false; 4566 } 4567 4568 if (Old) *Old = APValue(Value); 4569 4570 // bool arithmetic promotes to int, and the conversion back to bool 4571 // doesn't reduce mod 2^n, so special-case it. 4572 if (SubobjType->isBooleanType()) { 4573 if (AccessKind == AK_Increment) 4574 Value = 1; 4575 else 4576 Value = !Value; 4577 return true; 4578 } 4579 4580 bool WasNegative = Value.isNegative(); 4581 if (AccessKind == AK_Increment) { 4582 ++Value; 4583 4584 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4585 APSInt ActualValue(Value, /*IsUnsigned*/true); 4586 return HandleOverflow(Info, E, ActualValue, SubobjType); 4587 } 4588 } else { 4589 --Value; 4590 4591 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4592 unsigned BitWidth = Value.getBitWidth(); 4593 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4594 ActualValue.setBit(BitWidth); 4595 return HandleOverflow(Info, E, ActualValue, SubobjType); 4596 } 4597 } 4598 return true; 4599 } 4600 bool found(APFloat &Value, QualType SubobjType) { 4601 if (!checkConst(SubobjType)) 4602 return false; 4603 4604 if (Old) *Old = APValue(Value); 4605 4606 APFloat One(Value.getSemantics(), 1); 4607 if (AccessKind == AK_Increment) 4608 Value.add(One, APFloat::rmNearestTiesToEven); 4609 else 4610 Value.subtract(One, APFloat::rmNearestTiesToEven); 4611 return true; 4612 } 4613 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4614 if (!checkConst(SubobjType)) 4615 return false; 4616 4617 QualType PointeeType; 4618 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4619 PointeeType = PT->getPointeeType(); 4620 else { 4621 Info.FFDiag(E); 4622 return false; 4623 } 4624 4625 LValue LVal; 4626 LVal.setFrom(Info.Ctx, Subobj); 4627 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4628 AccessKind == AK_Increment ? 1 : -1)) 4629 return false; 4630 LVal.moveInto(Subobj); 4631 return true; 4632 } 4633 }; 4634 } // end anonymous namespace 4635 4636 /// Perform an increment or decrement on LVal. 4637 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4638 QualType LValType, bool IsIncrement, APValue *Old) { 4639 if (LVal.Designator.Invalid) 4640 return false; 4641 4642 if (!Info.getLangOpts().CPlusPlus14) { 4643 Info.FFDiag(E); 4644 return false; 4645 } 4646 4647 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4648 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4649 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4650 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4651 } 4652 4653 /// Build an lvalue for the object argument of a member function call. 4654 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4655 LValue &This) { 4656 if (Object->getType()->isPointerType() && Object->isPRValue()) 4657 return EvaluatePointer(Object, This, Info); 4658 4659 if (Object->isGLValue()) 4660 return EvaluateLValue(Object, This, Info); 4661 4662 if (Object->getType()->isLiteralType(Info.Ctx)) 4663 return EvaluateTemporary(Object, This, Info); 4664 4665 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4666 return false; 4667 } 4668 4669 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4670 /// lvalue referring to the result. 4671 /// 4672 /// \param Info - Information about the ongoing evaluation. 4673 /// \param LV - An lvalue referring to the base of the member pointer. 4674 /// \param RHS - The member pointer expression. 4675 /// \param IncludeMember - Specifies whether the member itself is included in 4676 /// the resulting LValue subobject designator. This is not possible when 4677 /// creating a bound member function. 4678 /// \return The field or method declaration to which the member pointer refers, 4679 /// or 0 if evaluation fails. 4680 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4681 QualType LVType, 4682 LValue &LV, 4683 const Expr *RHS, 4684 bool IncludeMember = true) { 4685 MemberPtr MemPtr; 4686 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4687 return nullptr; 4688 4689 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4690 // member value, the behavior is undefined. 4691 if (!MemPtr.getDecl()) { 4692 // FIXME: Specific diagnostic. 4693 Info.FFDiag(RHS); 4694 return nullptr; 4695 } 4696 4697 if (MemPtr.isDerivedMember()) { 4698 // This is a member of some derived class. Truncate LV appropriately. 4699 // The end of the derived-to-base path for the base object must match the 4700 // derived-to-base path for the member pointer. 4701 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4702 LV.Designator.Entries.size()) { 4703 Info.FFDiag(RHS); 4704 return nullptr; 4705 } 4706 unsigned PathLengthToMember = 4707 LV.Designator.Entries.size() - MemPtr.Path.size(); 4708 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4709 const CXXRecordDecl *LVDecl = getAsBaseClass( 4710 LV.Designator.Entries[PathLengthToMember + I]); 4711 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4712 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4713 Info.FFDiag(RHS); 4714 return nullptr; 4715 } 4716 } 4717 4718 // Truncate the lvalue to the appropriate derived class. 4719 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4720 PathLengthToMember)) 4721 return nullptr; 4722 } else if (!MemPtr.Path.empty()) { 4723 // Extend the LValue path with the member pointer's path. 4724 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4725 MemPtr.Path.size() + IncludeMember); 4726 4727 // Walk down to the appropriate base class. 4728 if (const PointerType *PT = LVType->getAs<PointerType>()) 4729 LVType = PT->getPointeeType(); 4730 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4731 assert(RD && "member pointer access on non-class-type expression"); 4732 // The first class in the path is that of the lvalue. 4733 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4734 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4735 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4736 return nullptr; 4737 RD = Base; 4738 } 4739 // Finally cast to the class containing the member. 4740 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4741 MemPtr.getContainingRecord())) 4742 return nullptr; 4743 } 4744 4745 // Add the member. Note that we cannot build bound member functions here. 4746 if (IncludeMember) { 4747 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4748 if (!HandleLValueMember(Info, RHS, LV, FD)) 4749 return nullptr; 4750 } else if (const IndirectFieldDecl *IFD = 4751 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4752 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4753 return nullptr; 4754 } else { 4755 llvm_unreachable("can't construct reference to bound member function"); 4756 } 4757 } 4758 4759 return MemPtr.getDecl(); 4760 } 4761 4762 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4763 const BinaryOperator *BO, 4764 LValue &LV, 4765 bool IncludeMember = true) { 4766 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4767 4768 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4769 if (Info.noteFailure()) { 4770 MemberPtr MemPtr; 4771 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4772 } 4773 return nullptr; 4774 } 4775 4776 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4777 BO->getRHS(), IncludeMember); 4778 } 4779 4780 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4781 /// the provided lvalue, which currently refers to the base object. 4782 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4783 LValue &Result) { 4784 SubobjectDesignator &D = Result.Designator; 4785 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4786 return false; 4787 4788 QualType TargetQT = E->getType(); 4789 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4790 TargetQT = PT->getPointeeType(); 4791 4792 // Check this cast lands within the final derived-to-base subobject path. 4793 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4794 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4795 << D.MostDerivedType << TargetQT; 4796 return false; 4797 } 4798 4799 // Check the type of the final cast. We don't need to check the path, 4800 // since a cast can only be formed if the path is unique. 4801 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4802 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4803 const CXXRecordDecl *FinalType; 4804 if (NewEntriesSize == D.MostDerivedPathLength) 4805 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4806 else 4807 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4808 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4809 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4810 << D.MostDerivedType << TargetQT; 4811 return false; 4812 } 4813 4814 // Truncate the lvalue to the appropriate derived class. 4815 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4816 } 4817 4818 /// Get the value to use for a default-initialized object of type T. 4819 /// Return false if it encounters something invalid. 4820 static bool getDefaultInitValue(QualType T, APValue &Result) { 4821 bool Success = true; 4822 if (auto *RD = T->getAsCXXRecordDecl()) { 4823 if (RD->isInvalidDecl()) { 4824 Result = APValue(); 4825 return false; 4826 } 4827 if (RD->isUnion()) { 4828 Result = APValue((const FieldDecl *)nullptr); 4829 return true; 4830 } 4831 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4832 std::distance(RD->field_begin(), RD->field_end())); 4833 4834 unsigned Index = 0; 4835 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4836 End = RD->bases_end(); 4837 I != End; ++I, ++Index) 4838 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4839 4840 for (const auto *I : RD->fields()) { 4841 if (I->isUnnamedBitfield()) 4842 continue; 4843 Success &= getDefaultInitValue(I->getType(), 4844 Result.getStructField(I->getFieldIndex())); 4845 } 4846 return Success; 4847 } 4848 4849 if (auto *AT = 4850 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4851 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4852 if (Result.hasArrayFiller()) 4853 Success &= 4854 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4855 4856 return Success; 4857 } 4858 4859 Result = APValue::IndeterminateValue(); 4860 return true; 4861 } 4862 4863 namespace { 4864 enum EvalStmtResult { 4865 /// Evaluation failed. 4866 ESR_Failed, 4867 /// Hit a 'return' statement. 4868 ESR_Returned, 4869 /// Evaluation succeeded. 4870 ESR_Succeeded, 4871 /// Hit a 'continue' statement. 4872 ESR_Continue, 4873 /// Hit a 'break' statement. 4874 ESR_Break, 4875 /// Still scanning for 'case' or 'default' statement. 4876 ESR_CaseNotFound 4877 }; 4878 } 4879 4880 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4881 if (VD->isInvalidDecl()) 4882 return false; 4883 // We don't need to evaluate the initializer for a static local. 4884 if (!VD->hasLocalStorage()) 4885 return true; 4886 4887 LValue Result; 4888 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4889 ScopeKind::Block, Result); 4890 4891 const Expr *InitE = VD->getInit(); 4892 if (!InitE) { 4893 if (VD->getType()->isDependentType()) 4894 return Info.noteSideEffect(); 4895 return getDefaultInitValue(VD->getType(), Val); 4896 } 4897 if (InitE->isValueDependent()) 4898 return false; 4899 4900 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4901 // Wipe out any partially-computed value, to allow tracking that this 4902 // evaluation failed. 4903 Val = APValue(); 4904 return false; 4905 } 4906 4907 return true; 4908 } 4909 4910 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4911 bool OK = true; 4912 4913 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4914 OK &= EvaluateVarDecl(Info, VD); 4915 4916 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4917 for (auto *BD : DD->bindings()) 4918 if (auto *VD = BD->getHoldingVar()) 4919 OK &= EvaluateDecl(Info, VD); 4920 4921 return OK; 4922 } 4923 4924 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4925 assert(E->isValueDependent()); 4926 if (Info.noteSideEffect()) 4927 return true; 4928 assert(E->containsErrors() && "valid value-dependent expression should never " 4929 "reach invalid code path."); 4930 return false; 4931 } 4932 4933 /// Evaluate a condition (either a variable declaration or an expression). 4934 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4935 const Expr *Cond, bool &Result) { 4936 if (Cond->isValueDependent()) 4937 return false; 4938 FullExpressionRAII Scope(Info); 4939 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4940 return false; 4941 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4942 return false; 4943 return Scope.destroy(); 4944 } 4945 4946 namespace { 4947 /// A location where the result (returned value) of evaluating a 4948 /// statement should be stored. 4949 struct StmtResult { 4950 /// The APValue that should be filled in with the returned value. 4951 APValue &Value; 4952 /// The location containing the result, if any (used to support RVO). 4953 const LValue *Slot; 4954 }; 4955 4956 struct TempVersionRAII { 4957 CallStackFrame &Frame; 4958 4959 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4960 Frame.pushTempVersion(); 4961 } 4962 4963 ~TempVersionRAII() { 4964 Frame.popTempVersion(); 4965 } 4966 }; 4967 4968 } 4969 4970 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4971 const Stmt *S, 4972 const SwitchCase *SC = nullptr); 4973 4974 /// Evaluate the body of a loop, and translate the result as appropriate. 4975 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4976 const Stmt *Body, 4977 const SwitchCase *Case = nullptr) { 4978 BlockScopeRAII Scope(Info); 4979 4980 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4981 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4982 ESR = ESR_Failed; 4983 4984 switch (ESR) { 4985 case ESR_Break: 4986 return ESR_Succeeded; 4987 case ESR_Succeeded: 4988 case ESR_Continue: 4989 return ESR_Continue; 4990 case ESR_Failed: 4991 case ESR_Returned: 4992 case ESR_CaseNotFound: 4993 return ESR; 4994 } 4995 llvm_unreachable("Invalid EvalStmtResult!"); 4996 } 4997 4998 /// Evaluate a switch statement. 4999 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 5000 const SwitchStmt *SS) { 5001 BlockScopeRAII Scope(Info); 5002 5003 // Evaluate the switch condition. 5004 APSInt Value; 5005 { 5006 if (const Stmt *Init = SS->getInit()) { 5007 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5008 if (ESR != ESR_Succeeded) { 5009 if (ESR != ESR_Failed && !Scope.destroy()) 5010 ESR = ESR_Failed; 5011 return ESR; 5012 } 5013 } 5014 5015 FullExpressionRAII CondScope(Info); 5016 if (SS->getConditionVariable() && 5017 !EvaluateDecl(Info, SS->getConditionVariable())) 5018 return ESR_Failed; 5019 if (SS->getCond()->isValueDependent()) { 5020 // We don't know what the value is, and which branch should jump to. 5021 EvaluateDependentExpr(SS->getCond(), Info); 5022 return ESR_Failed; 5023 } 5024 if (!EvaluateInteger(SS->getCond(), Value, Info)) 5025 return ESR_Failed; 5026 5027 if (!CondScope.destroy()) 5028 return ESR_Failed; 5029 } 5030 5031 // Find the switch case corresponding to the value of the condition. 5032 // FIXME: Cache this lookup. 5033 const SwitchCase *Found = nullptr; 5034 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 5035 SC = SC->getNextSwitchCase()) { 5036 if (isa<DefaultStmt>(SC)) { 5037 Found = SC; 5038 continue; 5039 } 5040 5041 const CaseStmt *CS = cast<CaseStmt>(SC); 5042 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 5043 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 5044 : LHS; 5045 if (LHS <= Value && Value <= RHS) { 5046 Found = SC; 5047 break; 5048 } 5049 } 5050 5051 if (!Found) 5052 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5053 5054 // Search the switch body for the switch case and evaluate it from there. 5055 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 5056 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 5057 return ESR_Failed; 5058 5059 switch (ESR) { 5060 case ESR_Break: 5061 return ESR_Succeeded; 5062 case ESR_Succeeded: 5063 case ESR_Continue: 5064 case ESR_Failed: 5065 case ESR_Returned: 5066 return ESR; 5067 case ESR_CaseNotFound: 5068 // This can only happen if the switch case is nested within a statement 5069 // expression. We have no intention of supporting that. 5070 Info.FFDiag(Found->getBeginLoc(), 5071 diag::note_constexpr_stmt_expr_unsupported); 5072 return ESR_Failed; 5073 } 5074 llvm_unreachable("Invalid EvalStmtResult!"); 5075 } 5076 5077 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { 5078 // An expression E is a core constant expression unless the evaluation of E 5079 // would evaluate one of the following: [C++23] - a control flow that passes 5080 // through a declaration of a variable with static or thread storage duration 5081 // unless that variable is usable in constant expressions. 5082 if (VD->isLocalVarDecl() && VD->isStaticLocal() && 5083 !VD->isUsableInConstantExpressions(Info.Ctx)) { 5084 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) 5085 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; 5086 return false; 5087 } 5088 return true; 5089 } 5090 5091 // Evaluate a statement. 5092 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5093 const Stmt *S, const SwitchCase *Case) { 5094 if (!Info.nextStep(S)) 5095 return ESR_Failed; 5096 5097 // If we're hunting down a 'case' or 'default' label, recurse through 5098 // substatements until we hit the label. 5099 if (Case) { 5100 switch (S->getStmtClass()) { 5101 case Stmt::CompoundStmtClass: 5102 // FIXME: Precompute which substatement of a compound statement we 5103 // would jump to, and go straight there rather than performing a 5104 // linear scan each time. 5105 case Stmt::LabelStmtClass: 5106 case Stmt::AttributedStmtClass: 5107 case Stmt::DoStmtClass: 5108 break; 5109 5110 case Stmt::CaseStmtClass: 5111 case Stmt::DefaultStmtClass: 5112 if (Case == S) 5113 Case = nullptr; 5114 break; 5115 5116 case Stmt::IfStmtClass: { 5117 // FIXME: Precompute which side of an 'if' we would jump to, and go 5118 // straight there rather than scanning both sides. 5119 const IfStmt *IS = cast<IfStmt>(S); 5120 5121 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5122 // preceded by our switch label. 5123 BlockScopeRAII Scope(Info); 5124 5125 // Step into the init statement in case it brings an (uninitialized) 5126 // variable into scope. 5127 if (const Stmt *Init = IS->getInit()) { 5128 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5129 if (ESR != ESR_CaseNotFound) { 5130 assert(ESR != ESR_Succeeded); 5131 return ESR; 5132 } 5133 } 5134 5135 // Condition variable must be initialized if it exists. 5136 // FIXME: We can skip evaluating the body if there's a condition 5137 // variable, as there can't be any case labels within it. 5138 // (The same is true for 'for' statements.) 5139 5140 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5141 if (ESR == ESR_Failed) 5142 return ESR; 5143 if (ESR != ESR_CaseNotFound) 5144 return Scope.destroy() ? ESR : ESR_Failed; 5145 if (!IS->getElse()) 5146 return ESR_CaseNotFound; 5147 5148 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5149 if (ESR == ESR_Failed) 5150 return ESR; 5151 if (ESR != ESR_CaseNotFound) 5152 return Scope.destroy() ? ESR : ESR_Failed; 5153 return ESR_CaseNotFound; 5154 } 5155 5156 case Stmt::WhileStmtClass: { 5157 EvalStmtResult ESR = 5158 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5159 if (ESR != ESR_Continue) 5160 return ESR; 5161 break; 5162 } 5163 5164 case Stmt::ForStmtClass: { 5165 const ForStmt *FS = cast<ForStmt>(S); 5166 BlockScopeRAII Scope(Info); 5167 5168 // Step into the init statement in case it brings an (uninitialized) 5169 // variable into scope. 5170 if (const Stmt *Init = FS->getInit()) { 5171 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5172 if (ESR != ESR_CaseNotFound) { 5173 assert(ESR != ESR_Succeeded); 5174 return ESR; 5175 } 5176 } 5177 5178 EvalStmtResult ESR = 5179 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5180 if (ESR != ESR_Continue) 5181 return ESR; 5182 if (const auto *Inc = FS->getInc()) { 5183 if (Inc->isValueDependent()) { 5184 if (!EvaluateDependentExpr(Inc, Info)) 5185 return ESR_Failed; 5186 } else { 5187 FullExpressionRAII IncScope(Info); 5188 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5189 return ESR_Failed; 5190 } 5191 } 5192 break; 5193 } 5194 5195 case Stmt::DeclStmtClass: { 5196 // Start the lifetime of any uninitialized variables we encounter. They 5197 // might be used by the selected branch of the switch. 5198 const DeclStmt *DS = cast<DeclStmt>(S); 5199 for (const auto *D : DS->decls()) { 5200 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5201 if (!CheckLocalVariableDeclaration(Info, VD)) 5202 return ESR_Failed; 5203 if (VD->hasLocalStorage() && !VD->getInit()) 5204 if (!EvaluateVarDecl(Info, VD)) 5205 return ESR_Failed; 5206 // FIXME: If the variable has initialization that can't be jumped 5207 // over, bail out of any immediately-surrounding compound-statement 5208 // too. There can't be any case labels here. 5209 } 5210 } 5211 return ESR_CaseNotFound; 5212 } 5213 5214 default: 5215 return ESR_CaseNotFound; 5216 } 5217 } 5218 5219 switch (S->getStmtClass()) { 5220 default: 5221 if (const Expr *E = dyn_cast<Expr>(S)) { 5222 if (E->isValueDependent()) { 5223 if (!EvaluateDependentExpr(E, Info)) 5224 return ESR_Failed; 5225 } else { 5226 // Don't bother evaluating beyond an expression-statement which couldn't 5227 // be evaluated. 5228 // FIXME: Do we need the FullExpressionRAII object here? 5229 // VisitExprWithCleanups should create one when necessary. 5230 FullExpressionRAII Scope(Info); 5231 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5232 return ESR_Failed; 5233 } 5234 return ESR_Succeeded; 5235 } 5236 5237 Info.FFDiag(S->getBeginLoc()); 5238 return ESR_Failed; 5239 5240 case Stmt::NullStmtClass: 5241 return ESR_Succeeded; 5242 5243 case Stmt::DeclStmtClass: { 5244 const DeclStmt *DS = cast<DeclStmt>(S); 5245 for (const auto *D : DS->decls()) { 5246 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 5247 if (VD && !CheckLocalVariableDeclaration(Info, VD)) 5248 return ESR_Failed; 5249 // Each declaration initialization is its own full-expression. 5250 FullExpressionRAII Scope(Info); 5251 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5252 return ESR_Failed; 5253 if (!Scope.destroy()) 5254 return ESR_Failed; 5255 } 5256 return ESR_Succeeded; 5257 } 5258 5259 case Stmt::ReturnStmtClass: { 5260 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5261 FullExpressionRAII Scope(Info); 5262 if (RetExpr && RetExpr->isValueDependent()) { 5263 EvaluateDependentExpr(RetExpr, Info); 5264 // We know we returned, but we don't know what the value is. 5265 return ESR_Failed; 5266 } 5267 if (RetExpr && 5268 !(Result.Slot 5269 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5270 : Evaluate(Result.Value, Info, RetExpr))) 5271 return ESR_Failed; 5272 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5273 } 5274 5275 case Stmt::CompoundStmtClass: { 5276 BlockScopeRAII Scope(Info); 5277 5278 const CompoundStmt *CS = cast<CompoundStmt>(S); 5279 for (const auto *BI : CS->body()) { 5280 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5281 if (ESR == ESR_Succeeded) 5282 Case = nullptr; 5283 else if (ESR != ESR_CaseNotFound) { 5284 if (ESR != ESR_Failed && !Scope.destroy()) 5285 return ESR_Failed; 5286 return ESR; 5287 } 5288 } 5289 if (Case) 5290 return ESR_CaseNotFound; 5291 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5292 } 5293 5294 case Stmt::IfStmtClass: { 5295 const IfStmt *IS = cast<IfStmt>(S); 5296 5297 // Evaluate the condition, as either a var decl or as an expression. 5298 BlockScopeRAII Scope(Info); 5299 if (const Stmt *Init = IS->getInit()) { 5300 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5301 if (ESR != ESR_Succeeded) { 5302 if (ESR != ESR_Failed && !Scope.destroy()) 5303 return ESR_Failed; 5304 return ESR; 5305 } 5306 } 5307 bool Cond; 5308 if (IS->isConsteval()) { 5309 Cond = IS->isNonNegatedConsteval(); 5310 // If we are not in a constant context, if consteval should not evaluate 5311 // to true. 5312 if (!Info.InConstantContext) 5313 Cond = !Cond; 5314 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5315 Cond)) 5316 return ESR_Failed; 5317 5318 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5319 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5320 if (ESR != ESR_Succeeded) { 5321 if (ESR != ESR_Failed && !Scope.destroy()) 5322 return ESR_Failed; 5323 return ESR; 5324 } 5325 } 5326 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5327 } 5328 5329 case Stmt::WhileStmtClass: { 5330 const WhileStmt *WS = cast<WhileStmt>(S); 5331 while (true) { 5332 BlockScopeRAII Scope(Info); 5333 bool Continue; 5334 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5335 Continue)) 5336 return ESR_Failed; 5337 if (!Continue) 5338 break; 5339 5340 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5341 if (ESR != ESR_Continue) { 5342 if (ESR != ESR_Failed && !Scope.destroy()) 5343 return ESR_Failed; 5344 return ESR; 5345 } 5346 if (!Scope.destroy()) 5347 return ESR_Failed; 5348 } 5349 return ESR_Succeeded; 5350 } 5351 5352 case Stmt::DoStmtClass: { 5353 const DoStmt *DS = cast<DoStmt>(S); 5354 bool Continue; 5355 do { 5356 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5357 if (ESR != ESR_Continue) 5358 return ESR; 5359 Case = nullptr; 5360 5361 if (DS->getCond()->isValueDependent()) { 5362 EvaluateDependentExpr(DS->getCond(), Info); 5363 // Bailout as we don't know whether to keep going or terminate the loop. 5364 return ESR_Failed; 5365 } 5366 FullExpressionRAII CondScope(Info); 5367 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5368 !CondScope.destroy()) 5369 return ESR_Failed; 5370 } while (Continue); 5371 return ESR_Succeeded; 5372 } 5373 5374 case Stmt::ForStmtClass: { 5375 const ForStmt *FS = cast<ForStmt>(S); 5376 BlockScopeRAII ForScope(Info); 5377 if (FS->getInit()) { 5378 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5379 if (ESR != ESR_Succeeded) { 5380 if (ESR != ESR_Failed && !ForScope.destroy()) 5381 return ESR_Failed; 5382 return ESR; 5383 } 5384 } 5385 while (true) { 5386 BlockScopeRAII IterScope(Info); 5387 bool Continue = true; 5388 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5389 FS->getCond(), Continue)) 5390 return ESR_Failed; 5391 if (!Continue) 5392 break; 5393 5394 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5395 if (ESR != ESR_Continue) { 5396 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5397 return ESR_Failed; 5398 return ESR; 5399 } 5400 5401 if (const auto *Inc = FS->getInc()) { 5402 if (Inc->isValueDependent()) { 5403 if (!EvaluateDependentExpr(Inc, Info)) 5404 return ESR_Failed; 5405 } else { 5406 FullExpressionRAII IncScope(Info); 5407 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5408 return ESR_Failed; 5409 } 5410 } 5411 5412 if (!IterScope.destroy()) 5413 return ESR_Failed; 5414 } 5415 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5416 } 5417 5418 case Stmt::CXXForRangeStmtClass: { 5419 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5420 BlockScopeRAII Scope(Info); 5421 5422 // Evaluate the init-statement if present. 5423 if (FS->getInit()) { 5424 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5425 if (ESR != ESR_Succeeded) { 5426 if (ESR != ESR_Failed && !Scope.destroy()) 5427 return ESR_Failed; 5428 return ESR; 5429 } 5430 } 5431 5432 // Initialize the __range variable. 5433 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5434 if (ESR != ESR_Succeeded) { 5435 if (ESR != ESR_Failed && !Scope.destroy()) 5436 return ESR_Failed; 5437 return ESR; 5438 } 5439 5440 // In error-recovery cases it's possible to get here even if we failed to 5441 // synthesize the __begin and __end variables. 5442 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5443 return ESR_Failed; 5444 5445 // Create the __begin and __end iterators. 5446 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5447 if (ESR != ESR_Succeeded) { 5448 if (ESR != ESR_Failed && !Scope.destroy()) 5449 return ESR_Failed; 5450 return ESR; 5451 } 5452 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5453 if (ESR != ESR_Succeeded) { 5454 if (ESR != ESR_Failed && !Scope.destroy()) 5455 return ESR_Failed; 5456 return ESR; 5457 } 5458 5459 while (true) { 5460 // Condition: __begin != __end. 5461 { 5462 if (FS->getCond()->isValueDependent()) { 5463 EvaluateDependentExpr(FS->getCond(), Info); 5464 // We don't know whether to keep going or terminate the loop. 5465 return ESR_Failed; 5466 } 5467 bool Continue = true; 5468 FullExpressionRAII CondExpr(Info); 5469 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5470 return ESR_Failed; 5471 if (!Continue) 5472 break; 5473 } 5474 5475 // User's variable declaration, initialized by *__begin. 5476 BlockScopeRAII InnerScope(Info); 5477 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5478 if (ESR != ESR_Succeeded) { 5479 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5480 return ESR_Failed; 5481 return ESR; 5482 } 5483 5484 // Loop body. 5485 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5486 if (ESR != ESR_Continue) { 5487 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5488 return ESR_Failed; 5489 return ESR; 5490 } 5491 if (FS->getInc()->isValueDependent()) { 5492 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5493 return ESR_Failed; 5494 } else { 5495 // Increment: ++__begin 5496 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5497 return ESR_Failed; 5498 } 5499 5500 if (!InnerScope.destroy()) 5501 return ESR_Failed; 5502 } 5503 5504 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5505 } 5506 5507 case Stmt::SwitchStmtClass: 5508 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5509 5510 case Stmt::ContinueStmtClass: 5511 return ESR_Continue; 5512 5513 case Stmt::BreakStmtClass: 5514 return ESR_Break; 5515 5516 case Stmt::LabelStmtClass: 5517 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5518 5519 case Stmt::AttributedStmtClass: 5520 // As a general principle, C++11 attributes can be ignored without 5521 // any semantic impact. 5522 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5523 Case); 5524 5525 case Stmt::CaseStmtClass: 5526 case Stmt::DefaultStmtClass: 5527 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5528 case Stmt::CXXTryStmtClass: 5529 // Evaluate try blocks by evaluating all sub statements. 5530 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5531 } 5532 } 5533 5534 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5535 /// default constructor. If so, we'll fold it whether or not it's marked as 5536 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5537 /// so we need special handling. 5538 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5539 const CXXConstructorDecl *CD, 5540 bool IsValueInitialization) { 5541 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5542 return false; 5543 5544 // Value-initialization does not call a trivial default constructor, so such a 5545 // call is a core constant expression whether or not the constructor is 5546 // constexpr. 5547 if (!CD->isConstexpr() && !IsValueInitialization) { 5548 if (Info.getLangOpts().CPlusPlus11) { 5549 // FIXME: If DiagDecl is an implicitly-declared special member function, 5550 // we should be much more explicit about why it's not constexpr. 5551 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5552 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5553 Info.Note(CD->getLocation(), diag::note_declared_at); 5554 } else { 5555 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5556 } 5557 } 5558 return true; 5559 } 5560 5561 /// CheckConstexprFunction - Check that a function can be called in a constant 5562 /// expression. 5563 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5564 const FunctionDecl *Declaration, 5565 const FunctionDecl *Definition, 5566 const Stmt *Body) { 5567 // Potential constant expressions can contain calls to declared, but not yet 5568 // defined, constexpr functions. 5569 if (Info.checkingPotentialConstantExpression() && !Definition && 5570 Declaration->isConstexpr()) 5571 return false; 5572 5573 // Bail out if the function declaration itself is invalid. We will 5574 // have produced a relevant diagnostic while parsing it, so just 5575 // note the problematic sub-expression. 5576 if (Declaration->isInvalidDecl()) { 5577 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5578 return false; 5579 } 5580 5581 // DR1872: An instantiated virtual constexpr function can't be called in a 5582 // constant expression (prior to C++20). We can still constant-fold such a 5583 // call. 5584 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5585 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5586 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5587 5588 if (Definition && Definition->isInvalidDecl()) { 5589 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5590 return false; 5591 } 5592 5593 // Can we evaluate this function call? 5594 if (Definition && Definition->isConstexpr() && Body) 5595 return true; 5596 5597 if (Info.getLangOpts().CPlusPlus11) { 5598 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5599 5600 // If this function is not constexpr because it is an inherited 5601 // non-constexpr constructor, diagnose that directly. 5602 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5603 if (CD && CD->isInheritingConstructor()) { 5604 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5605 if (!Inherited->isConstexpr()) 5606 DiagDecl = CD = Inherited; 5607 } 5608 5609 // FIXME: If DiagDecl is an implicitly-declared special member function 5610 // or an inheriting constructor, we should be much more explicit about why 5611 // it's not constexpr. 5612 if (CD && CD->isInheritingConstructor()) 5613 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5614 << CD->getInheritedConstructor().getConstructor()->getParent(); 5615 else 5616 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5617 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5618 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5619 } else { 5620 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5621 } 5622 return false; 5623 } 5624 5625 namespace { 5626 struct CheckDynamicTypeHandler { 5627 AccessKinds AccessKind; 5628 typedef bool result_type; 5629 bool failed() { return false; } 5630 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5631 bool found(APSInt &Value, QualType SubobjType) { return true; } 5632 bool found(APFloat &Value, QualType SubobjType) { return true; } 5633 }; 5634 } // end anonymous namespace 5635 5636 /// Check that we can access the notional vptr of an object / determine its 5637 /// dynamic type. 5638 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5639 AccessKinds AK, bool Polymorphic) { 5640 if (This.Designator.Invalid) 5641 return false; 5642 5643 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5644 5645 if (!Obj) 5646 return false; 5647 5648 if (!Obj.Value) { 5649 // The object is not usable in constant expressions, so we can't inspect 5650 // its value to see if it's in-lifetime or what the active union members 5651 // are. We can still check for a one-past-the-end lvalue. 5652 if (This.Designator.isOnePastTheEnd() || 5653 This.Designator.isMostDerivedAnUnsizedArray()) { 5654 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5655 ? diag::note_constexpr_access_past_end 5656 : diag::note_constexpr_access_unsized_array) 5657 << AK; 5658 return false; 5659 } else if (Polymorphic) { 5660 // Conservatively refuse to perform a polymorphic operation if we would 5661 // not be able to read a notional 'vptr' value. 5662 APValue Val; 5663 This.moveInto(Val); 5664 QualType StarThisType = 5665 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5666 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5667 << AK << Val.getAsString(Info.Ctx, StarThisType); 5668 return false; 5669 } 5670 return true; 5671 } 5672 5673 CheckDynamicTypeHandler Handler{AK}; 5674 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5675 } 5676 5677 /// Check that the pointee of the 'this' pointer in a member function call is 5678 /// either within its lifetime or in its period of construction or destruction. 5679 static bool 5680 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5681 const LValue &This, 5682 const CXXMethodDecl *NamedMember) { 5683 return checkDynamicType( 5684 Info, E, This, 5685 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5686 } 5687 5688 struct DynamicType { 5689 /// The dynamic class type of the object. 5690 const CXXRecordDecl *Type; 5691 /// The corresponding path length in the lvalue. 5692 unsigned PathLength; 5693 }; 5694 5695 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5696 unsigned PathLength) { 5697 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5698 Designator.Entries.size() && "invalid path length"); 5699 return (PathLength == Designator.MostDerivedPathLength) 5700 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5701 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5702 } 5703 5704 /// Determine the dynamic type of an object. 5705 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info, 5706 const Expr *E, 5707 LValue &This, 5708 AccessKinds AK) { 5709 // If we don't have an lvalue denoting an object of class type, there is no 5710 // meaningful dynamic type. (We consider objects of non-class type to have no 5711 // dynamic type.) 5712 if (!checkDynamicType(Info, E, This, AK, true)) 5713 return std::nullopt; 5714 5715 // Refuse to compute a dynamic type in the presence of virtual bases. This 5716 // shouldn't happen other than in constant-folding situations, since literal 5717 // types can't have virtual bases. 5718 // 5719 // Note that consumers of DynamicType assume that the type has no virtual 5720 // bases, and will need modifications if this restriction is relaxed. 5721 const CXXRecordDecl *Class = 5722 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5723 if (!Class || Class->getNumVBases()) { 5724 Info.FFDiag(E); 5725 return std::nullopt; 5726 } 5727 5728 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5729 // binary search here instead. But the overwhelmingly common case is that 5730 // we're not in the middle of a constructor, so it probably doesn't matter 5731 // in practice. 5732 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5733 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5734 PathLength <= Path.size(); ++PathLength) { 5735 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5736 Path.slice(0, PathLength))) { 5737 case ConstructionPhase::Bases: 5738 case ConstructionPhase::DestroyingBases: 5739 // We're constructing or destroying a base class. This is not the dynamic 5740 // type. 5741 break; 5742 5743 case ConstructionPhase::None: 5744 case ConstructionPhase::AfterBases: 5745 case ConstructionPhase::AfterFields: 5746 case ConstructionPhase::Destroying: 5747 // We've finished constructing the base classes and not yet started 5748 // destroying them again, so this is the dynamic type. 5749 return DynamicType{getBaseClassType(This.Designator, PathLength), 5750 PathLength}; 5751 } 5752 } 5753 5754 // CWG issue 1517: we're constructing a base class of the object described by 5755 // 'This', so that object has not yet begun its period of construction and 5756 // any polymorphic operation on it results in undefined behavior. 5757 Info.FFDiag(E); 5758 return std::nullopt; 5759 } 5760 5761 /// Perform virtual dispatch. 5762 static const CXXMethodDecl *HandleVirtualDispatch( 5763 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5764 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5765 std::optional<DynamicType> DynType = ComputeDynamicType( 5766 Info, E, This, 5767 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5768 if (!DynType) 5769 return nullptr; 5770 5771 // Find the final overrider. It must be declared in one of the classes on the 5772 // path from the dynamic type to the static type. 5773 // FIXME: If we ever allow literal types to have virtual base classes, that 5774 // won't be true. 5775 const CXXMethodDecl *Callee = Found; 5776 unsigned PathLength = DynType->PathLength; 5777 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5778 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5779 const CXXMethodDecl *Overrider = 5780 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5781 if (Overrider) { 5782 Callee = Overrider; 5783 break; 5784 } 5785 } 5786 5787 // C++2a [class.abstract]p6: 5788 // the effect of making a virtual call to a pure virtual function [...] is 5789 // undefined 5790 if (Callee->isPure()) { 5791 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5792 Info.Note(Callee->getLocation(), diag::note_declared_at); 5793 return nullptr; 5794 } 5795 5796 // If necessary, walk the rest of the path to determine the sequence of 5797 // covariant adjustment steps to apply. 5798 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5799 Found->getReturnType())) { 5800 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5801 for (unsigned CovariantPathLength = PathLength + 1; 5802 CovariantPathLength != This.Designator.Entries.size(); 5803 ++CovariantPathLength) { 5804 const CXXRecordDecl *NextClass = 5805 getBaseClassType(This.Designator, CovariantPathLength); 5806 const CXXMethodDecl *Next = 5807 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5808 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5809 Next->getReturnType(), CovariantAdjustmentPath.back())) 5810 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5811 } 5812 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5813 CovariantAdjustmentPath.back())) 5814 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5815 } 5816 5817 // Perform 'this' adjustment. 5818 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5819 return nullptr; 5820 5821 return Callee; 5822 } 5823 5824 /// Perform the adjustment from a value returned by a virtual function to 5825 /// a value of the statically expected type, which may be a pointer or 5826 /// reference to a base class of the returned type. 5827 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5828 APValue &Result, 5829 ArrayRef<QualType> Path) { 5830 assert(Result.isLValue() && 5831 "unexpected kind of APValue for covariant return"); 5832 if (Result.isNullPointer()) 5833 return true; 5834 5835 LValue LVal; 5836 LVal.setFrom(Info.Ctx, Result); 5837 5838 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5839 for (unsigned I = 1; I != Path.size(); ++I) { 5840 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5841 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5842 if (OldClass != NewClass && 5843 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5844 return false; 5845 OldClass = NewClass; 5846 } 5847 5848 LVal.moveInto(Result); 5849 return true; 5850 } 5851 5852 /// Determine whether \p Base, which is known to be a direct base class of 5853 /// \p Derived, is a public base class. 5854 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5855 const CXXRecordDecl *Base) { 5856 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5857 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5858 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5859 return BaseSpec.getAccessSpecifier() == AS_public; 5860 } 5861 llvm_unreachable("Base is not a direct base of Derived"); 5862 } 5863 5864 /// Apply the given dynamic cast operation on the provided lvalue. 5865 /// 5866 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5867 /// to find a suitable target subobject. 5868 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5869 LValue &Ptr) { 5870 // We can't do anything with a non-symbolic pointer value. 5871 SubobjectDesignator &D = Ptr.Designator; 5872 if (D.Invalid) 5873 return false; 5874 5875 // C++ [expr.dynamic.cast]p6: 5876 // If v is a null pointer value, the result is a null pointer value. 5877 if (Ptr.isNullPointer() && !E->isGLValue()) 5878 return true; 5879 5880 // For all the other cases, we need the pointer to point to an object within 5881 // its lifetime / period of construction / destruction, and we need to know 5882 // its dynamic type. 5883 std::optional<DynamicType> DynType = 5884 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5885 if (!DynType) 5886 return false; 5887 5888 // C++ [expr.dynamic.cast]p7: 5889 // If T is "pointer to cv void", then the result is a pointer to the most 5890 // derived object 5891 if (E->getType()->isVoidPointerType()) 5892 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5893 5894 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5895 assert(C && "dynamic_cast target is not void pointer nor class"); 5896 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5897 5898 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5899 // C++ [expr.dynamic.cast]p9: 5900 if (!E->isGLValue()) { 5901 // The value of a failed cast to pointer type is the null pointer value 5902 // of the required result type. 5903 Ptr.setNull(Info.Ctx, E->getType()); 5904 return true; 5905 } 5906 5907 // A failed cast to reference type throws [...] std::bad_cast. 5908 unsigned DiagKind; 5909 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5910 DynType->Type->isDerivedFrom(C))) 5911 DiagKind = 0; 5912 else if (!Paths || Paths->begin() == Paths->end()) 5913 DiagKind = 1; 5914 else if (Paths->isAmbiguous(CQT)) 5915 DiagKind = 2; 5916 else { 5917 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5918 DiagKind = 3; 5919 } 5920 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5921 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5922 << Info.Ctx.getRecordType(DynType->Type) 5923 << E->getType().getUnqualifiedType(); 5924 return false; 5925 }; 5926 5927 // Runtime check, phase 1: 5928 // Walk from the base subobject towards the derived object looking for the 5929 // target type. 5930 for (int PathLength = Ptr.Designator.Entries.size(); 5931 PathLength >= (int)DynType->PathLength; --PathLength) { 5932 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5933 if (declaresSameEntity(Class, C)) 5934 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5935 // We can only walk across public inheritance edges. 5936 if (PathLength > (int)DynType->PathLength && 5937 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5938 Class)) 5939 return RuntimeCheckFailed(nullptr); 5940 } 5941 5942 // Runtime check, phase 2: 5943 // Search the dynamic type for an unambiguous public base of type C. 5944 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5945 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5946 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5947 Paths.front().Access == AS_public) { 5948 // Downcast to the dynamic type... 5949 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5950 return false; 5951 // ... then upcast to the chosen base class subobject. 5952 for (CXXBasePathElement &Elem : Paths.front()) 5953 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5954 return false; 5955 return true; 5956 } 5957 5958 // Otherwise, the runtime check fails. 5959 return RuntimeCheckFailed(&Paths); 5960 } 5961 5962 namespace { 5963 struct StartLifetimeOfUnionMemberHandler { 5964 EvalInfo &Info; 5965 const Expr *LHSExpr; 5966 const FieldDecl *Field; 5967 bool DuringInit; 5968 bool Failed = false; 5969 static const AccessKinds AccessKind = AK_Assign; 5970 5971 typedef bool result_type; 5972 bool failed() { return Failed; } 5973 bool found(APValue &Subobj, QualType SubobjType) { 5974 // We are supposed to perform no initialization but begin the lifetime of 5975 // the object. We interpret that as meaning to do what default 5976 // initialization of the object would do if all constructors involved were 5977 // trivial: 5978 // * All base, non-variant member, and array element subobjects' lifetimes 5979 // begin 5980 // * No variant members' lifetimes begin 5981 // * All scalar subobjects whose lifetimes begin have indeterminate values 5982 assert(SubobjType->isUnionType()); 5983 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5984 // This union member is already active. If it's also in-lifetime, there's 5985 // nothing to do. 5986 if (Subobj.getUnionValue().hasValue()) 5987 return true; 5988 } else if (DuringInit) { 5989 // We're currently in the process of initializing a different union 5990 // member. If we carried on, that initialization would attempt to 5991 // store to an inactive union member, resulting in undefined behavior. 5992 Info.FFDiag(LHSExpr, 5993 diag::note_constexpr_union_member_change_during_init); 5994 return false; 5995 } 5996 APValue Result; 5997 Failed = !getDefaultInitValue(Field->getType(), Result); 5998 Subobj.setUnion(Field, Result); 5999 return true; 6000 } 6001 bool found(APSInt &Value, QualType SubobjType) { 6002 llvm_unreachable("wrong value kind for union object"); 6003 } 6004 bool found(APFloat &Value, QualType SubobjType) { 6005 llvm_unreachable("wrong value kind for union object"); 6006 } 6007 }; 6008 } // end anonymous namespace 6009 6010 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 6011 6012 /// Handle a builtin simple-assignment or a call to a trivial assignment 6013 /// operator whose left-hand side might involve a union member access. If it 6014 /// does, implicitly start the lifetime of any accessed union elements per 6015 /// C++20 [class.union]5. 6016 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, 6017 const Expr *LHSExpr, 6018 const LValue &LHS) { 6019 if (LHS.InvalidBase || LHS.Designator.Invalid) 6020 return false; 6021 6022 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 6023 // C++ [class.union]p5: 6024 // define the set S(E) of subexpressions of E as follows: 6025 unsigned PathLength = LHS.Designator.Entries.size(); 6026 for (const Expr *E = LHSExpr; E != nullptr;) { 6027 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 6028 if (auto *ME = dyn_cast<MemberExpr>(E)) { 6029 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 6030 // Note that we can't implicitly start the lifetime of a reference, 6031 // so we don't need to proceed any further if we reach one. 6032 if (!FD || FD->getType()->isReferenceType()) 6033 break; 6034 6035 // ... and also contains A.B if B names a union member ... 6036 if (FD->getParent()->isUnion()) { 6037 // ... of a non-class, non-array type, or of a class type with a 6038 // trivial default constructor that is not deleted, or an array of 6039 // such types. 6040 auto *RD = 6041 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 6042 if (!RD || RD->hasTrivialDefaultConstructor()) 6043 UnionPathLengths.push_back({PathLength - 1, FD}); 6044 } 6045 6046 E = ME->getBase(); 6047 --PathLength; 6048 assert(declaresSameEntity(FD, 6049 LHS.Designator.Entries[PathLength] 6050 .getAsBaseOrMember().getPointer())); 6051 6052 // -- If E is of the form A[B] and is interpreted as a built-in array 6053 // subscripting operator, S(E) is [S(the array operand, if any)]. 6054 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 6055 // Step over an ArrayToPointerDecay implicit cast. 6056 auto *Base = ASE->getBase()->IgnoreImplicit(); 6057 if (!Base->getType()->isArrayType()) 6058 break; 6059 6060 E = Base; 6061 --PathLength; 6062 6063 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6064 // Step over a derived-to-base conversion. 6065 E = ICE->getSubExpr(); 6066 if (ICE->getCastKind() == CK_NoOp) 6067 continue; 6068 if (ICE->getCastKind() != CK_DerivedToBase && 6069 ICE->getCastKind() != CK_UncheckedDerivedToBase) 6070 break; 6071 // Walk path backwards as we walk up from the base to the derived class. 6072 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 6073 if (Elt->isVirtual()) { 6074 // A class with virtual base classes never has a trivial default 6075 // constructor, so S(E) is empty in this case. 6076 E = nullptr; 6077 break; 6078 } 6079 6080 --PathLength; 6081 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 6082 LHS.Designator.Entries[PathLength] 6083 .getAsBaseOrMember().getPointer())); 6084 } 6085 6086 // -- Otherwise, S(E) is empty. 6087 } else { 6088 break; 6089 } 6090 } 6091 6092 // Common case: no unions' lifetimes are started. 6093 if (UnionPathLengths.empty()) 6094 return true; 6095 6096 // if modification of X [would access an inactive union member], an object 6097 // of the type of X is implicitly created 6098 CompleteObject Obj = 6099 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 6100 if (!Obj) 6101 return false; 6102 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6103 llvm::reverse(UnionPathLengths)) { 6104 // Form a designator for the union object. 6105 SubobjectDesignator D = LHS.Designator; 6106 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6107 6108 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6109 ConstructionPhase::AfterBases; 6110 StartLifetimeOfUnionMemberHandler StartLifetime{ 6111 Info, LHSExpr, LengthAndField.second, DuringInit}; 6112 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6113 return false; 6114 } 6115 6116 return true; 6117 } 6118 6119 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6120 CallRef Call, EvalInfo &Info, 6121 bool NonNull = false) { 6122 LValue LV; 6123 // Create the parameter slot and register its destruction. For a vararg 6124 // argument, create a temporary. 6125 // FIXME: For calling conventions that destroy parameters in the callee, 6126 // should we consider performing destruction when the function returns 6127 // instead? 6128 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6129 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6130 ScopeKind::Call, LV); 6131 if (!EvaluateInPlace(V, Info, LV, Arg)) 6132 return false; 6133 6134 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6135 // undefined behavior, so is non-constant. 6136 if (NonNull && V.isLValue() && V.isNullPointer()) { 6137 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6138 return false; 6139 } 6140 6141 return true; 6142 } 6143 6144 /// Evaluate the arguments to a function call. 6145 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6146 EvalInfo &Info, const FunctionDecl *Callee, 6147 bool RightToLeft = false) { 6148 bool Success = true; 6149 llvm::SmallBitVector ForbiddenNullArgs; 6150 if (Callee->hasAttr<NonNullAttr>()) { 6151 ForbiddenNullArgs.resize(Args.size()); 6152 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6153 if (!Attr->args_size()) { 6154 ForbiddenNullArgs.set(); 6155 break; 6156 } else 6157 for (auto Idx : Attr->args()) { 6158 unsigned ASTIdx = Idx.getASTIndex(); 6159 if (ASTIdx >= Args.size()) 6160 continue; 6161 ForbiddenNullArgs[ASTIdx] = true; 6162 } 6163 } 6164 } 6165 for (unsigned I = 0; I < Args.size(); I++) { 6166 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6167 const ParmVarDecl *PVD = 6168 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6169 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6170 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6171 // If we're checking for a potential constant expression, evaluate all 6172 // initializers even if some of them fail. 6173 if (!Info.noteFailure()) 6174 return false; 6175 Success = false; 6176 } 6177 } 6178 return Success; 6179 } 6180 6181 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6182 /// constructor or assignment operator. 6183 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6184 const Expr *E, APValue &Result, 6185 bool CopyObjectRepresentation) { 6186 // Find the reference argument. 6187 CallStackFrame *Frame = Info.CurrentCall; 6188 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6189 if (!RefValue) { 6190 Info.FFDiag(E); 6191 return false; 6192 } 6193 6194 // Copy out the contents of the RHS object. 6195 LValue RefLValue; 6196 RefLValue.setFrom(Info.Ctx, *RefValue); 6197 return handleLValueToRValueConversion( 6198 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6199 CopyObjectRepresentation); 6200 } 6201 6202 /// Evaluate a function call. 6203 static bool HandleFunctionCall(SourceLocation CallLoc, 6204 const FunctionDecl *Callee, const LValue *This, 6205 const Expr *E, ArrayRef<const Expr *> Args, 6206 CallRef Call, const Stmt *Body, EvalInfo &Info, 6207 APValue &Result, const LValue *ResultSlot) { 6208 if (!Info.CheckCallLimit(CallLoc)) 6209 return false; 6210 6211 CallStackFrame Frame(Info, CallLoc, Callee, This, E, Call); 6212 6213 // For a trivial copy or move assignment, perform an APValue copy. This is 6214 // essential for unions, where the operations performed by the assignment 6215 // operator cannot be represented as statements. 6216 // 6217 // Skip this for non-union classes with no fields; in that case, the defaulted 6218 // copy/move does not actually read the object. 6219 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6220 if (MD && MD->isDefaulted() && 6221 (MD->getParent()->isUnion() || 6222 (MD->isTrivial() && 6223 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6224 assert(This && 6225 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6226 APValue RHSValue; 6227 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6228 MD->getParent()->isUnion())) 6229 return false; 6230 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6231 RHSValue)) 6232 return false; 6233 This->moveInto(Result); 6234 return true; 6235 } else if (MD && isLambdaCallOperator(MD)) { 6236 // We're in a lambda; determine the lambda capture field maps unless we're 6237 // just constexpr checking a lambda's call operator. constexpr checking is 6238 // done before the captures have been added to the closure object (unless 6239 // we're inferring constexpr-ness), so we don't have access to them in this 6240 // case. But since we don't need the captures to constexpr check, we can 6241 // just ignore them. 6242 if (!Info.checkingPotentialConstantExpression()) 6243 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6244 Frame.LambdaThisCaptureField); 6245 } 6246 6247 StmtResult Ret = {Result, ResultSlot}; 6248 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6249 if (ESR == ESR_Succeeded) { 6250 if (Callee->getReturnType()->isVoidType()) 6251 return true; 6252 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6253 } 6254 return ESR == ESR_Returned; 6255 } 6256 6257 /// Evaluate a constructor call. 6258 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6259 CallRef Call, 6260 const CXXConstructorDecl *Definition, 6261 EvalInfo &Info, APValue &Result) { 6262 SourceLocation CallLoc = E->getExprLoc(); 6263 if (!Info.CheckCallLimit(CallLoc)) 6264 return false; 6265 6266 const CXXRecordDecl *RD = Definition->getParent(); 6267 if (RD->getNumVBases()) { 6268 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6269 return false; 6270 } 6271 6272 EvalInfo::EvaluatingConstructorRAII EvalObj( 6273 Info, 6274 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6275 RD->getNumBases()); 6276 CallStackFrame Frame(Info, CallLoc, Definition, &This, E, Call); 6277 6278 // FIXME: Creating an APValue just to hold a nonexistent return value is 6279 // wasteful. 6280 APValue RetVal; 6281 StmtResult Ret = {RetVal, nullptr}; 6282 6283 // If it's a delegating constructor, delegate. 6284 if (Definition->isDelegatingConstructor()) { 6285 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6286 if ((*I)->getInit()->isValueDependent()) { 6287 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6288 return false; 6289 } else { 6290 FullExpressionRAII InitScope(Info); 6291 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6292 !InitScope.destroy()) 6293 return false; 6294 } 6295 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6296 } 6297 6298 // For a trivial copy or move constructor, perform an APValue copy. This is 6299 // essential for unions (or classes with anonymous union members), where the 6300 // operations performed by the constructor cannot be represented by 6301 // ctor-initializers. 6302 // 6303 // Skip this for empty non-union classes; we should not perform an 6304 // lvalue-to-rvalue conversion on them because their copy constructor does not 6305 // actually read them. 6306 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6307 (Definition->getParent()->isUnion() || 6308 (Definition->isTrivial() && 6309 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6310 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6311 Definition->getParent()->isUnion()); 6312 } 6313 6314 // Reserve space for the struct members. 6315 if (!Result.hasValue()) { 6316 if (!RD->isUnion()) 6317 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6318 std::distance(RD->field_begin(), RD->field_end())); 6319 else 6320 // A union starts with no active member. 6321 Result = APValue((const FieldDecl*)nullptr); 6322 } 6323 6324 if (RD->isInvalidDecl()) return false; 6325 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6326 6327 // A scope for temporaries lifetime-extended by reference members. 6328 BlockScopeRAII LifetimeExtendedScope(Info); 6329 6330 bool Success = true; 6331 unsigned BasesSeen = 0; 6332 #ifndef NDEBUG 6333 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6334 #endif 6335 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6336 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6337 // We might be initializing the same field again if this is an indirect 6338 // field initialization. 6339 if (FieldIt == RD->field_end() || 6340 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6341 assert(Indirect && "fields out of order?"); 6342 return; 6343 } 6344 6345 // Default-initialize any fields with no explicit initializer. 6346 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6347 assert(FieldIt != RD->field_end() && "missing field?"); 6348 if (!FieldIt->isUnnamedBitfield()) 6349 Success &= getDefaultInitValue( 6350 FieldIt->getType(), 6351 Result.getStructField(FieldIt->getFieldIndex())); 6352 } 6353 ++FieldIt; 6354 }; 6355 for (const auto *I : Definition->inits()) { 6356 LValue Subobject = This; 6357 LValue SubobjectParent = This; 6358 APValue *Value = &Result; 6359 6360 // Determine the subobject to initialize. 6361 FieldDecl *FD = nullptr; 6362 if (I->isBaseInitializer()) { 6363 QualType BaseType(I->getBaseClass(), 0); 6364 #ifndef NDEBUG 6365 // Non-virtual base classes are initialized in the order in the class 6366 // definition. We have already checked for virtual base classes. 6367 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6368 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6369 "base class initializers not in expected order"); 6370 ++BaseIt; 6371 #endif 6372 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6373 BaseType->getAsCXXRecordDecl(), &Layout)) 6374 return false; 6375 Value = &Result.getStructBase(BasesSeen++); 6376 } else if ((FD = I->getMember())) { 6377 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6378 return false; 6379 if (RD->isUnion()) { 6380 Result = APValue(FD); 6381 Value = &Result.getUnionValue(); 6382 } else { 6383 SkipToField(FD, false); 6384 Value = &Result.getStructField(FD->getFieldIndex()); 6385 } 6386 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6387 // Walk the indirect field decl's chain to find the object to initialize, 6388 // and make sure we've initialized every step along it. 6389 auto IndirectFieldChain = IFD->chain(); 6390 for (auto *C : IndirectFieldChain) { 6391 FD = cast<FieldDecl>(C); 6392 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6393 // Switch the union field if it differs. This happens if we had 6394 // preceding zero-initialization, and we're now initializing a union 6395 // subobject other than the first. 6396 // FIXME: In this case, the values of the other subobjects are 6397 // specified, since zero-initialization sets all padding bits to zero. 6398 if (!Value->hasValue() || 6399 (Value->isUnion() && Value->getUnionField() != FD)) { 6400 if (CD->isUnion()) 6401 *Value = APValue(FD); 6402 else 6403 // FIXME: This immediately starts the lifetime of all members of 6404 // an anonymous struct. It would be preferable to strictly start 6405 // member lifetime in initialization order. 6406 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6407 } 6408 // Store Subobject as its parent before updating it for the last element 6409 // in the chain. 6410 if (C == IndirectFieldChain.back()) 6411 SubobjectParent = Subobject; 6412 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6413 return false; 6414 if (CD->isUnion()) 6415 Value = &Value->getUnionValue(); 6416 else { 6417 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6418 SkipToField(FD, true); 6419 Value = &Value->getStructField(FD->getFieldIndex()); 6420 } 6421 } 6422 } else { 6423 llvm_unreachable("unknown base initializer kind"); 6424 } 6425 6426 // Need to override This for implicit field initializers as in this case 6427 // This refers to innermost anonymous struct/union containing initializer, 6428 // not to currently constructed class. 6429 const Expr *Init = I->getInit(); 6430 if (Init->isValueDependent()) { 6431 if (!EvaluateDependentExpr(Init, Info)) 6432 return false; 6433 } else { 6434 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6435 isa<CXXDefaultInitExpr>(Init)); 6436 FullExpressionRAII InitScope(Info); 6437 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6438 (FD && FD->isBitField() && 6439 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6440 // If we're checking for a potential constant expression, evaluate all 6441 // initializers even if some of them fail. 6442 if (!Info.noteFailure()) 6443 return false; 6444 Success = false; 6445 } 6446 } 6447 6448 // This is the point at which the dynamic type of the object becomes this 6449 // class type. 6450 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6451 EvalObj.finishedConstructingBases(); 6452 } 6453 6454 // Default-initialize any remaining fields. 6455 if (!RD->isUnion()) { 6456 for (; FieldIt != RD->field_end(); ++FieldIt) { 6457 if (!FieldIt->isUnnamedBitfield()) 6458 Success &= getDefaultInitValue( 6459 FieldIt->getType(), 6460 Result.getStructField(FieldIt->getFieldIndex())); 6461 } 6462 } 6463 6464 EvalObj.finishedConstructingFields(); 6465 6466 return Success && 6467 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6468 LifetimeExtendedScope.destroy(); 6469 } 6470 6471 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6472 ArrayRef<const Expr*> Args, 6473 const CXXConstructorDecl *Definition, 6474 EvalInfo &Info, APValue &Result) { 6475 CallScopeRAII CallScope(Info); 6476 CallRef Call = Info.CurrentCall->createCall(Definition); 6477 if (!EvaluateArgs(Args, Call, Info, Definition)) 6478 return false; 6479 6480 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6481 CallScope.destroy(); 6482 } 6483 6484 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6485 const LValue &This, APValue &Value, 6486 QualType T) { 6487 // Objects can only be destroyed while they're within their lifetimes. 6488 // FIXME: We have no representation for whether an object of type nullptr_t 6489 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6490 // as indeterminate instead? 6491 if (Value.isAbsent() && !T->isNullPtrType()) { 6492 APValue Printable; 6493 This.moveInto(Printable); 6494 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6495 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6496 return false; 6497 } 6498 6499 // Invent an expression for location purposes. 6500 // FIXME: We shouldn't need to do this. 6501 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6502 6503 // For arrays, destroy elements right-to-left. 6504 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6505 uint64_t Size = CAT->getSize().getZExtValue(); 6506 QualType ElemT = CAT->getElementType(); 6507 6508 LValue ElemLV = This; 6509 ElemLV.addArray(Info, &LocE, CAT); 6510 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6511 return false; 6512 6513 // Ensure that we have actual array elements available to destroy; the 6514 // destructors might mutate the value, so we can't run them on the array 6515 // filler. 6516 if (Size && Size > Value.getArrayInitializedElts()) 6517 expandArray(Value, Value.getArraySize() - 1); 6518 6519 for (; Size != 0; --Size) { 6520 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6521 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6522 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6523 return false; 6524 } 6525 6526 // End the lifetime of this array now. 6527 Value = APValue(); 6528 return true; 6529 } 6530 6531 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6532 if (!RD) { 6533 if (T.isDestructedType()) { 6534 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6535 return false; 6536 } 6537 6538 Value = APValue(); 6539 return true; 6540 } 6541 6542 if (RD->getNumVBases()) { 6543 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6544 return false; 6545 } 6546 6547 const CXXDestructorDecl *DD = RD->getDestructor(); 6548 if (!DD && !RD->hasTrivialDestructor()) { 6549 Info.FFDiag(CallLoc); 6550 return false; 6551 } 6552 6553 if (!DD || DD->isTrivial() || 6554 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6555 // A trivial destructor just ends the lifetime of the object. Check for 6556 // this case before checking for a body, because we might not bother 6557 // building a body for a trivial destructor. Note that it doesn't matter 6558 // whether the destructor is constexpr in this case; all trivial 6559 // destructors are constexpr. 6560 // 6561 // If an anonymous union would be destroyed, some enclosing destructor must 6562 // have been explicitly defined, and the anonymous union destruction should 6563 // have no effect. 6564 Value = APValue(); 6565 return true; 6566 } 6567 6568 if (!Info.CheckCallLimit(CallLoc)) 6569 return false; 6570 6571 const FunctionDecl *Definition = nullptr; 6572 const Stmt *Body = DD->getBody(Definition); 6573 6574 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6575 return false; 6576 6577 CallStackFrame Frame(Info, CallLoc, Definition, &This, /*CallExpr=*/nullptr, 6578 CallRef()); 6579 6580 // We're now in the period of destruction of this object. 6581 unsigned BasesLeft = RD->getNumBases(); 6582 EvalInfo::EvaluatingDestructorRAII EvalObj( 6583 Info, 6584 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6585 if (!EvalObj.DidInsert) { 6586 // C++2a [class.dtor]p19: 6587 // the behavior is undefined if the destructor is invoked for an object 6588 // whose lifetime has ended 6589 // (Note that formally the lifetime ends when the period of destruction 6590 // begins, even though certain uses of the object remain valid until the 6591 // period of destruction ends.) 6592 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6593 return false; 6594 } 6595 6596 // FIXME: Creating an APValue just to hold a nonexistent return value is 6597 // wasteful. 6598 APValue RetVal; 6599 StmtResult Ret = {RetVal, nullptr}; 6600 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6601 return false; 6602 6603 // A union destructor does not implicitly destroy its members. 6604 if (RD->isUnion()) 6605 return true; 6606 6607 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6608 6609 // We don't have a good way to iterate fields in reverse, so collect all the 6610 // fields first and then walk them backwards. 6611 SmallVector<FieldDecl*, 16> Fields(RD->fields()); 6612 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6613 if (FD->isUnnamedBitfield()) 6614 continue; 6615 6616 LValue Subobject = This; 6617 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6618 return false; 6619 6620 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6621 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6622 FD->getType())) 6623 return false; 6624 } 6625 6626 if (BasesLeft != 0) 6627 EvalObj.startedDestroyingBases(); 6628 6629 // Destroy base classes in reverse order. 6630 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6631 --BasesLeft; 6632 6633 QualType BaseType = Base.getType(); 6634 LValue Subobject = This; 6635 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6636 BaseType->getAsCXXRecordDecl(), &Layout)) 6637 return false; 6638 6639 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6640 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6641 BaseType)) 6642 return false; 6643 } 6644 assert(BasesLeft == 0 && "NumBases was wrong?"); 6645 6646 // The period of destruction ends now. The object is gone. 6647 Value = APValue(); 6648 return true; 6649 } 6650 6651 namespace { 6652 struct DestroyObjectHandler { 6653 EvalInfo &Info; 6654 const Expr *E; 6655 const LValue &This; 6656 const AccessKinds AccessKind; 6657 6658 typedef bool result_type; 6659 bool failed() { return false; } 6660 bool found(APValue &Subobj, QualType SubobjType) { 6661 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6662 SubobjType); 6663 } 6664 bool found(APSInt &Value, QualType SubobjType) { 6665 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6666 return false; 6667 } 6668 bool found(APFloat &Value, QualType SubobjType) { 6669 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6670 return false; 6671 } 6672 }; 6673 } 6674 6675 /// Perform a destructor or pseudo-destructor call on the given object, which 6676 /// might in general not be a complete object. 6677 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6678 const LValue &This, QualType ThisType) { 6679 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6680 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6681 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6682 } 6683 6684 /// Destroy and end the lifetime of the given complete object. 6685 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6686 APValue::LValueBase LVBase, APValue &Value, 6687 QualType T) { 6688 // If we've had an unmodeled side-effect, we can't rely on mutable state 6689 // (such as the object we're about to destroy) being correct. 6690 if (Info.EvalStatus.HasSideEffects) 6691 return false; 6692 6693 LValue LV; 6694 LV.set({LVBase}); 6695 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6696 } 6697 6698 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6699 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6700 LValue &Result) { 6701 if (Info.checkingPotentialConstantExpression() || 6702 Info.SpeculativeEvaluationDepth) 6703 return false; 6704 6705 // This is permitted only within a call to std::allocator<T>::allocate. 6706 auto Caller = Info.getStdAllocatorCaller("allocate"); 6707 if (!Caller) { 6708 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6709 ? diag::note_constexpr_new_untyped 6710 : diag::note_constexpr_new); 6711 return false; 6712 } 6713 6714 QualType ElemType = Caller.ElemType; 6715 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6716 Info.FFDiag(E->getExprLoc(), 6717 diag::note_constexpr_new_not_complete_object_type) 6718 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6719 return false; 6720 } 6721 6722 APSInt ByteSize; 6723 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6724 return false; 6725 bool IsNothrow = false; 6726 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6727 EvaluateIgnoredValue(Info, E->getArg(I)); 6728 IsNothrow |= E->getType()->isNothrowT(); 6729 } 6730 6731 CharUnits ElemSize; 6732 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6733 return false; 6734 APInt Size, Remainder; 6735 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6736 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6737 if (Remainder != 0) { 6738 // This likely indicates a bug in the implementation of 'std::allocator'. 6739 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6740 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6741 return false; 6742 } 6743 6744 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6745 if (IsNothrow) { 6746 Result.setNull(Info.Ctx, E->getType()); 6747 return true; 6748 } 6749 6750 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6751 return false; 6752 } 6753 6754 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6755 ArrayType::Normal, 0); 6756 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6757 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6758 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6759 return true; 6760 } 6761 6762 static bool hasVirtualDestructor(QualType T) { 6763 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6764 if (CXXDestructorDecl *DD = RD->getDestructor()) 6765 return DD->isVirtual(); 6766 return false; 6767 } 6768 6769 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6770 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6771 if (CXXDestructorDecl *DD = RD->getDestructor()) 6772 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6773 return nullptr; 6774 } 6775 6776 /// Check that the given object is a suitable pointer to a heap allocation that 6777 /// still exists and is of the right kind for the purpose of a deletion. 6778 /// 6779 /// On success, returns the heap allocation to deallocate. On failure, produces 6780 /// a diagnostic and returns std::nullopt. 6781 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6782 const LValue &Pointer, 6783 DynAlloc::Kind DeallocKind) { 6784 auto PointerAsString = [&] { 6785 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6786 }; 6787 6788 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6789 if (!DA) { 6790 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6791 << PointerAsString(); 6792 if (Pointer.Base) 6793 NoteLValueLocation(Info, Pointer.Base); 6794 return std::nullopt; 6795 } 6796 6797 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6798 if (!Alloc) { 6799 Info.FFDiag(E, diag::note_constexpr_double_delete); 6800 return std::nullopt; 6801 } 6802 6803 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6804 if (DeallocKind != (*Alloc)->getKind()) { 6805 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6806 << DeallocKind << (*Alloc)->getKind() << AllocType; 6807 NoteLValueLocation(Info, Pointer.Base); 6808 return std::nullopt; 6809 } 6810 6811 bool Subobject = false; 6812 if (DeallocKind == DynAlloc::New) { 6813 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6814 Pointer.Designator.isOnePastTheEnd(); 6815 } else { 6816 Subobject = Pointer.Designator.Entries.size() != 1 || 6817 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6818 } 6819 if (Subobject) { 6820 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6821 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6822 return std::nullopt; 6823 } 6824 6825 return Alloc; 6826 } 6827 6828 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6829 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6830 if (Info.checkingPotentialConstantExpression() || 6831 Info.SpeculativeEvaluationDepth) 6832 return false; 6833 6834 // This is permitted only within a call to std::allocator<T>::deallocate. 6835 if (!Info.getStdAllocatorCaller("deallocate")) { 6836 Info.FFDiag(E->getExprLoc()); 6837 return true; 6838 } 6839 6840 LValue Pointer; 6841 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6842 return false; 6843 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6844 EvaluateIgnoredValue(Info, E->getArg(I)); 6845 6846 if (Pointer.Designator.Invalid) 6847 return false; 6848 6849 // Deleting a null pointer would have no effect, but it's not permitted by 6850 // std::allocator<T>::deallocate's contract. 6851 if (Pointer.isNullPointer()) { 6852 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6853 return true; 6854 } 6855 6856 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6857 return false; 6858 6859 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6860 return true; 6861 } 6862 6863 //===----------------------------------------------------------------------===// 6864 // Generic Evaluation 6865 //===----------------------------------------------------------------------===// 6866 namespace { 6867 6868 class BitCastBuffer { 6869 // FIXME: We're going to need bit-level granularity when we support 6870 // bit-fields. 6871 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6872 // we don't support a host or target where that is the case. Still, we should 6873 // use a more generic type in case we ever do. 6874 SmallVector<std::optional<unsigned char>, 32> Bytes; 6875 6876 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6877 "Need at least 8 bit unsigned char"); 6878 6879 bool TargetIsLittleEndian; 6880 6881 public: 6882 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6883 : Bytes(Width.getQuantity()), 6884 TargetIsLittleEndian(TargetIsLittleEndian) {} 6885 6886 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width, 6887 SmallVectorImpl<unsigned char> &Output) const { 6888 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6889 // If a byte of an integer is uninitialized, then the whole integer is 6890 // uninitialized. 6891 if (!Bytes[I.getQuantity()]) 6892 return false; 6893 Output.push_back(*Bytes[I.getQuantity()]); 6894 } 6895 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6896 std::reverse(Output.begin(), Output.end()); 6897 return true; 6898 } 6899 6900 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6901 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6902 std::reverse(Input.begin(), Input.end()); 6903 6904 size_t Index = 0; 6905 for (unsigned char Byte : Input) { 6906 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6907 Bytes[Offset.getQuantity() + Index] = Byte; 6908 ++Index; 6909 } 6910 } 6911 6912 size_t size() { return Bytes.size(); } 6913 }; 6914 6915 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6916 /// target would represent the value at runtime. 6917 class APValueToBufferConverter { 6918 EvalInfo &Info; 6919 BitCastBuffer Buffer; 6920 const CastExpr *BCE; 6921 6922 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6923 const CastExpr *BCE) 6924 : Info(Info), 6925 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6926 BCE(BCE) {} 6927 6928 bool visit(const APValue &Val, QualType Ty) { 6929 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6930 } 6931 6932 // Write out Val with type Ty into Buffer starting at Offset. 6933 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6934 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6935 6936 // As a special case, nullptr_t has an indeterminate value. 6937 if (Ty->isNullPtrType()) 6938 return true; 6939 6940 // Dig through Src to find the byte at SrcOffset. 6941 switch (Val.getKind()) { 6942 case APValue::Indeterminate: 6943 case APValue::None: 6944 return true; 6945 6946 case APValue::Int: 6947 return visitInt(Val.getInt(), Ty, Offset); 6948 case APValue::Float: 6949 return visitFloat(Val.getFloat(), Ty, Offset); 6950 case APValue::Array: 6951 return visitArray(Val, Ty, Offset); 6952 case APValue::Struct: 6953 return visitRecord(Val, Ty, Offset); 6954 6955 case APValue::ComplexInt: 6956 case APValue::ComplexFloat: 6957 case APValue::Vector: 6958 case APValue::FixedPoint: 6959 // FIXME: We should support these. 6960 6961 case APValue::Union: 6962 case APValue::MemberPointer: 6963 case APValue::AddrLabelDiff: { 6964 Info.FFDiag(BCE->getBeginLoc(), 6965 diag::note_constexpr_bit_cast_unsupported_type) 6966 << Ty; 6967 return false; 6968 } 6969 6970 case APValue::LValue: 6971 llvm_unreachable("LValue subobject in bit_cast?"); 6972 } 6973 llvm_unreachable("Unhandled APValue::ValueKind"); 6974 } 6975 6976 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6977 const RecordDecl *RD = Ty->getAsRecordDecl(); 6978 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6979 6980 // Visit the base classes. 6981 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6982 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6983 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6984 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6985 6986 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6987 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6988 return false; 6989 } 6990 } 6991 6992 // Visit the fields. 6993 unsigned FieldIdx = 0; 6994 for (FieldDecl *FD : RD->fields()) { 6995 if (FD->isBitField()) { 6996 Info.FFDiag(BCE->getBeginLoc(), 6997 diag::note_constexpr_bit_cast_unsupported_bitfield); 6998 return false; 6999 } 7000 7001 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7002 7003 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 7004 "only bit-fields can have sub-char alignment"); 7005 CharUnits FieldOffset = 7006 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 7007 QualType FieldTy = FD->getType(); 7008 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 7009 return false; 7010 ++FieldIdx; 7011 } 7012 7013 return true; 7014 } 7015 7016 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 7017 const auto *CAT = 7018 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 7019 if (!CAT) 7020 return false; 7021 7022 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 7023 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 7024 unsigned ArraySize = Val.getArraySize(); 7025 // First, initialize the initialized elements. 7026 for (unsigned I = 0; I != NumInitializedElts; ++I) { 7027 const APValue &SubObj = Val.getArrayInitializedElt(I); 7028 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 7029 return false; 7030 } 7031 7032 // Next, initialize the rest of the array using the filler. 7033 if (Val.hasArrayFiller()) { 7034 const APValue &Filler = Val.getArrayFiller(); 7035 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 7036 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 7037 return false; 7038 } 7039 } 7040 7041 return true; 7042 } 7043 7044 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 7045 APSInt AdjustedVal = Val; 7046 unsigned Width = AdjustedVal.getBitWidth(); 7047 if (Ty->isBooleanType()) { 7048 Width = Info.Ctx.getTypeSize(Ty); 7049 AdjustedVal = AdjustedVal.extend(Width); 7050 } 7051 7052 SmallVector<unsigned char, 8> Bytes(Width / 8); 7053 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 7054 Buffer.writeObject(Offset, Bytes); 7055 return true; 7056 } 7057 7058 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 7059 APSInt AsInt(Val.bitcastToAPInt()); 7060 return visitInt(AsInt, Ty, Offset); 7061 } 7062 7063 public: 7064 static std::optional<BitCastBuffer> 7065 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) { 7066 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 7067 APValueToBufferConverter Converter(Info, DstSize, BCE); 7068 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 7069 return std::nullopt; 7070 return Converter.Buffer; 7071 } 7072 }; 7073 7074 /// Write an BitCastBuffer into an APValue. 7075 class BufferToAPValueConverter { 7076 EvalInfo &Info; 7077 const BitCastBuffer &Buffer; 7078 const CastExpr *BCE; 7079 7080 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 7081 const CastExpr *BCE) 7082 : Info(Info), Buffer(Buffer), BCE(BCE) {} 7083 7084 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 7085 // with an invalid type, so anything left is a deficiency on our part (FIXME). 7086 // Ideally this will be unreachable. 7087 std::nullopt_t unsupportedType(QualType Ty) { 7088 Info.FFDiag(BCE->getBeginLoc(), 7089 diag::note_constexpr_bit_cast_unsupported_type) 7090 << Ty; 7091 return std::nullopt; 7092 } 7093 7094 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) { 7095 Info.FFDiag(BCE->getBeginLoc(), 7096 diag::note_constexpr_bit_cast_unrepresentable_value) 7097 << Ty << toString(Val, /*Radix=*/10); 7098 return std::nullopt; 7099 } 7100 7101 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 7102 const EnumType *EnumSugar = nullptr) { 7103 if (T->isNullPtrType()) { 7104 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7105 return APValue((Expr *)nullptr, 7106 /*Offset=*/CharUnits::fromQuantity(NullValue), 7107 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7108 } 7109 7110 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7111 7112 // Work around floating point types that contain unused padding bytes. This 7113 // is really just `long double` on x86, which is the only fundamental type 7114 // with padding bytes. 7115 if (T->isRealFloatingType()) { 7116 const llvm::fltSemantics &Semantics = 7117 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7118 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7119 assert(NumBits % 8 == 0); 7120 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7121 if (NumBytes != SizeOf) 7122 SizeOf = NumBytes; 7123 } 7124 7125 SmallVector<uint8_t, 8> Bytes; 7126 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7127 // If this is std::byte or unsigned char, then its okay to store an 7128 // indeterminate value. 7129 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7130 bool IsUChar = 7131 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7132 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7133 if (!IsStdByte && !IsUChar) { 7134 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7135 Info.FFDiag(BCE->getExprLoc(), 7136 diag::note_constexpr_bit_cast_indet_dest) 7137 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7138 return std::nullopt; 7139 } 7140 7141 return APValue::IndeterminateValue(); 7142 } 7143 7144 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7145 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7146 7147 if (T->isIntegralOrEnumerationType()) { 7148 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7149 7150 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7151 if (IntWidth != Val.getBitWidth()) { 7152 APSInt Truncated = Val.trunc(IntWidth); 7153 if (Truncated.extend(Val.getBitWidth()) != Val) 7154 return unrepresentableValue(QualType(T, 0), Val); 7155 Val = Truncated; 7156 } 7157 7158 return APValue(Val); 7159 } 7160 7161 if (T->isRealFloatingType()) { 7162 const llvm::fltSemantics &Semantics = 7163 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7164 return APValue(APFloat(Semantics, Val)); 7165 } 7166 7167 return unsupportedType(QualType(T, 0)); 7168 } 7169 7170 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7171 const RecordDecl *RD = RTy->getAsRecordDecl(); 7172 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7173 7174 unsigned NumBases = 0; 7175 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7176 NumBases = CXXRD->getNumBases(); 7177 7178 APValue ResultVal(APValue::UninitStruct(), NumBases, 7179 std::distance(RD->field_begin(), RD->field_end())); 7180 7181 // Visit the base classes. 7182 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7183 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7184 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7185 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7186 if (BaseDecl->isEmpty() || 7187 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7188 continue; 7189 7190 std::optional<APValue> SubObj = visitType( 7191 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7192 if (!SubObj) 7193 return std::nullopt; 7194 ResultVal.getStructBase(I) = *SubObj; 7195 } 7196 } 7197 7198 // Visit the fields. 7199 unsigned FieldIdx = 0; 7200 for (FieldDecl *FD : RD->fields()) { 7201 // FIXME: We don't currently support bit-fields. A lot of the logic for 7202 // this is in CodeGen, so we need to factor it around. 7203 if (FD->isBitField()) { 7204 Info.FFDiag(BCE->getBeginLoc(), 7205 diag::note_constexpr_bit_cast_unsupported_bitfield); 7206 return std::nullopt; 7207 } 7208 7209 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7210 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7211 7212 CharUnits FieldOffset = 7213 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7214 Offset; 7215 QualType FieldTy = FD->getType(); 7216 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7217 if (!SubObj) 7218 return std::nullopt; 7219 ResultVal.getStructField(FieldIdx) = *SubObj; 7220 ++FieldIdx; 7221 } 7222 7223 return ResultVal; 7224 } 7225 7226 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7227 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7228 assert(!RepresentationType.isNull() && 7229 "enum forward decl should be caught by Sema"); 7230 const auto *AsBuiltin = 7231 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7232 // Recurse into the underlying type. Treat std::byte transparently as 7233 // unsigned char. 7234 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7235 } 7236 7237 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7238 size_t Size = Ty->getSize().getLimitedValue(); 7239 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7240 7241 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7242 for (size_t I = 0; I != Size; ++I) { 7243 std::optional<APValue> ElementValue = 7244 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7245 if (!ElementValue) 7246 return std::nullopt; 7247 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7248 } 7249 7250 return ArrayValue; 7251 } 7252 7253 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7254 return unsupportedType(QualType(Ty, 0)); 7255 } 7256 7257 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7258 QualType Can = Ty.getCanonicalType(); 7259 7260 switch (Can->getTypeClass()) { 7261 #define TYPE(Class, Base) \ 7262 case Type::Class: \ 7263 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7264 #define ABSTRACT_TYPE(Class, Base) 7265 #define NON_CANONICAL_TYPE(Class, Base) \ 7266 case Type::Class: \ 7267 llvm_unreachable("non-canonical type should be impossible!"); 7268 #define DEPENDENT_TYPE(Class, Base) \ 7269 case Type::Class: \ 7270 llvm_unreachable( \ 7271 "dependent types aren't supported in the constant evaluator!"); 7272 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7273 case Type::Class: \ 7274 llvm_unreachable("either dependent or not canonical!"); 7275 #include "clang/AST/TypeNodes.inc" 7276 } 7277 llvm_unreachable("Unhandled Type::TypeClass"); 7278 } 7279 7280 public: 7281 // Pull out a full value of type DstType. 7282 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7283 const CastExpr *BCE) { 7284 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7285 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7286 } 7287 }; 7288 7289 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7290 QualType Ty, EvalInfo *Info, 7291 const ASTContext &Ctx, 7292 bool CheckingDest) { 7293 Ty = Ty.getCanonicalType(); 7294 7295 auto diag = [&](int Reason) { 7296 if (Info) 7297 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7298 << CheckingDest << (Reason == 4) << Reason; 7299 return false; 7300 }; 7301 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7302 if (Info) 7303 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7304 << NoteTy << Construct << Ty; 7305 return false; 7306 }; 7307 7308 if (Ty->isUnionType()) 7309 return diag(0); 7310 if (Ty->isPointerType()) 7311 return diag(1); 7312 if (Ty->isMemberPointerType()) 7313 return diag(2); 7314 if (Ty.isVolatileQualified()) 7315 return diag(3); 7316 7317 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7318 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7319 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7320 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7321 CheckingDest)) 7322 return note(1, BS.getType(), BS.getBeginLoc()); 7323 } 7324 for (FieldDecl *FD : Record->fields()) { 7325 if (FD->getType()->isReferenceType()) 7326 return diag(4); 7327 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7328 CheckingDest)) 7329 return note(0, FD->getType(), FD->getBeginLoc()); 7330 } 7331 } 7332 7333 if (Ty->isArrayType() && 7334 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7335 Info, Ctx, CheckingDest)) 7336 return false; 7337 7338 return true; 7339 } 7340 7341 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7342 const ASTContext &Ctx, 7343 const CastExpr *BCE) { 7344 bool DestOK = checkBitCastConstexprEligibilityType( 7345 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7346 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7347 BCE->getBeginLoc(), 7348 BCE->getSubExpr()->getType(), Info, Ctx, false); 7349 return SourceOK; 7350 } 7351 7352 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7353 APValue &SourceValue, 7354 const CastExpr *BCE) { 7355 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7356 "no host or target supports non 8-bit chars"); 7357 assert(SourceValue.isLValue() && 7358 "LValueToRValueBitcast requires an lvalue operand!"); 7359 7360 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7361 return false; 7362 7363 LValue SourceLValue; 7364 APValue SourceRValue; 7365 SourceLValue.setFrom(Info.Ctx, SourceValue); 7366 if (!handleLValueToRValueConversion( 7367 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7368 SourceRValue, /*WantObjectRepresentation=*/true)) 7369 return false; 7370 7371 // Read out SourceValue into a char buffer. 7372 std::optional<BitCastBuffer> Buffer = 7373 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7374 if (!Buffer) 7375 return false; 7376 7377 // Write out the buffer into a new APValue. 7378 std::optional<APValue> MaybeDestValue = 7379 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7380 if (!MaybeDestValue) 7381 return false; 7382 7383 DestValue = std::move(*MaybeDestValue); 7384 return true; 7385 } 7386 7387 template <class Derived> 7388 class ExprEvaluatorBase 7389 : public ConstStmtVisitor<Derived, bool> { 7390 private: 7391 Derived &getDerived() { return static_cast<Derived&>(*this); } 7392 bool DerivedSuccess(const APValue &V, const Expr *E) { 7393 return getDerived().Success(V, E); 7394 } 7395 bool DerivedZeroInitialization(const Expr *E) { 7396 return getDerived().ZeroInitialization(E); 7397 } 7398 7399 // Check whether a conditional operator with a non-constant condition is a 7400 // potential constant expression. If neither arm is a potential constant 7401 // expression, then the conditional operator is not either. 7402 template<typename ConditionalOperator> 7403 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7404 assert(Info.checkingPotentialConstantExpression()); 7405 7406 // Speculatively evaluate both arms. 7407 SmallVector<PartialDiagnosticAt, 8> Diag; 7408 { 7409 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7410 StmtVisitorTy::Visit(E->getFalseExpr()); 7411 if (Diag.empty()) 7412 return; 7413 } 7414 7415 { 7416 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7417 Diag.clear(); 7418 StmtVisitorTy::Visit(E->getTrueExpr()); 7419 if (Diag.empty()) 7420 return; 7421 } 7422 7423 Error(E, diag::note_constexpr_conditional_never_const); 7424 } 7425 7426 7427 template<typename ConditionalOperator> 7428 bool HandleConditionalOperator(const ConditionalOperator *E) { 7429 bool BoolResult; 7430 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7431 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7432 CheckPotentialConstantConditional(E); 7433 return false; 7434 } 7435 if (Info.noteFailure()) { 7436 StmtVisitorTy::Visit(E->getTrueExpr()); 7437 StmtVisitorTy::Visit(E->getFalseExpr()); 7438 } 7439 return false; 7440 } 7441 7442 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7443 return StmtVisitorTy::Visit(EvalExpr); 7444 } 7445 7446 protected: 7447 EvalInfo &Info; 7448 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7449 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7450 7451 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7452 return Info.CCEDiag(E, D); 7453 } 7454 7455 bool ZeroInitialization(const Expr *E) { return Error(E); } 7456 7457 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) { 7458 unsigned BuiltinOp = E->getBuiltinCallee(); 7459 return BuiltinOp != 0 && 7460 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp); 7461 } 7462 7463 public: 7464 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7465 7466 EvalInfo &getEvalInfo() { return Info; } 7467 7468 /// Report an evaluation error. This should only be called when an error is 7469 /// first discovered. When propagating an error, just return false. 7470 bool Error(const Expr *E, diag::kind D) { 7471 Info.FFDiag(E, D); 7472 return false; 7473 } 7474 bool Error(const Expr *E) { 7475 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7476 } 7477 7478 bool VisitStmt(const Stmt *) { 7479 llvm_unreachable("Expression evaluator should not be called on stmts"); 7480 } 7481 bool VisitExpr(const Expr *E) { 7482 return Error(E); 7483 } 7484 7485 bool VisitConstantExpr(const ConstantExpr *E) { 7486 if (E->hasAPValueResult()) 7487 return DerivedSuccess(E->getAPValueResult(), E); 7488 7489 return StmtVisitorTy::Visit(E->getSubExpr()); 7490 } 7491 7492 bool VisitParenExpr(const ParenExpr *E) 7493 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7494 bool VisitUnaryExtension(const UnaryOperator *E) 7495 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7496 bool VisitUnaryPlus(const UnaryOperator *E) 7497 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7498 bool VisitChooseExpr(const ChooseExpr *E) 7499 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7500 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7501 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7502 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7503 { return StmtVisitorTy::Visit(E->getReplacement()); } 7504 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7505 TempVersionRAII RAII(*Info.CurrentCall); 7506 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7507 return StmtVisitorTy::Visit(E->getExpr()); 7508 } 7509 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7510 TempVersionRAII RAII(*Info.CurrentCall); 7511 // The initializer may not have been parsed yet, or might be erroneous. 7512 if (!E->getExpr()) 7513 return Error(E); 7514 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7515 return StmtVisitorTy::Visit(E->getExpr()); 7516 } 7517 7518 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7519 FullExpressionRAII Scope(Info); 7520 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7521 } 7522 7523 // Temporaries are registered when created, so we don't care about 7524 // CXXBindTemporaryExpr. 7525 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7526 return StmtVisitorTy::Visit(E->getSubExpr()); 7527 } 7528 7529 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7530 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7531 return static_cast<Derived*>(this)->VisitCastExpr(E); 7532 } 7533 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7534 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7535 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7536 return static_cast<Derived*>(this)->VisitCastExpr(E); 7537 } 7538 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7539 return static_cast<Derived*>(this)->VisitCastExpr(E); 7540 } 7541 7542 bool VisitBinaryOperator(const BinaryOperator *E) { 7543 switch (E->getOpcode()) { 7544 default: 7545 return Error(E); 7546 7547 case BO_Comma: 7548 VisitIgnoredValue(E->getLHS()); 7549 return StmtVisitorTy::Visit(E->getRHS()); 7550 7551 case BO_PtrMemD: 7552 case BO_PtrMemI: { 7553 LValue Obj; 7554 if (!HandleMemberPointerAccess(Info, E, Obj)) 7555 return false; 7556 APValue Result; 7557 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7558 return false; 7559 return DerivedSuccess(Result, E); 7560 } 7561 } 7562 } 7563 7564 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7565 return StmtVisitorTy::Visit(E->getSemanticForm()); 7566 } 7567 7568 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7569 // Evaluate and cache the common expression. We treat it as a temporary, 7570 // even though it's not quite the same thing. 7571 LValue CommonLV; 7572 if (!Evaluate(Info.CurrentCall->createTemporary( 7573 E->getOpaqueValue(), 7574 getStorageType(Info.Ctx, E->getOpaqueValue()), 7575 ScopeKind::FullExpression, CommonLV), 7576 Info, E->getCommon())) 7577 return false; 7578 7579 return HandleConditionalOperator(E); 7580 } 7581 7582 bool VisitConditionalOperator(const ConditionalOperator *E) { 7583 bool IsBcpCall = false; 7584 // If the condition (ignoring parens) is a __builtin_constant_p call, 7585 // the result is a constant expression if it can be folded without 7586 // side-effects. This is an important GNU extension. See GCC PR38377 7587 // for discussion. 7588 if (const CallExpr *CallCE = 7589 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7590 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7591 IsBcpCall = true; 7592 7593 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7594 // constant expression; we can't check whether it's potentially foldable. 7595 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7596 // it would return 'false' in this mode. 7597 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7598 return false; 7599 7600 FoldConstant Fold(Info, IsBcpCall); 7601 if (!HandleConditionalOperator(E)) { 7602 Fold.keepDiagnostics(); 7603 return false; 7604 } 7605 7606 return true; 7607 } 7608 7609 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7610 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7611 return DerivedSuccess(*Value, E); 7612 7613 const Expr *Source = E->getSourceExpr(); 7614 if (!Source) 7615 return Error(E); 7616 if (Source == E) { 7617 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7618 return Error(E); 7619 } 7620 return StmtVisitorTy::Visit(Source); 7621 } 7622 7623 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7624 for (const Expr *SemE : E->semantics()) { 7625 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7626 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7627 // result expression: there could be two different LValues that would 7628 // refer to the same object in that case, and we can't model that. 7629 if (SemE == E->getResultExpr()) 7630 return Error(E); 7631 7632 // Unique OVEs get evaluated if and when we encounter them when 7633 // emitting the rest of the semantic form, rather than eagerly. 7634 if (OVE->isUnique()) 7635 continue; 7636 7637 LValue LV; 7638 if (!Evaluate(Info.CurrentCall->createTemporary( 7639 OVE, getStorageType(Info.Ctx, OVE), 7640 ScopeKind::FullExpression, LV), 7641 Info, OVE->getSourceExpr())) 7642 return false; 7643 } else if (SemE == E->getResultExpr()) { 7644 if (!StmtVisitorTy::Visit(SemE)) 7645 return false; 7646 } else { 7647 if (!EvaluateIgnoredValue(Info, SemE)) 7648 return false; 7649 } 7650 } 7651 return true; 7652 } 7653 7654 bool VisitCallExpr(const CallExpr *E) { 7655 APValue Result; 7656 if (!handleCallExpr(E, Result, nullptr)) 7657 return false; 7658 return DerivedSuccess(Result, E); 7659 } 7660 7661 bool handleCallExpr(const CallExpr *E, APValue &Result, 7662 const LValue *ResultSlot) { 7663 CallScopeRAII CallScope(Info); 7664 7665 const Expr *Callee = E->getCallee()->IgnoreParens(); 7666 QualType CalleeType = Callee->getType(); 7667 7668 const FunctionDecl *FD = nullptr; 7669 LValue *This = nullptr, ThisVal; 7670 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs()); 7671 bool HasQualifier = false; 7672 7673 CallRef Call; 7674 7675 // Extract function decl and 'this' pointer from the callee. 7676 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7677 const CXXMethodDecl *Member = nullptr; 7678 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7679 // Explicit bound member calls, such as x.f() or p->g(); 7680 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7681 return false; 7682 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7683 if (!Member) 7684 return Error(Callee); 7685 This = &ThisVal; 7686 HasQualifier = ME->hasQualifier(); 7687 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7688 // Indirect bound member calls ('.*' or '->*'). 7689 const ValueDecl *D = 7690 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7691 if (!D) 7692 return false; 7693 Member = dyn_cast<CXXMethodDecl>(D); 7694 if (!Member) 7695 return Error(Callee); 7696 This = &ThisVal; 7697 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7698 if (!Info.getLangOpts().CPlusPlus20) 7699 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7700 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7701 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7702 } else 7703 return Error(Callee); 7704 FD = Member; 7705 } else if (CalleeType->isFunctionPointerType()) { 7706 LValue CalleeLV; 7707 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7708 return false; 7709 7710 if (!CalleeLV.getLValueOffset().isZero()) 7711 return Error(Callee); 7712 if (CalleeLV.isNullPointer()) { 7713 Info.FFDiag(Callee, diag::note_constexpr_null_callee) 7714 << const_cast<Expr *>(Callee); 7715 return false; 7716 } 7717 FD = dyn_cast_or_null<FunctionDecl>( 7718 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7719 if (!FD) 7720 return Error(Callee); 7721 // Don't call function pointers which have been cast to some other type. 7722 // Per DR (no number yet), the caller and callee can differ in noexcept. 7723 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7724 CalleeType->getPointeeType(), FD->getType())) { 7725 return Error(E); 7726 } 7727 7728 // For an (overloaded) assignment expression, evaluate the RHS before the 7729 // LHS. 7730 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7731 if (OCE && OCE->isAssignmentOp()) { 7732 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7733 Call = Info.CurrentCall->createCall(FD); 7734 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7735 Info, FD, /*RightToLeft=*/true)) 7736 return false; 7737 } 7738 7739 // Overloaded operator calls to member functions are represented as normal 7740 // calls with '*this' as the first argument. 7741 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7742 if (MD && !MD->isStatic()) { 7743 // FIXME: When selecting an implicit conversion for an overloaded 7744 // operator delete, we sometimes try to evaluate calls to conversion 7745 // operators without a 'this' parameter! 7746 if (Args.empty()) 7747 return Error(E); 7748 7749 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7750 return false; 7751 This = &ThisVal; 7752 7753 // If this is syntactically a simple assignment using a trivial 7754 // assignment operator, start the lifetimes of union members as needed, 7755 // per C++20 [class.union]5. 7756 if (Info.getLangOpts().CPlusPlus20 && OCE && 7757 OCE->getOperator() == OO_Equal && MD->isTrivial() && 7758 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal)) 7759 return false; 7760 7761 Args = Args.slice(1); 7762 } else if (MD && MD->isLambdaStaticInvoker()) { 7763 // Map the static invoker for the lambda back to the call operator. 7764 // Conveniently, we don't have to slice out the 'this' argument (as is 7765 // being done for the non-static case), since a static member function 7766 // doesn't have an implicit argument passed in. 7767 const CXXRecordDecl *ClosureClass = MD->getParent(); 7768 assert( 7769 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7770 "Number of captures must be zero for conversion to function-ptr"); 7771 7772 const CXXMethodDecl *LambdaCallOp = 7773 ClosureClass->getLambdaCallOperator(); 7774 7775 // Set 'FD', the function that will be called below, to the call 7776 // operator. If the closure object represents a generic lambda, find 7777 // the corresponding specialization of the call operator. 7778 7779 if (ClosureClass->isGenericLambda()) { 7780 assert(MD->isFunctionTemplateSpecialization() && 7781 "A generic lambda's static-invoker function must be a " 7782 "template specialization"); 7783 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7784 FunctionTemplateDecl *CallOpTemplate = 7785 LambdaCallOp->getDescribedFunctionTemplate(); 7786 void *InsertPos = nullptr; 7787 FunctionDecl *CorrespondingCallOpSpecialization = 7788 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7789 assert(CorrespondingCallOpSpecialization && 7790 "We must always have a function call operator specialization " 7791 "that corresponds to our static invoker specialization"); 7792 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7793 } else 7794 FD = LambdaCallOp; 7795 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7796 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7797 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7798 LValue Ptr; 7799 if (!HandleOperatorNewCall(Info, E, Ptr)) 7800 return false; 7801 Ptr.moveInto(Result); 7802 return CallScope.destroy(); 7803 } else { 7804 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7805 } 7806 } 7807 } else 7808 return Error(E); 7809 7810 // Evaluate the arguments now if we've not already done so. 7811 if (!Call) { 7812 Call = Info.CurrentCall->createCall(FD); 7813 if (!EvaluateArgs(Args, Call, Info, FD)) 7814 return false; 7815 } 7816 7817 SmallVector<QualType, 4> CovariantAdjustmentPath; 7818 if (This) { 7819 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7820 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7821 // Perform virtual dispatch, if necessary. 7822 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7823 CovariantAdjustmentPath); 7824 if (!FD) 7825 return false; 7826 } else { 7827 // Check that the 'this' pointer points to an object of the right type. 7828 // FIXME: If this is an assignment operator call, we may need to change 7829 // the active union member before we check this. 7830 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7831 return false; 7832 } 7833 } 7834 7835 // Destructor calls are different enough that they have their own codepath. 7836 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7837 assert(This && "no 'this' pointer for destructor call"); 7838 return HandleDestruction(Info, E, *This, 7839 Info.Ctx.getRecordType(DD->getParent())) && 7840 CallScope.destroy(); 7841 } 7842 7843 const FunctionDecl *Definition = nullptr; 7844 Stmt *Body = FD->getBody(Definition); 7845 7846 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7847 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call, 7848 Body, Info, Result, ResultSlot)) 7849 return false; 7850 7851 if (!CovariantAdjustmentPath.empty() && 7852 !HandleCovariantReturnAdjustment(Info, E, Result, 7853 CovariantAdjustmentPath)) 7854 return false; 7855 7856 return CallScope.destroy(); 7857 } 7858 7859 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7860 return StmtVisitorTy::Visit(E->getInitializer()); 7861 } 7862 bool VisitInitListExpr(const InitListExpr *E) { 7863 if (E->getNumInits() == 0) 7864 return DerivedZeroInitialization(E); 7865 if (E->getNumInits() == 1) 7866 return StmtVisitorTy::Visit(E->getInit(0)); 7867 return Error(E); 7868 } 7869 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7870 return DerivedZeroInitialization(E); 7871 } 7872 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7873 return DerivedZeroInitialization(E); 7874 } 7875 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7876 return DerivedZeroInitialization(E); 7877 } 7878 7879 /// A member expression where the object is a prvalue is itself a prvalue. 7880 bool VisitMemberExpr(const MemberExpr *E) { 7881 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7882 "missing temporary materialization conversion"); 7883 assert(!E->isArrow() && "missing call to bound member function?"); 7884 7885 APValue Val; 7886 if (!Evaluate(Val, Info, E->getBase())) 7887 return false; 7888 7889 QualType BaseTy = E->getBase()->getType(); 7890 7891 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7892 if (!FD) return Error(E); 7893 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7894 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7895 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7896 7897 // Note: there is no lvalue base here. But this case should only ever 7898 // happen in C or in C++98, where we cannot be evaluating a constexpr 7899 // constructor, which is the only case the base matters. 7900 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7901 SubobjectDesignator Designator(BaseTy); 7902 Designator.addDeclUnchecked(FD); 7903 7904 APValue Result; 7905 return extractSubobject(Info, E, Obj, Designator, Result) && 7906 DerivedSuccess(Result, E); 7907 } 7908 7909 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7910 APValue Val; 7911 if (!Evaluate(Val, Info, E->getBase())) 7912 return false; 7913 7914 if (Val.isVector()) { 7915 SmallVector<uint32_t, 4> Indices; 7916 E->getEncodedElementAccess(Indices); 7917 if (Indices.size() == 1) { 7918 // Return scalar. 7919 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7920 } else { 7921 // Construct new APValue vector. 7922 SmallVector<APValue, 4> Elts; 7923 for (unsigned I = 0; I < Indices.size(); ++I) { 7924 Elts.push_back(Val.getVectorElt(Indices[I])); 7925 } 7926 APValue VecResult(Elts.data(), Indices.size()); 7927 return DerivedSuccess(VecResult, E); 7928 } 7929 } 7930 7931 return false; 7932 } 7933 7934 bool VisitCastExpr(const CastExpr *E) { 7935 switch (E->getCastKind()) { 7936 default: 7937 break; 7938 7939 case CK_AtomicToNonAtomic: { 7940 APValue AtomicVal; 7941 // This does not need to be done in place even for class/array types: 7942 // atomic-to-non-atomic conversion implies copying the object 7943 // representation. 7944 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7945 return false; 7946 return DerivedSuccess(AtomicVal, E); 7947 } 7948 7949 case CK_NoOp: 7950 case CK_UserDefinedConversion: 7951 return StmtVisitorTy::Visit(E->getSubExpr()); 7952 7953 case CK_LValueToRValue: { 7954 LValue LVal; 7955 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7956 return false; 7957 APValue RVal; 7958 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7959 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7960 LVal, RVal)) 7961 return false; 7962 return DerivedSuccess(RVal, E); 7963 } 7964 case CK_LValueToRValueBitCast: { 7965 APValue DestValue, SourceValue; 7966 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7967 return false; 7968 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7969 return false; 7970 return DerivedSuccess(DestValue, E); 7971 } 7972 7973 case CK_AddressSpaceConversion: { 7974 APValue Value; 7975 if (!Evaluate(Value, Info, E->getSubExpr())) 7976 return false; 7977 return DerivedSuccess(Value, E); 7978 } 7979 } 7980 7981 return Error(E); 7982 } 7983 7984 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7985 return VisitUnaryPostIncDec(UO); 7986 } 7987 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7988 return VisitUnaryPostIncDec(UO); 7989 } 7990 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7991 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7992 return Error(UO); 7993 7994 LValue LVal; 7995 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7996 return false; 7997 APValue RVal; 7998 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7999 UO->isIncrementOp(), &RVal)) 8000 return false; 8001 return DerivedSuccess(RVal, UO); 8002 } 8003 8004 bool VisitStmtExpr(const StmtExpr *E) { 8005 // We will have checked the full-expressions inside the statement expression 8006 // when they were completed, and don't need to check them again now. 8007 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior, 8008 false); 8009 8010 const CompoundStmt *CS = E->getSubStmt(); 8011 if (CS->body_empty()) 8012 return true; 8013 8014 BlockScopeRAII Scope(Info); 8015 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 8016 BE = CS->body_end(); 8017 /**/; ++BI) { 8018 if (BI + 1 == BE) { 8019 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 8020 if (!FinalExpr) { 8021 Info.FFDiag((*BI)->getBeginLoc(), 8022 diag::note_constexpr_stmt_expr_unsupported); 8023 return false; 8024 } 8025 return this->Visit(FinalExpr) && Scope.destroy(); 8026 } 8027 8028 APValue ReturnValue; 8029 StmtResult Result = { ReturnValue, nullptr }; 8030 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 8031 if (ESR != ESR_Succeeded) { 8032 // FIXME: If the statement-expression terminated due to 'return', 8033 // 'break', or 'continue', it would be nice to propagate that to 8034 // the outer statement evaluation rather than bailing out. 8035 if (ESR != ESR_Failed) 8036 Info.FFDiag((*BI)->getBeginLoc(), 8037 diag::note_constexpr_stmt_expr_unsupported); 8038 return false; 8039 } 8040 } 8041 8042 llvm_unreachable("Return from function from the loop above."); 8043 } 8044 8045 /// Visit a value which is evaluated, but whose value is ignored. 8046 void VisitIgnoredValue(const Expr *E) { 8047 EvaluateIgnoredValue(Info, E); 8048 } 8049 8050 /// Potentially visit a MemberExpr's base expression. 8051 void VisitIgnoredBaseExpression(const Expr *E) { 8052 // While MSVC doesn't evaluate the base expression, it does diagnose the 8053 // presence of side-effecting behavior. 8054 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 8055 return; 8056 VisitIgnoredValue(E); 8057 } 8058 }; 8059 8060 } // namespace 8061 8062 //===----------------------------------------------------------------------===// 8063 // Common base class for lvalue and temporary evaluation. 8064 //===----------------------------------------------------------------------===// 8065 namespace { 8066 template<class Derived> 8067 class LValueExprEvaluatorBase 8068 : public ExprEvaluatorBase<Derived> { 8069 protected: 8070 LValue &Result; 8071 bool InvalidBaseOK; 8072 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 8073 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 8074 8075 bool Success(APValue::LValueBase B) { 8076 Result.set(B); 8077 return true; 8078 } 8079 8080 bool evaluatePointer(const Expr *E, LValue &Result) { 8081 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 8082 } 8083 8084 public: 8085 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 8086 : ExprEvaluatorBaseTy(Info), Result(Result), 8087 InvalidBaseOK(InvalidBaseOK) {} 8088 8089 bool Success(const APValue &V, const Expr *E) { 8090 Result.setFrom(this->Info.Ctx, V); 8091 return true; 8092 } 8093 8094 bool VisitMemberExpr(const MemberExpr *E) { 8095 // Handle non-static data members. 8096 QualType BaseTy; 8097 bool EvalOK; 8098 if (E->isArrow()) { 8099 EvalOK = evaluatePointer(E->getBase(), Result); 8100 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 8101 } else if (E->getBase()->isPRValue()) { 8102 assert(E->getBase()->getType()->isRecordType()); 8103 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 8104 BaseTy = E->getBase()->getType(); 8105 } else { 8106 EvalOK = this->Visit(E->getBase()); 8107 BaseTy = E->getBase()->getType(); 8108 } 8109 if (!EvalOK) { 8110 if (!InvalidBaseOK) 8111 return false; 8112 Result.setInvalid(E); 8113 return true; 8114 } 8115 8116 const ValueDecl *MD = E->getMemberDecl(); 8117 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8118 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8119 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8120 (void)BaseTy; 8121 if (!HandleLValueMember(this->Info, E, Result, FD)) 8122 return false; 8123 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8124 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8125 return false; 8126 } else 8127 return this->Error(E); 8128 8129 if (MD->getType()->isReferenceType()) { 8130 APValue RefValue; 8131 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8132 RefValue)) 8133 return false; 8134 return Success(RefValue, E); 8135 } 8136 return true; 8137 } 8138 8139 bool VisitBinaryOperator(const BinaryOperator *E) { 8140 switch (E->getOpcode()) { 8141 default: 8142 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8143 8144 case BO_PtrMemD: 8145 case BO_PtrMemI: 8146 return HandleMemberPointerAccess(this->Info, E, Result); 8147 } 8148 } 8149 8150 bool VisitCastExpr(const CastExpr *E) { 8151 switch (E->getCastKind()) { 8152 default: 8153 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8154 8155 case CK_DerivedToBase: 8156 case CK_UncheckedDerivedToBase: 8157 if (!this->Visit(E->getSubExpr())) 8158 return false; 8159 8160 // Now figure out the necessary offset to add to the base LV to get from 8161 // the derived class to the base class. 8162 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8163 Result); 8164 } 8165 } 8166 }; 8167 } 8168 8169 //===----------------------------------------------------------------------===// 8170 // LValue Evaluation 8171 // 8172 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8173 // function designators (in C), decl references to void objects (in C), and 8174 // temporaries (if building with -Wno-address-of-temporary). 8175 // 8176 // LValue evaluation produces values comprising a base expression of one of the 8177 // following types: 8178 // - Declarations 8179 // * VarDecl 8180 // * FunctionDecl 8181 // - Literals 8182 // * CompoundLiteralExpr in C (and in global scope in C++) 8183 // * StringLiteral 8184 // * PredefinedExpr 8185 // * ObjCStringLiteralExpr 8186 // * ObjCEncodeExpr 8187 // * AddrLabelExpr 8188 // * BlockExpr 8189 // * CallExpr for a MakeStringConstant builtin 8190 // - typeid(T) expressions, as TypeInfoLValues 8191 // - Locals and temporaries 8192 // * MaterializeTemporaryExpr 8193 // * Any Expr, with a CallIndex indicating the function in which the temporary 8194 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8195 // from the AST (FIXME). 8196 // * A MaterializeTemporaryExpr that has static storage duration, with no 8197 // CallIndex, for a lifetime-extended temporary. 8198 // * The ConstantExpr that is currently being evaluated during evaluation of an 8199 // immediate invocation. 8200 // plus an offset in bytes. 8201 //===----------------------------------------------------------------------===// 8202 namespace { 8203 class LValueExprEvaluator 8204 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8205 public: 8206 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8207 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8208 8209 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8210 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8211 8212 bool VisitCallExpr(const CallExpr *E); 8213 bool VisitDeclRefExpr(const DeclRefExpr *E); 8214 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8215 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8216 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8217 bool VisitMemberExpr(const MemberExpr *E); 8218 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8219 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8220 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8221 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8222 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8223 bool VisitUnaryDeref(const UnaryOperator *E); 8224 bool VisitUnaryReal(const UnaryOperator *E); 8225 bool VisitUnaryImag(const UnaryOperator *E); 8226 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8227 return VisitUnaryPreIncDec(UO); 8228 } 8229 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8230 return VisitUnaryPreIncDec(UO); 8231 } 8232 bool VisitBinAssign(const BinaryOperator *BO); 8233 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8234 8235 bool VisitCastExpr(const CastExpr *E) { 8236 switch (E->getCastKind()) { 8237 default: 8238 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8239 8240 case CK_LValueBitCast: 8241 this->CCEDiag(E, diag::note_constexpr_invalid_cast) 8242 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 8243 if (!Visit(E->getSubExpr())) 8244 return false; 8245 Result.Designator.setInvalid(); 8246 return true; 8247 8248 case CK_BaseToDerived: 8249 if (!Visit(E->getSubExpr())) 8250 return false; 8251 return HandleBaseToDerivedCast(Info, E, Result); 8252 8253 case CK_Dynamic: 8254 if (!Visit(E->getSubExpr())) 8255 return false; 8256 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8257 } 8258 } 8259 }; 8260 } // end anonymous namespace 8261 8262 /// Evaluate an expression as an lvalue. This can be legitimately called on 8263 /// expressions which are not glvalues, in three cases: 8264 /// * function designators in C, and 8265 /// * "extern void" objects 8266 /// * @selector() expressions in Objective-C 8267 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8268 bool InvalidBaseOK) { 8269 assert(!E->isValueDependent()); 8270 assert(E->isGLValue() || E->getType()->isFunctionType() || 8271 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens())); 8272 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8273 } 8274 8275 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8276 const NamedDecl *D = E->getDecl(); 8277 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl, 8278 UnnamedGlobalConstantDecl>(D)) 8279 return Success(cast<ValueDecl>(D)); 8280 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8281 return VisitVarDecl(E, VD); 8282 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8283 return Visit(BD->getBinding()); 8284 return Error(E); 8285 } 8286 8287 8288 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8289 8290 // If we are within a lambda's call operator, check whether the 'VD' referred 8291 // to within 'E' actually represents a lambda-capture that maps to a 8292 // data-member/field within the closure object, and if so, evaluate to the 8293 // field or what the field refers to. 8294 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8295 isa<DeclRefExpr>(E) && 8296 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8297 // We don't always have a complete capture-map when checking or inferring if 8298 // the function call operator meets the requirements of a constexpr function 8299 // - but we don't need to evaluate the captures to determine constexprness 8300 // (dcl.constexpr C++17). 8301 if (Info.checkingPotentialConstantExpression()) 8302 return false; 8303 8304 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8305 // Start with 'Result' referring to the complete closure object... 8306 Result = *Info.CurrentCall->This; 8307 // ... then update it to refer to the field of the closure object 8308 // that represents the capture. 8309 if (!HandleLValueMember(Info, E, Result, FD)) 8310 return false; 8311 // And if the field is of reference type, update 'Result' to refer to what 8312 // the field refers to. 8313 if (FD->getType()->isReferenceType()) { 8314 APValue RVal; 8315 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8316 RVal)) 8317 return false; 8318 Result.setFrom(Info.Ctx, RVal); 8319 } 8320 return true; 8321 } 8322 } 8323 8324 CallStackFrame *Frame = nullptr; 8325 unsigned Version = 0; 8326 if (VD->hasLocalStorage()) { 8327 // Only if a local variable was declared in the function currently being 8328 // evaluated, do we expect to be able to find its value in the current 8329 // frame. (Otherwise it was likely declared in an enclosing context and 8330 // could either have a valid evaluatable value (for e.g. a constexpr 8331 // variable) or be ill-formed (and trigger an appropriate evaluation 8332 // diagnostic)). 8333 CallStackFrame *CurrFrame = Info.CurrentCall; 8334 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8335 // Function parameters are stored in some caller's frame. (Usually the 8336 // immediate caller, but for an inherited constructor they may be more 8337 // distant.) 8338 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8339 if (CurrFrame->Arguments) { 8340 VD = CurrFrame->Arguments.getOrigParam(PVD); 8341 Frame = 8342 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8343 Version = CurrFrame->Arguments.Version; 8344 } 8345 } else { 8346 Frame = CurrFrame; 8347 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8348 } 8349 } 8350 } 8351 8352 if (!VD->getType()->isReferenceType()) { 8353 if (Frame) { 8354 Result.set({VD, Frame->Index, Version}); 8355 return true; 8356 } 8357 return Success(VD); 8358 } 8359 8360 if (!Info.getLangOpts().CPlusPlus11) { 8361 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8362 << VD << VD->getType(); 8363 Info.Note(VD->getLocation(), diag::note_declared_at); 8364 } 8365 8366 APValue *V; 8367 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8368 return false; 8369 if (!V->hasValue()) { 8370 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8371 // adjust the diagnostic to say that. 8372 if (!Info.checkingPotentialConstantExpression()) 8373 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8374 return false; 8375 } 8376 return Success(*V, E); 8377 } 8378 8379 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) { 8380 if (!IsConstantEvaluatedBuiltinCall(E)) 8381 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8382 8383 switch (E->getBuiltinCallee()) { 8384 default: 8385 return false; 8386 case Builtin::BIas_const: 8387 case Builtin::BIforward: 8388 case Builtin::BIforward_like: 8389 case Builtin::BImove: 8390 case Builtin::BImove_if_noexcept: 8391 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr()) 8392 return Visit(E->getArg(0)); 8393 break; 8394 } 8395 8396 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8397 } 8398 8399 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8400 const MaterializeTemporaryExpr *E) { 8401 // Walk through the expression to find the materialized temporary itself. 8402 SmallVector<const Expr *, 2> CommaLHSs; 8403 SmallVector<SubobjectAdjustment, 2> Adjustments; 8404 const Expr *Inner = 8405 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8406 8407 // If we passed any comma operators, evaluate their LHSs. 8408 for (const Expr *E : CommaLHSs) 8409 if (!EvaluateIgnoredValue(Info, E)) 8410 return false; 8411 8412 // A materialized temporary with static storage duration can appear within the 8413 // result of a constant expression evaluation, so we need to preserve its 8414 // value for use outside this evaluation. 8415 APValue *Value; 8416 if (E->getStorageDuration() == SD_Static) { 8417 if (Info.EvalMode == EvalInfo::EM_ConstantFold) 8418 return false; 8419 // FIXME: What about SD_Thread? 8420 Value = E->getOrCreateValue(true); 8421 *Value = APValue(); 8422 Result.set(E); 8423 } else { 8424 Value = &Info.CurrentCall->createTemporary( 8425 E, E->getType(), 8426 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8427 : ScopeKind::Block, 8428 Result); 8429 } 8430 8431 QualType Type = Inner->getType(); 8432 8433 // Materialize the temporary itself. 8434 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8435 *Value = APValue(); 8436 return false; 8437 } 8438 8439 // Adjust our lvalue to refer to the desired subobject. 8440 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8441 --I; 8442 switch (Adjustments[I].Kind) { 8443 case SubobjectAdjustment::DerivedToBaseAdjustment: 8444 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8445 Type, Result)) 8446 return false; 8447 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8448 break; 8449 8450 case SubobjectAdjustment::FieldAdjustment: 8451 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8452 return false; 8453 Type = Adjustments[I].Field->getType(); 8454 break; 8455 8456 case SubobjectAdjustment::MemberPointerAdjustment: 8457 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8458 Adjustments[I].Ptr.RHS)) 8459 return false; 8460 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8461 break; 8462 } 8463 } 8464 8465 return true; 8466 } 8467 8468 bool 8469 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8470 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8471 "lvalue compound literal in c++?"); 8472 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8473 // only see this when folding in C, so there's no standard to follow here. 8474 return Success(E); 8475 } 8476 8477 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8478 TypeInfoLValue TypeInfo; 8479 8480 if (!E->isPotentiallyEvaluated()) { 8481 if (E->isTypeOperand()) 8482 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8483 else 8484 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8485 } else { 8486 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8487 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8488 << E->getExprOperand()->getType() 8489 << E->getExprOperand()->getSourceRange(); 8490 } 8491 8492 if (!Visit(E->getExprOperand())) 8493 return false; 8494 8495 std::optional<DynamicType> DynType = 8496 ComputeDynamicType(Info, E, Result, AK_TypeId); 8497 if (!DynType) 8498 return false; 8499 8500 TypeInfo = 8501 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8502 } 8503 8504 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8505 } 8506 8507 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8508 return Success(E->getGuidDecl()); 8509 } 8510 8511 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8512 // Handle static data members. 8513 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8514 VisitIgnoredBaseExpression(E->getBase()); 8515 return VisitVarDecl(E, VD); 8516 } 8517 8518 // Handle static member functions. 8519 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8520 if (MD->isStatic()) { 8521 VisitIgnoredBaseExpression(E->getBase()); 8522 return Success(MD); 8523 } 8524 } 8525 8526 // Handle non-static data members. 8527 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8528 } 8529 8530 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8531 // FIXME: Deal with vectors as array subscript bases. 8532 if (E->getBase()->getType()->isVectorType() || 8533 E->getBase()->getType()->isVLSTBuiltinType()) 8534 return Error(E); 8535 8536 APSInt Index; 8537 bool Success = true; 8538 8539 // C++17's rules require us to evaluate the LHS first, regardless of which 8540 // side is the base. 8541 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8542 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8543 : !EvaluateInteger(SubExpr, Index, Info)) { 8544 if (!Info.noteFailure()) 8545 return false; 8546 Success = false; 8547 } 8548 } 8549 8550 return Success && 8551 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8552 } 8553 8554 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8555 return evaluatePointer(E->getSubExpr(), Result); 8556 } 8557 8558 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8559 if (!Visit(E->getSubExpr())) 8560 return false; 8561 // __real is a no-op on scalar lvalues. 8562 if (E->getSubExpr()->getType()->isAnyComplexType()) 8563 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8564 return true; 8565 } 8566 8567 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8568 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8569 "lvalue __imag__ on scalar?"); 8570 if (!Visit(E->getSubExpr())) 8571 return false; 8572 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8573 return true; 8574 } 8575 8576 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8577 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8578 return Error(UO); 8579 8580 if (!this->Visit(UO->getSubExpr())) 8581 return false; 8582 8583 return handleIncDec( 8584 this->Info, UO, Result, UO->getSubExpr()->getType(), 8585 UO->isIncrementOp(), nullptr); 8586 } 8587 8588 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8589 const CompoundAssignOperator *CAO) { 8590 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8591 return Error(CAO); 8592 8593 bool Success = true; 8594 8595 // C++17 onwards require that we evaluate the RHS first. 8596 APValue RHS; 8597 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8598 if (!Info.noteFailure()) 8599 return false; 8600 Success = false; 8601 } 8602 8603 // The overall lvalue result is the result of evaluating the LHS. 8604 if (!this->Visit(CAO->getLHS()) || !Success) 8605 return false; 8606 8607 return handleCompoundAssignment( 8608 this->Info, CAO, 8609 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8610 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8611 } 8612 8613 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8614 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8615 return Error(E); 8616 8617 bool Success = true; 8618 8619 // C++17 onwards require that we evaluate the RHS first. 8620 APValue NewVal; 8621 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8622 if (!Info.noteFailure()) 8623 return false; 8624 Success = false; 8625 } 8626 8627 if (!this->Visit(E->getLHS()) || !Success) 8628 return false; 8629 8630 if (Info.getLangOpts().CPlusPlus20 && 8631 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8632 return false; 8633 8634 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8635 NewVal); 8636 } 8637 8638 //===----------------------------------------------------------------------===// 8639 // Pointer Evaluation 8640 //===----------------------------------------------------------------------===// 8641 8642 /// Attempts to compute the number of bytes available at the pointer 8643 /// returned by a function with the alloc_size attribute. Returns true if we 8644 /// were successful. Places an unsigned number into `Result`. 8645 /// 8646 /// This expects the given CallExpr to be a call to a function with an 8647 /// alloc_size attribute. 8648 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8649 const CallExpr *Call, 8650 llvm::APInt &Result) { 8651 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8652 8653 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8654 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8655 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8656 if (Call->getNumArgs() <= SizeArgNo) 8657 return false; 8658 8659 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8660 Expr::EvalResult ExprResult; 8661 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8662 return false; 8663 Into = ExprResult.Val.getInt(); 8664 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8665 return false; 8666 Into = Into.zext(BitsInSizeT); 8667 return true; 8668 }; 8669 8670 APSInt SizeOfElem; 8671 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8672 return false; 8673 8674 if (!AllocSize->getNumElemsParam().isValid()) { 8675 Result = std::move(SizeOfElem); 8676 return true; 8677 } 8678 8679 APSInt NumberOfElems; 8680 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8681 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8682 return false; 8683 8684 bool Overflow; 8685 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8686 if (Overflow) 8687 return false; 8688 8689 Result = std::move(BytesAvailable); 8690 return true; 8691 } 8692 8693 /// Convenience function. LVal's base must be a call to an alloc_size 8694 /// function. 8695 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8696 const LValue &LVal, 8697 llvm::APInt &Result) { 8698 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8699 "Can't get the size of a non alloc_size function"); 8700 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8701 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8702 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8703 } 8704 8705 /// Attempts to evaluate the given LValueBase as the result of a call to 8706 /// a function with the alloc_size attribute. If it was possible to do so, this 8707 /// function will return true, make Result's Base point to said function call, 8708 /// and mark Result's Base as invalid. 8709 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8710 LValue &Result) { 8711 if (Base.isNull()) 8712 return false; 8713 8714 // Because we do no form of static analysis, we only support const variables. 8715 // 8716 // Additionally, we can't support parameters, nor can we support static 8717 // variables (in the latter case, use-before-assign isn't UB; in the former, 8718 // we have no clue what they'll be assigned to). 8719 const auto *VD = 8720 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8721 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8722 return false; 8723 8724 const Expr *Init = VD->getAnyInitializer(); 8725 if (!Init || Init->getType().isNull()) 8726 return false; 8727 8728 const Expr *E = Init->IgnoreParens(); 8729 if (!tryUnwrapAllocSizeCall(E)) 8730 return false; 8731 8732 // Store E instead of E unwrapped so that the type of the LValue's base is 8733 // what the user wanted. 8734 Result.setInvalid(E); 8735 8736 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8737 Result.addUnsizedArray(Info, E, Pointee); 8738 return true; 8739 } 8740 8741 namespace { 8742 class PointerExprEvaluator 8743 : public ExprEvaluatorBase<PointerExprEvaluator> { 8744 LValue &Result; 8745 bool InvalidBaseOK; 8746 8747 bool Success(const Expr *E) { 8748 Result.set(E); 8749 return true; 8750 } 8751 8752 bool evaluateLValue(const Expr *E, LValue &Result) { 8753 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8754 } 8755 8756 bool evaluatePointer(const Expr *E, LValue &Result) { 8757 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8758 } 8759 8760 bool visitNonBuiltinCallExpr(const CallExpr *E); 8761 public: 8762 8763 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8764 : ExprEvaluatorBaseTy(info), Result(Result), 8765 InvalidBaseOK(InvalidBaseOK) {} 8766 8767 bool Success(const APValue &V, const Expr *E) { 8768 Result.setFrom(Info.Ctx, V); 8769 return true; 8770 } 8771 bool ZeroInitialization(const Expr *E) { 8772 Result.setNull(Info.Ctx, E->getType()); 8773 return true; 8774 } 8775 8776 bool VisitBinaryOperator(const BinaryOperator *E); 8777 bool VisitCastExpr(const CastExpr* E); 8778 bool VisitUnaryAddrOf(const UnaryOperator *E); 8779 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8780 { return Success(E); } 8781 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8782 if (E->isExpressibleAsConstantInitializer()) 8783 return Success(E); 8784 if (Info.noteFailure()) 8785 EvaluateIgnoredValue(Info, E->getSubExpr()); 8786 return Error(E); 8787 } 8788 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8789 { return Success(E); } 8790 bool VisitCallExpr(const CallExpr *E); 8791 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8792 bool VisitBlockExpr(const BlockExpr *E) { 8793 if (!E->getBlockDecl()->hasCaptures()) 8794 return Success(E); 8795 return Error(E); 8796 } 8797 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8798 // Can't look at 'this' when checking a potential constant expression. 8799 if (Info.checkingPotentialConstantExpression()) 8800 return false; 8801 if (!Info.CurrentCall->This) { 8802 if (Info.getLangOpts().CPlusPlus11) 8803 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8804 else 8805 Info.FFDiag(E); 8806 return false; 8807 } 8808 Result = *Info.CurrentCall->This; 8809 8810 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8811 // Ensure we actually have captured 'this'. If something was wrong with 8812 // 'this' capture, the error would have been previously reported. 8813 // Otherwise we can be inside of a default initialization of an object 8814 // declared by lambda's body, so no need to return false. 8815 if (!Info.CurrentCall->LambdaThisCaptureField) 8816 return true; 8817 8818 // If we have captured 'this', the 'this' expression refers 8819 // to the enclosing '*this' object (either by value or reference) which is 8820 // either copied into the closure object's field that represents the 8821 // '*this' or refers to '*this'. 8822 // Update 'Result' to refer to the data member/field of the closure object 8823 // that represents the '*this' capture. 8824 if (!HandleLValueMember(Info, E, Result, 8825 Info.CurrentCall->LambdaThisCaptureField)) 8826 return false; 8827 // If we captured '*this' by reference, replace the field with its referent. 8828 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8829 ->isPointerType()) { 8830 APValue RVal; 8831 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8832 RVal)) 8833 return false; 8834 8835 Result.setFrom(Info.Ctx, RVal); 8836 } 8837 } 8838 return true; 8839 } 8840 8841 bool VisitCXXNewExpr(const CXXNewExpr *E); 8842 8843 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8844 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?"); 8845 APValue LValResult = E->EvaluateInContext( 8846 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8847 Result.setFrom(Info.Ctx, LValResult); 8848 return true; 8849 } 8850 8851 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8852 std::string ResultStr = E->ComputeName(Info.Ctx); 8853 8854 QualType CharTy = Info.Ctx.CharTy.withConst(); 8855 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8856 ResultStr.size() + 1); 8857 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8858 ArrayType::Normal, 0); 8859 8860 StringLiteral *SL = 8861 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary, 8862 /*Pascal*/ false, ArrayTy, E->getLocation()); 8863 8864 evaluateLValue(SL, Result); 8865 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8866 return true; 8867 } 8868 8869 // FIXME: Missing: @protocol, @selector 8870 }; 8871 } // end anonymous namespace 8872 8873 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8874 bool InvalidBaseOK) { 8875 assert(!E->isValueDependent()); 8876 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8877 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8878 } 8879 8880 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8881 if (E->getOpcode() != BO_Add && 8882 E->getOpcode() != BO_Sub) 8883 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8884 8885 const Expr *PExp = E->getLHS(); 8886 const Expr *IExp = E->getRHS(); 8887 if (IExp->getType()->isPointerType()) 8888 std::swap(PExp, IExp); 8889 8890 bool EvalPtrOK = evaluatePointer(PExp, Result); 8891 if (!EvalPtrOK && !Info.noteFailure()) 8892 return false; 8893 8894 llvm::APSInt Offset; 8895 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8896 return false; 8897 8898 if (E->getOpcode() == BO_Sub) 8899 negateAsSigned(Offset); 8900 8901 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8902 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8903 } 8904 8905 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8906 return evaluateLValue(E->getSubExpr(), Result); 8907 } 8908 8909 // Is the provided decl 'std::source_location::current'? 8910 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) { 8911 if (!FD) 8912 return false; 8913 const IdentifierInfo *FnII = FD->getIdentifier(); 8914 if (!FnII || !FnII->isStr("current")) 8915 return false; 8916 8917 const auto *RD = dyn_cast<RecordDecl>(FD->getParent()); 8918 if (!RD) 8919 return false; 8920 8921 const IdentifierInfo *ClassII = RD->getIdentifier(); 8922 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location"); 8923 } 8924 8925 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8926 const Expr *SubExpr = E->getSubExpr(); 8927 8928 switch (E->getCastKind()) { 8929 default: 8930 break; 8931 case CK_BitCast: 8932 case CK_CPointerToObjCPointerCast: 8933 case CK_BlockPointerToObjCPointerCast: 8934 case CK_AnyPointerToBlockPointerCast: 8935 case CK_AddressSpaceConversion: 8936 if (!Visit(SubExpr)) 8937 return false; 8938 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8939 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8940 // also static_casts, but we disallow them as a resolution to DR1312. 8941 if (!E->getType()->isVoidPointerType()) { 8942 // In some circumstances, we permit casting from void* to cv1 T*, when the 8943 // actual pointee object is actually a cv2 T. 8944 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid && 8945 !Result.IsNullPtr; 8946 bool VoidPtrCastMaybeOK = 8947 HasValidResult && 8948 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8949 E->getType()->getPointeeType()); 8950 // 1. We'll allow it in std::allocator::allocate, and anything which that 8951 // calls. 8952 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s 8953 // <source_location> header. Fixed in GCC 12 and later (2022-04-??). 8954 // We'll allow it in the body of std::source_location::current. GCC's 8955 // implementation had a parameter of type `void*`, and casts from 8956 // that back to `const __impl*` in its body. 8957 if (VoidPtrCastMaybeOK && 8958 (Info.getStdAllocatorCaller("allocate") || 8959 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) || 8960 Info.getLangOpts().CPlusPlus26)) { 8961 // Permitted. 8962 } else { 8963 if (SubExpr->getType()->isVoidPointerType()) { 8964 if (HasValidResult) 8965 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast) 8966 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26 8967 << Result.Designator.getType(Info.Ctx).getCanonicalType() 8968 << E->getType()->getPointeeType(); 8969 else 8970 CCEDiag(E, diag::note_constexpr_invalid_cast) 8971 << 3 << SubExpr->getType(); 8972 } else 8973 CCEDiag(E, diag::note_constexpr_invalid_cast) 8974 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 8975 Result.Designator.setInvalid(); 8976 } 8977 } 8978 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8979 ZeroInitialization(E); 8980 return true; 8981 8982 case CK_DerivedToBase: 8983 case CK_UncheckedDerivedToBase: 8984 if (!evaluatePointer(E->getSubExpr(), Result)) 8985 return false; 8986 if (!Result.Base && Result.Offset.isZero()) 8987 return true; 8988 8989 // Now figure out the necessary offset to add to the base LV to get from 8990 // the derived class to the base class. 8991 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8992 castAs<PointerType>()->getPointeeType(), 8993 Result); 8994 8995 case CK_BaseToDerived: 8996 if (!Visit(E->getSubExpr())) 8997 return false; 8998 if (!Result.Base && Result.Offset.isZero()) 8999 return true; 9000 return HandleBaseToDerivedCast(Info, E, Result); 9001 9002 case CK_Dynamic: 9003 if (!Visit(E->getSubExpr())) 9004 return false; 9005 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 9006 9007 case CK_NullToPointer: 9008 VisitIgnoredValue(E->getSubExpr()); 9009 return ZeroInitialization(E); 9010 9011 case CK_IntegralToPointer: { 9012 CCEDiag(E, diag::note_constexpr_invalid_cast) 9013 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 9014 9015 APValue Value; 9016 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 9017 break; 9018 9019 if (Value.isInt()) { 9020 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 9021 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 9022 Result.Base = (Expr*)nullptr; 9023 Result.InvalidBase = false; 9024 Result.Offset = CharUnits::fromQuantity(N); 9025 Result.Designator.setInvalid(); 9026 Result.IsNullPtr = false; 9027 return true; 9028 } else { 9029 // Cast is of an lvalue, no need to change value. 9030 Result.setFrom(Info.Ctx, Value); 9031 return true; 9032 } 9033 } 9034 9035 case CK_ArrayToPointerDecay: { 9036 if (SubExpr->isGLValue()) { 9037 if (!evaluateLValue(SubExpr, Result)) 9038 return false; 9039 } else { 9040 APValue &Value = Info.CurrentCall->createTemporary( 9041 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 9042 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 9043 return false; 9044 } 9045 // The result is a pointer to the first element of the array. 9046 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 9047 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 9048 Result.addArray(Info, E, CAT); 9049 else 9050 Result.addUnsizedArray(Info, E, AT->getElementType()); 9051 return true; 9052 } 9053 9054 case CK_FunctionToPointerDecay: 9055 return evaluateLValue(SubExpr, Result); 9056 9057 case CK_LValueToRValue: { 9058 LValue LVal; 9059 if (!evaluateLValue(E->getSubExpr(), LVal)) 9060 return false; 9061 9062 APValue RVal; 9063 // Note, we use the subexpression's type in order to retain cv-qualifiers. 9064 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 9065 LVal, RVal)) 9066 return InvalidBaseOK && 9067 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 9068 return Success(RVal, E); 9069 } 9070 } 9071 9072 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9073 } 9074 9075 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 9076 UnaryExprOrTypeTrait ExprKind) { 9077 // C++ [expr.alignof]p3: 9078 // When alignof is applied to a reference type, the result is the 9079 // alignment of the referenced type. 9080 T = T.getNonReferenceType(); 9081 9082 if (T.getQualifiers().hasUnaligned()) 9083 return CharUnits::One(); 9084 9085 const bool AlignOfReturnsPreferred = 9086 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 9087 9088 // __alignof is defined to return the preferred alignment. 9089 // Before 8, clang returned the preferred alignment for alignof and _Alignof 9090 // as well. 9091 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 9092 return Info.Ctx.toCharUnitsFromBits( 9093 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 9094 // alignof and _Alignof are defined to return the ABI alignment. 9095 else if (ExprKind == UETT_AlignOf) 9096 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 9097 else 9098 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 9099 } 9100 9101 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 9102 UnaryExprOrTypeTrait ExprKind) { 9103 E = E->IgnoreParens(); 9104 9105 // The kinds of expressions that we have special-case logic here for 9106 // should be kept up to date with the special checks for those 9107 // expressions in Sema. 9108 9109 // alignof decl is always accepted, even if it doesn't make sense: we default 9110 // to 1 in those cases. 9111 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 9112 return Info.Ctx.getDeclAlign(DRE->getDecl(), 9113 /*RefAsPointee*/true); 9114 9115 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 9116 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 9117 /*RefAsPointee*/true); 9118 9119 return GetAlignOfType(Info, E->getType(), ExprKind); 9120 } 9121 9122 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 9123 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 9124 return Info.Ctx.getDeclAlign(VD); 9125 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 9126 return GetAlignOfExpr(Info, E, UETT_AlignOf); 9127 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 9128 } 9129 9130 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 9131 /// __builtin_is_aligned and __builtin_assume_aligned. 9132 static bool getAlignmentArgument(const Expr *E, QualType ForType, 9133 EvalInfo &Info, APSInt &Alignment) { 9134 if (!EvaluateInteger(E, Alignment, Info)) 9135 return false; 9136 if (Alignment < 0 || !Alignment.isPowerOf2()) { 9137 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 9138 return false; 9139 } 9140 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 9141 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 9142 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 9143 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 9144 << MaxValue << ForType << Alignment; 9145 return false; 9146 } 9147 // Ensure both alignment and source value have the same bit width so that we 9148 // don't assert when computing the resulting value. 9149 APSInt ExtAlignment = 9150 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 9151 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 9152 "Alignment should not be changed by ext/trunc"); 9153 Alignment = ExtAlignment; 9154 assert(Alignment.getBitWidth() == SrcWidth); 9155 return true; 9156 } 9157 9158 // To be clear: this happily visits unsupported builtins. Better name welcomed. 9159 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 9160 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 9161 return true; 9162 9163 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 9164 return false; 9165 9166 Result.setInvalid(E); 9167 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 9168 Result.addUnsizedArray(Info, E, PointeeTy); 9169 return true; 9170 } 9171 9172 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 9173 if (!IsConstantEvaluatedBuiltinCall(E)) 9174 return visitNonBuiltinCallExpr(E); 9175 return VisitBuiltinCallExpr(E, E->getBuiltinCallee()); 9176 } 9177 9178 // Determine if T is a character type for which we guarantee that 9179 // sizeof(T) == 1. 9180 static bool isOneByteCharacterType(QualType T) { 9181 return T->isCharType() || T->isChar8Type(); 9182 } 9183 9184 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9185 unsigned BuiltinOp) { 9186 if (IsNoOpCall(E)) 9187 return Success(E); 9188 9189 switch (BuiltinOp) { 9190 case Builtin::BIaddressof: 9191 case Builtin::BI__addressof: 9192 case Builtin::BI__builtin_addressof: 9193 return evaluateLValue(E->getArg(0), Result); 9194 case Builtin::BI__builtin_assume_aligned: { 9195 // We need to be very careful here because: if the pointer does not have the 9196 // asserted alignment, then the behavior is undefined, and undefined 9197 // behavior is non-constant. 9198 if (!evaluatePointer(E->getArg(0), Result)) 9199 return false; 9200 9201 LValue OffsetResult(Result); 9202 APSInt Alignment; 9203 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9204 Alignment)) 9205 return false; 9206 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9207 9208 if (E->getNumArgs() > 2) { 9209 APSInt Offset; 9210 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9211 return false; 9212 9213 int64_t AdditionalOffset = -Offset.getZExtValue(); 9214 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9215 } 9216 9217 // If there is a base object, then it must have the correct alignment. 9218 if (OffsetResult.Base) { 9219 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9220 9221 if (BaseAlignment < Align) { 9222 Result.Designator.setInvalid(); 9223 // FIXME: Add support to Diagnostic for long / long long. 9224 CCEDiag(E->getArg(0), 9225 diag::note_constexpr_baa_insufficient_alignment) << 0 9226 << (unsigned)BaseAlignment.getQuantity() 9227 << (unsigned)Align.getQuantity(); 9228 return false; 9229 } 9230 } 9231 9232 // The offset must also have the correct alignment. 9233 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9234 Result.Designator.setInvalid(); 9235 9236 (OffsetResult.Base 9237 ? CCEDiag(E->getArg(0), 9238 diag::note_constexpr_baa_insufficient_alignment) << 1 9239 : CCEDiag(E->getArg(0), 9240 diag::note_constexpr_baa_value_insufficient_alignment)) 9241 << (int)OffsetResult.Offset.getQuantity() 9242 << (unsigned)Align.getQuantity(); 9243 return false; 9244 } 9245 9246 return true; 9247 } 9248 case Builtin::BI__builtin_align_up: 9249 case Builtin::BI__builtin_align_down: { 9250 if (!evaluatePointer(E->getArg(0), Result)) 9251 return false; 9252 APSInt Alignment; 9253 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9254 Alignment)) 9255 return false; 9256 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9257 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9258 // For align_up/align_down, we can return the same value if the alignment 9259 // is known to be greater or equal to the requested value. 9260 if (PtrAlign.getQuantity() >= Alignment) 9261 return true; 9262 9263 // The alignment could be greater than the minimum at run-time, so we cannot 9264 // infer much about the resulting pointer value. One case is possible: 9265 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9266 // can infer the correct index if the requested alignment is smaller than 9267 // the base alignment so we can perform the computation on the offset. 9268 if (BaseAlignment.getQuantity() >= Alignment) { 9269 assert(Alignment.getBitWidth() <= 64 && 9270 "Cannot handle > 64-bit address-space"); 9271 uint64_t Alignment64 = Alignment.getZExtValue(); 9272 CharUnits NewOffset = CharUnits::fromQuantity( 9273 BuiltinOp == Builtin::BI__builtin_align_down 9274 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9275 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9276 Result.adjustOffset(NewOffset - Result.Offset); 9277 // TODO: diagnose out-of-bounds values/only allow for arrays? 9278 return true; 9279 } 9280 // Otherwise, we cannot constant-evaluate the result. 9281 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9282 << Alignment; 9283 return false; 9284 } 9285 case Builtin::BI__builtin_operator_new: 9286 return HandleOperatorNewCall(Info, E, Result); 9287 case Builtin::BI__builtin_launder: 9288 return evaluatePointer(E->getArg(0), Result); 9289 case Builtin::BIstrchr: 9290 case Builtin::BIwcschr: 9291 case Builtin::BImemchr: 9292 case Builtin::BIwmemchr: 9293 if (Info.getLangOpts().CPlusPlus11) 9294 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9295 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 9296 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 9297 else 9298 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9299 [[fallthrough]]; 9300 case Builtin::BI__builtin_strchr: 9301 case Builtin::BI__builtin_wcschr: 9302 case Builtin::BI__builtin_memchr: 9303 case Builtin::BI__builtin_char_memchr: 9304 case Builtin::BI__builtin_wmemchr: { 9305 if (!Visit(E->getArg(0))) 9306 return false; 9307 APSInt Desired; 9308 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9309 return false; 9310 uint64_t MaxLength = uint64_t(-1); 9311 if (BuiltinOp != Builtin::BIstrchr && 9312 BuiltinOp != Builtin::BIwcschr && 9313 BuiltinOp != Builtin::BI__builtin_strchr && 9314 BuiltinOp != Builtin::BI__builtin_wcschr) { 9315 APSInt N; 9316 if (!EvaluateInteger(E->getArg(2), N, Info)) 9317 return false; 9318 MaxLength = N.getExtValue(); 9319 } 9320 // We cannot find the value if there are no candidates to match against. 9321 if (MaxLength == 0u) 9322 return ZeroInitialization(E); 9323 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9324 Result.Designator.Invalid) 9325 return false; 9326 QualType CharTy = Result.Designator.getType(Info.Ctx); 9327 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9328 BuiltinOp == Builtin::BI__builtin_memchr; 9329 assert(IsRawByte || 9330 Info.Ctx.hasSameUnqualifiedType( 9331 CharTy, E->getArg(0)->getType()->getPointeeType())); 9332 // Pointers to const void may point to objects of incomplete type. 9333 if (IsRawByte && CharTy->isIncompleteType()) { 9334 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9335 return false; 9336 } 9337 // Give up on byte-oriented matching against multibyte elements. 9338 // FIXME: We can compare the bytes in the correct order. 9339 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9340 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9341 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str() 9342 << CharTy; 9343 return false; 9344 } 9345 // Figure out what value we're actually looking for (after converting to 9346 // the corresponding unsigned type if necessary). 9347 uint64_t DesiredVal; 9348 bool StopAtNull = false; 9349 switch (BuiltinOp) { 9350 case Builtin::BIstrchr: 9351 case Builtin::BI__builtin_strchr: 9352 // strchr compares directly to the passed integer, and therefore 9353 // always fails if given an int that is not a char. 9354 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9355 E->getArg(1)->getType(), 9356 Desired), 9357 Desired)) 9358 return ZeroInitialization(E); 9359 StopAtNull = true; 9360 [[fallthrough]]; 9361 case Builtin::BImemchr: 9362 case Builtin::BI__builtin_memchr: 9363 case Builtin::BI__builtin_char_memchr: 9364 // memchr compares by converting both sides to unsigned char. That's also 9365 // correct for strchr if we get this far (to cope with plain char being 9366 // unsigned in the strchr case). 9367 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9368 break; 9369 9370 case Builtin::BIwcschr: 9371 case Builtin::BI__builtin_wcschr: 9372 StopAtNull = true; 9373 [[fallthrough]]; 9374 case Builtin::BIwmemchr: 9375 case Builtin::BI__builtin_wmemchr: 9376 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9377 DesiredVal = Desired.getZExtValue(); 9378 break; 9379 } 9380 9381 for (; MaxLength; --MaxLength) { 9382 APValue Char; 9383 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9384 !Char.isInt()) 9385 return false; 9386 if (Char.getInt().getZExtValue() == DesiredVal) 9387 return true; 9388 if (StopAtNull && !Char.getInt()) 9389 break; 9390 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9391 return false; 9392 } 9393 // Not found: return nullptr. 9394 return ZeroInitialization(E); 9395 } 9396 9397 case Builtin::BImemcpy: 9398 case Builtin::BImemmove: 9399 case Builtin::BIwmemcpy: 9400 case Builtin::BIwmemmove: 9401 if (Info.getLangOpts().CPlusPlus11) 9402 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9403 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 9404 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 9405 else 9406 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9407 [[fallthrough]]; 9408 case Builtin::BI__builtin_memcpy: 9409 case Builtin::BI__builtin_memmove: 9410 case Builtin::BI__builtin_wmemcpy: 9411 case Builtin::BI__builtin_wmemmove: { 9412 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9413 BuiltinOp == Builtin::BIwmemmove || 9414 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9415 BuiltinOp == Builtin::BI__builtin_wmemmove; 9416 bool Move = BuiltinOp == Builtin::BImemmove || 9417 BuiltinOp == Builtin::BIwmemmove || 9418 BuiltinOp == Builtin::BI__builtin_memmove || 9419 BuiltinOp == Builtin::BI__builtin_wmemmove; 9420 9421 // The result of mem* is the first argument. 9422 if (!Visit(E->getArg(0))) 9423 return false; 9424 LValue Dest = Result; 9425 9426 LValue Src; 9427 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9428 return false; 9429 9430 APSInt N; 9431 if (!EvaluateInteger(E->getArg(2), N, Info)) 9432 return false; 9433 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9434 9435 // If the size is zero, we treat this as always being a valid no-op. 9436 // (Even if one of the src and dest pointers is null.) 9437 if (!N) 9438 return true; 9439 9440 // Otherwise, if either of the operands is null, we can't proceed. Don't 9441 // try to determine the type of the copied objects, because there aren't 9442 // any. 9443 if (!Src.Base || !Dest.Base) { 9444 APValue Val; 9445 (!Src.Base ? Src : Dest).moveInto(Val); 9446 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9447 << Move << WChar << !!Src.Base 9448 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9449 return false; 9450 } 9451 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9452 return false; 9453 9454 // We require that Src and Dest are both pointers to arrays of 9455 // trivially-copyable type. (For the wide version, the designator will be 9456 // invalid if the designated object is not a wchar_t.) 9457 QualType T = Dest.Designator.getType(Info.Ctx); 9458 QualType SrcT = Src.Designator.getType(Info.Ctx); 9459 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9460 // FIXME: Consider using our bit_cast implementation to support this. 9461 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9462 return false; 9463 } 9464 if (T->isIncompleteType()) { 9465 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9466 return false; 9467 } 9468 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9469 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9470 return false; 9471 } 9472 9473 // Figure out how many T's we're copying. 9474 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9475 if (!WChar) { 9476 uint64_t Remainder; 9477 llvm::APInt OrigN = N; 9478 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9479 if (Remainder) { 9480 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9481 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9482 << (unsigned)TSize; 9483 return false; 9484 } 9485 } 9486 9487 // Check that the copying will remain within the arrays, just so that we 9488 // can give a more meaningful diagnostic. This implicitly also checks that 9489 // N fits into 64 bits. 9490 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9491 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9492 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9493 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9494 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9495 << toString(N, 10, /*Signed*/false); 9496 return false; 9497 } 9498 uint64_t NElems = N.getZExtValue(); 9499 uint64_t NBytes = NElems * TSize; 9500 9501 // Check for overlap. 9502 int Direction = 1; 9503 if (HasSameBase(Src, Dest)) { 9504 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9505 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9506 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9507 // Dest is inside the source region. 9508 if (!Move) { 9509 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9510 return false; 9511 } 9512 // For memmove and friends, copy backwards. 9513 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9514 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9515 return false; 9516 Direction = -1; 9517 } else if (!Move && SrcOffset >= DestOffset && 9518 SrcOffset - DestOffset < NBytes) { 9519 // Src is inside the destination region for memcpy: invalid. 9520 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9521 return false; 9522 } 9523 } 9524 9525 while (true) { 9526 APValue Val; 9527 // FIXME: Set WantObjectRepresentation to true if we're copying a 9528 // char-like type? 9529 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9530 !handleAssignment(Info, E, Dest, T, Val)) 9531 return false; 9532 // Do not iterate past the last element; if we're copying backwards, that 9533 // might take us off the start of the array. 9534 if (--NElems == 0) 9535 return true; 9536 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9537 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9538 return false; 9539 } 9540 } 9541 9542 default: 9543 return false; 9544 } 9545 } 9546 9547 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9548 APValue &Result, const InitListExpr *ILE, 9549 QualType AllocType); 9550 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9551 APValue &Result, 9552 const CXXConstructExpr *CCE, 9553 QualType AllocType); 9554 9555 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9556 if (!Info.getLangOpts().CPlusPlus20) 9557 Info.CCEDiag(E, diag::note_constexpr_new); 9558 9559 // We cannot speculatively evaluate a delete expression. 9560 if (Info.SpeculativeEvaluationDepth) 9561 return false; 9562 9563 FunctionDecl *OperatorNew = E->getOperatorNew(); 9564 9565 bool IsNothrow = false; 9566 bool IsPlacement = false; 9567 if (OperatorNew->isReservedGlobalPlacementOperator() && 9568 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9569 // FIXME Support array placement new. 9570 assert(E->getNumPlacementArgs() == 1); 9571 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9572 return false; 9573 if (Result.Designator.Invalid) 9574 return false; 9575 IsPlacement = true; 9576 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9577 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9578 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9579 return false; 9580 } else if (E->getNumPlacementArgs()) { 9581 // The only new-placement list we support is of the form (std::nothrow). 9582 // 9583 // FIXME: There is no restriction on this, but it's not clear that any 9584 // other form makes any sense. We get here for cases such as: 9585 // 9586 // new (std::align_val_t{N}) X(int) 9587 // 9588 // (which should presumably be valid only if N is a multiple of 9589 // alignof(int), and in any case can't be deallocated unless N is 9590 // alignof(X) and X has new-extended alignment). 9591 if (E->getNumPlacementArgs() != 1 || 9592 !E->getPlacementArg(0)->getType()->isNothrowT()) 9593 return Error(E, diag::note_constexpr_new_placement); 9594 9595 LValue Nothrow; 9596 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9597 return false; 9598 IsNothrow = true; 9599 } 9600 9601 const Expr *Init = E->getInitializer(); 9602 const InitListExpr *ResizedArrayILE = nullptr; 9603 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9604 bool ValueInit = false; 9605 9606 QualType AllocType = E->getAllocatedType(); 9607 if (std::optional<const Expr *> ArraySize = E->getArraySize()) { 9608 const Expr *Stripped = *ArraySize; 9609 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9610 Stripped = ICE->getSubExpr()) 9611 if (ICE->getCastKind() != CK_NoOp && 9612 ICE->getCastKind() != CK_IntegralCast) 9613 break; 9614 9615 llvm::APSInt ArrayBound; 9616 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9617 return false; 9618 9619 // C++ [expr.new]p9: 9620 // The expression is erroneous if: 9621 // -- [...] its value before converting to size_t [or] applying the 9622 // second standard conversion sequence is less than zero 9623 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9624 if (IsNothrow) 9625 return ZeroInitialization(E); 9626 9627 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9628 << ArrayBound << (*ArraySize)->getSourceRange(); 9629 return false; 9630 } 9631 9632 // -- its value is such that the size of the allocated object would 9633 // exceed the implementation-defined limit 9634 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9635 ArrayBound) > 9636 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9637 if (IsNothrow) 9638 return ZeroInitialization(E); 9639 9640 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9641 << ArrayBound << (*ArraySize)->getSourceRange(); 9642 return false; 9643 } 9644 9645 // -- the new-initializer is a braced-init-list and the number of 9646 // array elements for which initializers are provided [...] 9647 // exceeds the number of elements to initialize 9648 if (!Init) { 9649 // No initialization is performed. 9650 } else if (isa<CXXScalarValueInitExpr>(Init) || 9651 isa<ImplicitValueInitExpr>(Init)) { 9652 ValueInit = true; 9653 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9654 ResizedArrayCCE = CCE; 9655 } else { 9656 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9657 assert(CAT && "unexpected type for array initializer"); 9658 9659 unsigned Bits = 9660 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9661 llvm::APInt InitBound = CAT->getSize().zext(Bits); 9662 llvm::APInt AllocBound = ArrayBound.zext(Bits); 9663 if (InitBound.ugt(AllocBound)) { 9664 if (IsNothrow) 9665 return ZeroInitialization(E); 9666 9667 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9668 << toString(AllocBound, 10, /*Signed=*/false) 9669 << toString(InitBound, 10, /*Signed=*/false) 9670 << (*ArraySize)->getSourceRange(); 9671 return false; 9672 } 9673 9674 // If the sizes differ, we must have an initializer list, and we need 9675 // special handling for this case when we initialize. 9676 if (InitBound != AllocBound) 9677 ResizedArrayILE = cast<InitListExpr>(Init); 9678 } 9679 9680 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9681 ArrayType::Normal, 0); 9682 } else { 9683 assert(!AllocType->isArrayType() && 9684 "array allocation with non-array new"); 9685 } 9686 9687 APValue *Val; 9688 if (IsPlacement) { 9689 AccessKinds AK = AK_Construct; 9690 struct FindObjectHandler { 9691 EvalInfo &Info; 9692 const Expr *E; 9693 QualType AllocType; 9694 const AccessKinds AccessKind; 9695 APValue *Value; 9696 9697 typedef bool result_type; 9698 bool failed() { return false; } 9699 bool found(APValue &Subobj, QualType SubobjType) { 9700 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9701 // old name of the object to be used to name the new object. 9702 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9703 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9704 SubobjType << AllocType; 9705 return false; 9706 } 9707 Value = &Subobj; 9708 return true; 9709 } 9710 bool found(APSInt &Value, QualType SubobjType) { 9711 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9712 return false; 9713 } 9714 bool found(APFloat &Value, QualType SubobjType) { 9715 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9716 return false; 9717 } 9718 } Handler = {Info, E, AllocType, AK, nullptr}; 9719 9720 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9721 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9722 return false; 9723 9724 Val = Handler.Value; 9725 9726 // [basic.life]p1: 9727 // The lifetime of an object o of type T ends when [...] the storage 9728 // which the object occupies is [...] reused by an object that is not 9729 // nested within o (6.6.2). 9730 *Val = APValue(); 9731 } else { 9732 // Perform the allocation and obtain a pointer to the resulting object. 9733 Val = Info.createHeapAlloc(E, AllocType, Result); 9734 if (!Val) 9735 return false; 9736 } 9737 9738 if (ValueInit) { 9739 ImplicitValueInitExpr VIE(AllocType); 9740 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9741 return false; 9742 } else if (ResizedArrayILE) { 9743 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9744 AllocType)) 9745 return false; 9746 } else if (ResizedArrayCCE) { 9747 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9748 AllocType)) 9749 return false; 9750 } else if (Init) { 9751 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9752 return false; 9753 } else if (!getDefaultInitValue(AllocType, *Val)) { 9754 return false; 9755 } 9756 9757 // Array new returns a pointer to the first element, not a pointer to the 9758 // array. 9759 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9760 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9761 9762 return true; 9763 } 9764 //===----------------------------------------------------------------------===// 9765 // Member Pointer Evaluation 9766 //===----------------------------------------------------------------------===// 9767 9768 namespace { 9769 class MemberPointerExprEvaluator 9770 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9771 MemberPtr &Result; 9772 9773 bool Success(const ValueDecl *D) { 9774 Result = MemberPtr(D); 9775 return true; 9776 } 9777 public: 9778 9779 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9780 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9781 9782 bool Success(const APValue &V, const Expr *E) { 9783 Result.setFrom(V); 9784 return true; 9785 } 9786 bool ZeroInitialization(const Expr *E) { 9787 return Success((const ValueDecl*)nullptr); 9788 } 9789 9790 bool VisitCastExpr(const CastExpr *E); 9791 bool VisitUnaryAddrOf(const UnaryOperator *E); 9792 }; 9793 } // end anonymous namespace 9794 9795 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9796 EvalInfo &Info) { 9797 assert(!E->isValueDependent()); 9798 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9799 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9800 } 9801 9802 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9803 switch (E->getCastKind()) { 9804 default: 9805 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9806 9807 case CK_NullToMemberPointer: 9808 VisitIgnoredValue(E->getSubExpr()); 9809 return ZeroInitialization(E); 9810 9811 case CK_BaseToDerivedMemberPointer: { 9812 if (!Visit(E->getSubExpr())) 9813 return false; 9814 if (E->path_empty()) 9815 return true; 9816 // Base-to-derived member pointer casts store the path in derived-to-base 9817 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9818 // the wrong end of the derived->base arc, so stagger the path by one class. 9819 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9820 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9821 PathI != PathE; ++PathI) { 9822 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9823 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9824 if (!Result.castToDerived(Derived)) 9825 return Error(E); 9826 } 9827 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9828 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9829 return Error(E); 9830 return true; 9831 } 9832 9833 case CK_DerivedToBaseMemberPointer: 9834 if (!Visit(E->getSubExpr())) 9835 return false; 9836 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9837 PathE = E->path_end(); PathI != PathE; ++PathI) { 9838 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9839 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9840 if (!Result.castToBase(Base)) 9841 return Error(E); 9842 } 9843 return true; 9844 } 9845 } 9846 9847 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9848 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9849 // member can be formed. 9850 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9851 } 9852 9853 //===----------------------------------------------------------------------===// 9854 // Record Evaluation 9855 //===----------------------------------------------------------------------===// 9856 9857 namespace { 9858 class RecordExprEvaluator 9859 : public ExprEvaluatorBase<RecordExprEvaluator> { 9860 const LValue &This; 9861 APValue &Result; 9862 public: 9863 9864 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9865 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9866 9867 bool Success(const APValue &V, const Expr *E) { 9868 Result = V; 9869 return true; 9870 } 9871 bool ZeroInitialization(const Expr *E) { 9872 return ZeroInitialization(E, E->getType()); 9873 } 9874 bool ZeroInitialization(const Expr *E, QualType T); 9875 9876 bool VisitCallExpr(const CallExpr *E) { 9877 return handleCallExpr(E, Result, &This); 9878 } 9879 bool VisitCastExpr(const CastExpr *E); 9880 bool VisitInitListExpr(const InitListExpr *E); 9881 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9882 return VisitCXXConstructExpr(E, E->getType()); 9883 } 9884 bool VisitLambdaExpr(const LambdaExpr *E); 9885 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9886 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9887 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9888 bool VisitBinCmp(const BinaryOperator *E); 9889 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); 9890 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, 9891 ArrayRef<Expr *> Args); 9892 }; 9893 } 9894 9895 /// Perform zero-initialization on an object of non-union class type. 9896 /// C++11 [dcl.init]p5: 9897 /// To zero-initialize an object or reference of type T means: 9898 /// [...] 9899 /// -- if T is a (possibly cv-qualified) non-union class type, 9900 /// each non-static data member and each base-class subobject is 9901 /// zero-initialized 9902 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9903 const RecordDecl *RD, 9904 const LValue &This, APValue &Result) { 9905 assert(!RD->isUnion() && "Expected non-union class type"); 9906 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9907 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9908 std::distance(RD->field_begin(), RD->field_end())); 9909 9910 if (RD->isInvalidDecl()) return false; 9911 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9912 9913 if (CD) { 9914 unsigned Index = 0; 9915 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9916 End = CD->bases_end(); I != End; ++I, ++Index) { 9917 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9918 LValue Subobject = This; 9919 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9920 return false; 9921 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9922 Result.getStructBase(Index))) 9923 return false; 9924 } 9925 } 9926 9927 for (const auto *I : RD->fields()) { 9928 // -- if T is a reference type, no initialization is performed. 9929 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9930 continue; 9931 9932 LValue Subobject = This; 9933 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9934 return false; 9935 9936 ImplicitValueInitExpr VIE(I->getType()); 9937 if (!EvaluateInPlace( 9938 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9939 return false; 9940 } 9941 9942 return true; 9943 } 9944 9945 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9946 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9947 if (RD->isInvalidDecl()) return false; 9948 if (RD->isUnion()) { 9949 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9950 // object's first non-static named data member is zero-initialized 9951 RecordDecl::field_iterator I = RD->field_begin(); 9952 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9953 ++I; 9954 if (I == RD->field_end()) { 9955 Result = APValue((const FieldDecl*)nullptr); 9956 return true; 9957 } 9958 9959 LValue Subobject = This; 9960 if (!HandleLValueMember(Info, E, Subobject, *I)) 9961 return false; 9962 Result = APValue(*I); 9963 ImplicitValueInitExpr VIE(I->getType()); 9964 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9965 } 9966 9967 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9968 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9969 return false; 9970 } 9971 9972 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9973 } 9974 9975 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9976 switch (E->getCastKind()) { 9977 default: 9978 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9979 9980 case CK_ConstructorConversion: 9981 return Visit(E->getSubExpr()); 9982 9983 case CK_DerivedToBase: 9984 case CK_UncheckedDerivedToBase: { 9985 APValue DerivedObject; 9986 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9987 return false; 9988 if (!DerivedObject.isStruct()) 9989 return Error(E->getSubExpr()); 9990 9991 // Derived-to-base rvalue conversion: just slice off the derived part. 9992 APValue *Value = &DerivedObject; 9993 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9994 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9995 PathE = E->path_end(); PathI != PathE; ++PathI) { 9996 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9997 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9998 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9999 RD = Base; 10000 } 10001 Result = *Value; 10002 return true; 10003 } 10004 } 10005 } 10006 10007 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10008 if (E->isTransparent()) 10009 return Visit(E->getInit(0)); 10010 return VisitCXXParenListOrInitListExpr(E, E->inits()); 10011 } 10012 10013 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr( 10014 const Expr *ExprToVisit, ArrayRef<Expr *> Args) { 10015 const RecordDecl *RD = 10016 ExprToVisit->getType()->castAs<RecordType>()->getDecl(); 10017 if (RD->isInvalidDecl()) return false; 10018 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 10019 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 10020 10021 EvalInfo::EvaluatingConstructorRAII EvalObj( 10022 Info, 10023 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 10024 CXXRD && CXXRD->getNumBases()); 10025 10026 if (RD->isUnion()) { 10027 const FieldDecl *Field; 10028 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) { 10029 Field = ILE->getInitializedFieldInUnion(); 10030 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) { 10031 Field = PLIE->getInitializedFieldInUnion(); 10032 } else { 10033 llvm_unreachable( 10034 "Expression is neither an init list nor a C++ paren list"); 10035 } 10036 10037 Result = APValue(Field); 10038 if (!Field) 10039 return true; 10040 10041 // If the initializer list for a union does not contain any elements, the 10042 // first element of the union is value-initialized. 10043 // FIXME: The element should be initialized from an initializer list. 10044 // Is this difference ever observable for initializer lists which 10045 // we don't build? 10046 ImplicitValueInitExpr VIE(Field->getType()); 10047 const Expr *InitExpr = Args.empty() ? &VIE : Args[0]; 10048 10049 LValue Subobject = This; 10050 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 10051 return false; 10052 10053 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 10054 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 10055 isa<CXXDefaultInitExpr>(InitExpr)); 10056 10057 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 10058 if (Field->isBitField()) 10059 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 10060 Field); 10061 return true; 10062 } 10063 10064 return false; 10065 } 10066 10067 if (!Result.hasValue()) 10068 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 10069 std::distance(RD->field_begin(), RD->field_end())); 10070 unsigned ElementNo = 0; 10071 bool Success = true; 10072 10073 // Initialize base classes. 10074 if (CXXRD && CXXRD->getNumBases()) { 10075 for (const auto &Base : CXXRD->bases()) { 10076 assert(ElementNo < Args.size() && "missing init for base class"); 10077 const Expr *Init = Args[ElementNo]; 10078 10079 LValue Subobject = This; 10080 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 10081 return false; 10082 10083 APValue &FieldVal = Result.getStructBase(ElementNo); 10084 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 10085 if (!Info.noteFailure()) 10086 return false; 10087 Success = false; 10088 } 10089 ++ElementNo; 10090 } 10091 10092 EvalObj.finishedConstructingBases(); 10093 } 10094 10095 // Initialize members. 10096 for (const auto *Field : RD->fields()) { 10097 // Anonymous bit-fields are not considered members of the class for 10098 // purposes of aggregate initialization. 10099 if (Field->isUnnamedBitfield()) 10100 continue; 10101 10102 LValue Subobject = This; 10103 10104 bool HaveInit = ElementNo < Args.size(); 10105 10106 // FIXME: Diagnostics here should point to the end of the initializer 10107 // list, not the start. 10108 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit, 10109 Subobject, Field, &Layout)) 10110 return false; 10111 10112 // Perform an implicit value-initialization for members beyond the end of 10113 // the initializer list. 10114 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 10115 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE; 10116 10117 if (Field->getType()->isIncompleteArrayType()) { 10118 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) { 10119 if (!CAT->getSize().isZero()) { 10120 // Bail out for now. This might sort of "work", but the rest of the 10121 // code isn't really prepared to handle it. 10122 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array); 10123 return false; 10124 } 10125 } 10126 } 10127 10128 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 10129 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 10130 isa<CXXDefaultInitExpr>(Init)); 10131 10132 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10133 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 10134 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 10135 FieldVal, Field))) { 10136 if (!Info.noteFailure()) 10137 return false; 10138 Success = false; 10139 } 10140 } 10141 10142 EvalObj.finishedConstructingFields(); 10143 10144 return Success; 10145 } 10146 10147 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10148 QualType T) { 10149 // Note that E's type is not necessarily the type of our class here; we might 10150 // be initializing an array element instead. 10151 const CXXConstructorDecl *FD = E->getConstructor(); 10152 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 10153 10154 bool ZeroInit = E->requiresZeroInitialization(); 10155 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 10156 // If we've already performed zero-initialization, we're already done. 10157 if (Result.hasValue()) 10158 return true; 10159 10160 if (ZeroInit) 10161 return ZeroInitialization(E, T); 10162 10163 return getDefaultInitValue(T, Result); 10164 } 10165 10166 const FunctionDecl *Definition = nullptr; 10167 auto Body = FD->getBody(Definition); 10168 10169 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10170 return false; 10171 10172 // Avoid materializing a temporary for an elidable copy/move constructor. 10173 if (E->isElidable() && !ZeroInit) { 10174 // FIXME: This only handles the simplest case, where the source object 10175 // is passed directly as the first argument to the constructor. 10176 // This should also handle stepping though implicit casts and 10177 // and conversion sequences which involve two steps, with a 10178 // conversion operator followed by a converting constructor. 10179 const Expr *SrcObj = E->getArg(0); 10180 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 10181 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 10182 if (const MaterializeTemporaryExpr *ME = 10183 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 10184 return Visit(ME->getSubExpr()); 10185 } 10186 10187 if (ZeroInit && !ZeroInitialization(E, T)) 10188 return false; 10189 10190 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs()); 10191 return HandleConstructorCall(E, This, Args, 10192 cast<CXXConstructorDecl>(Definition), Info, 10193 Result); 10194 } 10195 10196 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 10197 const CXXInheritedCtorInitExpr *E) { 10198 if (!Info.CurrentCall) { 10199 assert(Info.checkingPotentialConstantExpression()); 10200 return false; 10201 } 10202 10203 const CXXConstructorDecl *FD = E->getConstructor(); 10204 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 10205 return false; 10206 10207 const FunctionDecl *Definition = nullptr; 10208 auto Body = FD->getBody(Definition); 10209 10210 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10211 return false; 10212 10213 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10214 cast<CXXConstructorDecl>(Definition), Info, 10215 Result); 10216 } 10217 10218 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10219 const CXXStdInitializerListExpr *E) { 10220 const ConstantArrayType *ArrayType = 10221 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10222 10223 LValue Array; 10224 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10225 return false; 10226 10227 assert(ArrayType && "unexpected type for array initializer"); 10228 10229 // Get a pointer to the first element of the array. 10230 Array.addArray(Info, E, ArrayType); 10231 10232 auto InvalidType = [&] { 10233 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10234 << E->getType(); 10235 return false; 10236 }; 10237 10238 // FIXME: Perform the checks on the field types in SemaInit. 10239 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10240 RecordDecl::field_iterator Field = Record->field_begin(); 10241 if (Field == Record->field_end()) 10242 return InvalidType(); 10243 10244 // Start pointer. 10245 if (!Field->getType()->isPointerType() || 10246 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10247 ArrayType->getElementType())) 10248 return InvalidType(); 10249 10250 // FIXME: What if the initializer_list type has base classes, etc? 10251 Result = APValue(APValue::UninitStruct(), 0, 2); 10252 Array.moveInto(Result.getStructField(0)); 10253 10254 if (++Field == Record->field_end()) 10255 return InvalidType(); 10256 10257 if (Field->getType()->isPointerType() && 10258 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10259 ArrayType->getElementType())) { 10260 // End pointer. 10261 if (!HandleLValueArrayAdjustment(Info, E, Array, 10262 ArrayType->getElementType(), 10263 ArrayType->getSize().getZExtValue())) 10264 return false; 10265 Array.moveInto(Result.getStructField(1)); 10266 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10267 // Length. 10268 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10269 else 10270 return InvalidType(); 10271 10272 if (++Field != Record->field_end()) 10273 return InvalidType(); 10274 10275 return true; 10276 } 10277 10278 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10279 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10280 if (ClosureClass->isInvalidDecl()) 10281 return false; 10282 10283 const size_t NumFields = 10284 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10285 10286 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10287 E->capture_init_end()) && 10288 "The number of lambda capture initializers should equal the number of " 10289 "fields within the closure type"); 10290 10291 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10292 // Iterate through all the lambda's closure object's fields and initialize 10293 // them. 10294 auto *CaptureInitIt = E->capture_init_begin(); 10295 bool Success = true; 10296 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10297 for (const auto *Field : ClosureClass->fields()) { 10298 assert(CaptureInitIt != E->capture_init_end()); 10299 // Get the initializer for this field 10300 Expr *const CurFieldInit = *CaptureInitIt++; 10301 10302 // If there is no initializer, either this is a VLA or an error has 10303 // occurred. 10304 if (!CurFieldInit) 10305 return Error(E); 10306 10307 LValue Subobject = This; 10308 10309 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10310 return false; 10311 10312 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10313 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10314 if (!Info.keepEvaluatingAfterFailure()) 10315 return false; 10316 Success = false; 10317 } 10318 } 10319 return Success; 10320 } 10321 10322 static bool EvaluateRecord(const Expr *E, const LValue &This, 10323 APValue &Result, EvalInfo &Info) { 10324 assert(!E->isValueDependent()); 10325 assert(E->isPRValue() && E->getType()->isRecordType() && 10326 "can't evaluate expression as a record rvalue"); 10327 return RecordExprEvaluator(Info, This, Result).Visit(E); 10328 } 10329 10330 //===----------------------------------------------------------------------===// 10331 // Temporary Evaluation 10332 // 10333 // Temporaries are represented in the AST as rvalues, but generally behave like 10334 // lvalues. The full-object of which the temporary is a subobject is implicitly 10335 // materialized so that a reference can bind to it. 10336 //===----------------------------------------------------------------------===// 10337 namespace { 10338 class TemporaryExprEvaluator 10339 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10340 public: 10341 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10342 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10343 10344 /// Visit an expression which constructs the value of this temporary. 10345 bool VisitConstructExpr(const Expr *E) { 10346 APValue &Value = Info.CurrentCall->createTemporary( 10347 E, E->getType(), ScopeKind::FullExpression, Result); 10348 return EvaluateInPlace(Value, Info, Result, E); 10349 } 10350 10351 bool VisitCastExpr(const CastExpr *E) { 10352 switch (E->getCastKind()) { 10353 default: 10354 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10355 10356 case CK_ConstructorConversion: 10357 return VisitConstructExpr(E->getSubExpr()); 10358 } 10359 } 10360 bool VisitInitListExpr(const InitListExpr *E) { 10361 return VisitConstructExpr(E); 10362 } 10363 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10364 return VisitConstructExpr(E); 10365 } 10366 bool VisitCallExpr(const CallExpr *E) { 10367 return VisitConstructExpr(E); 10368 } 10369 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10370 return VisitConstructExpr(E); 10371 } 10372 bool VisitLambdaExpr(const LambdaExpr *E) { 10373 return VisitConstructExpr(E); 10374 } 10375 }; 10376 } // end anonymous namespace 10377 10378 /// Evaluate an expression of record type as a temporary. 10379 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10380 assert(!E->isValueDependent()); 10381 assert(E->isPRValue() && E->getType()->isRecordType()); 10382 return TemporaryExprEvaluator(Info, Result).Visit(E); 10383 } 10384 10385 //===----------------------------------------------------------------------===// 10386 // Vector Evaluation 10387 //===----------------------------------------------------------------------===// 10388 10389 namespace { 10390 class VectorExprEvaluator 10391 : public ExprEvaluatorBase<VectorExprEvaluator> { 10392 APValue &Result; 10393 public: 10394 10395 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10396 : ExprEvaluatorBaseTy(info), Result(Result) {} 10397 10398 bool Success(ArrayRef<APValue> V, const Expr *E) { 10399 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10400 // FIXME: remove this APValue copy. 10401 Result = APValue(V.data(), V.size()); 10402 return true; 10403 } 10404 bool Success(const APValue &V, const Expr *E) { 10405 assert(V.isVector()); 10406 Result = V; 10407 return true; 10408 } 10409 bool ZeroInitialization(const Expr *E); 10410 10411 bool VisitUnaryReal(const UnaryOperator *E) 10412 { return Visit(E->getSubExpr()); } 10413 bool VisitCastExpr(const CastExpr* E); 10414 bool VisitInitListExpr(const InitListExpr *E); 10415 bool VisitUnaryImag(const UnaryOperator *E); 10416 bool VisitBinaryOperator(const BinaryOperator *E); 10417 bool VisitUnaryOperator(const UnaryOperator *E); 10418 // FIXME: Missing: conditional operator (for GNU 10419 // conditional select), shufflevector, ExtVectorElementExpr 10420 }; 10421 } // end anonymous namespace 10422 10423 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10424 assert(E->isPRValue() && E->getType()->isVectorType() && 10425 "not a vector prvalue"); 10426 return VectorExprEvaluator(Info, Result).Visit(E); 10427 } 10428 10429 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10430 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10431 unsigned NElts = VTy->getNumElements(); 10432 10433 const Expr *SE = E->getSubExpr(); 10434 QualType SETy = SE->getType(); 10435 10436 switch (E->getCastKind()) { 10437 case CK_VectorSplat: { 10438 APValue Val = APValue(); 10439 if (SETy->isIntegerType()) { 10440 APSInt IntResult; 10441 if (!EvaluateInteger(SE, IntResult, Info)) 10442 return false; 10443 Val = APValue(std::move(IntResult)); 10444 } else if (SETy->isRealFloatingType()) { 10445 APFloat FloatResult(0.0); 10446 if (!EvaluateFloat(SE, FloatResult, Info)) 10447 return false; 10448 Val = APValue(std::move(FloatResult)); 10449 } else { 10450 return Error(E); 10451 } 10452 10453 // Splat and create vector APValue. 10454 SmallVector<APValue, 4> Elts(NElts, Val); 10455 return Success(Elts, E); 10456 } 10457 case CK_BitCast: { 10458 // Evaluate the operand into an APInt we can extract from. 10459 llvm::APInt SValInt; 10460 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10461 return false; 10462 // Extract the elements 10463 QualType EltTy = VTy->getElementType(); 10464 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10465 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10466 SmallVector<APValue, 4> Elts; 10467 if (EltTy->isRealFloatingType()) { 10468 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10469 unsigned FloatEltSize = EltSize; 10470 if (&Sem == &APFloat::x87DoubleExtended()) 10471 FloatEltSize = 80; 10472 for (unsigned i = 0; i < NElts; i++) { 10473 llvm::APInt Elt; 10474 if (BigEndian) 10475 Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize); 10476 else 10477 Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize); 10478 Elts.push_back(APValue(APFloat(Sem, Elt))); 10479 } 10480 } else if (EltTy->isIntegerType()) { 10481 for (unsigned i = 0; i < NElts; i++) { 10482 llvm::APInt Elt; 10483 if (BigEndian) 10484 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10485 else 10486 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10487 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10488 } 10489 } else { 10490 return Error(E); 10491 } 10492 return Success(Elts, E); 10493 } 10494 default: 10495 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10496 } 10497 } 10498 10499 bool 10500 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10501 const VectorType *VT = E->getType()->castAs<VectorType>(); 10502 unsigned NumInits = E->getNumInits(); 10503 unsigned NumElements = VT->getNumElements(); 10504 10505 QualType EltTy = VT->getElementType(); 10506 SmallVector<APValue, 4> Elements; 10507 10508 // The number of initializers can be less than the number of 10509 // vector elements. For OpenCL, this can be due to nested vector 10510 // initialization. For GCC compatibility, missing trailing elements 10511 // should be initialized with zeroes. 10512 unsigned CountInits = 0, CountElts = 0; 10513 while (CountElts < NumElements) { 10514 // Handle nested vector initialization. 10515 if (CountInits < NumInits 10516 && E->getInit(CountInits)->getType()->isVectorType()) { 10517 APValue v; 10518 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10519 return Error(E); 10520 unsigned vlen = v.getVectorLength(); 10521 for (unsigned j = 0; j < vlen; j++) 10522 Elements.push_back(v.getVectorElt(j)); 10523 CountElts += vlen; 10524 } else if (EltTy->isIntegerType()) { 10525 llvm::APSInt sInt(32); 10526 if (CountInits < NumInits) { 10527 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10528 return false; 10529 } else // trailing integer zero. 10530 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10531 Elements.push_back(APValue(sInt)); 10532 CountElts++; 10533 } else { 10534 llvm::APFloat f(0.0); 10535 if (CountInits < NumInits) { 10536 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10537 return false; 10538 } else // trailing float zero. 10539 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10540 Elements.push_back(APValue(f)); 10541 CountElts++; 10542 } 10543 CountInits++; 10544 } 10545 return Success(Elements, E); 10546 } 10547 10548 bool 10549 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10550 const auto *VT = E->getType()->castAs<VectorType>(); 10551 QualType EltTy = VT->getElementType(); 10552 APValue ZeroElement; 10553 if (EltTy->isIntegerType()) 10554 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10555 else 10556 ZeroElement = 10557 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10558 10559 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10560 return Success(Elements, E); 10561 } 10562 10563 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10564 VisitIgnoredValue(E->getSubExpr()); 10565 return ZeroInitialization(E); 10566 } 10567 10568 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10569 BinaryOperatorKind Op = E->getOpcode(); 10570 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10571 "Operation not supported on vector types"); 10572 10573 if (Op == BO_Comma) 10574 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10575 10576 Expr *LHS = E->getLHS(); 10577 Expr *RHS = E->getRHS(); 10578 10579 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10580 "Must both be vector types"); 10581 // Checking JUST the types are the same would be fine, except shifts don't 10582 // need to have their types be the same (since you always shift by an int). 10583 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10584 E->getType()->castAs<VectorType>()->getNumElements() && 10585 RHS->getType()->castAs<VectorType>()->getNumElements() == 10586 E->getType()->castAs<VectorType>()->getNumElements() && 10587 "All operands must be the same size."); 10588 10589 APValue LHSValue; 10590 APValue RHSValue; 10591 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10592 if (!LHSOK && !Info.noteFailure()) 10593 return false; 10594 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10595 return false; 10596 10597 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10598 return false; 10599 10600 return Success(LHSValue, E); 10601 } 10602 10603 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10604 QualType ResultTy, 10605 UnaryOperatorKind Op, 10606 APValue Elt) { 10607 switch (Op) { 10608 case UO_Plus: 10609 // Nothing to do here. 10610 return Elt; 10611 case UO_Minus: 10612 if (Elt.getKind() == APValue::Int) { 10613 Elt.getInt().negate(); 10614 } else { 10615 assert(Elt.getKind() == APValue::Float && 10616 "Vector can only be int or float type"); 10617 Elt.getFloat().changeSign(); 10618 } 10619 return Elt; 10620 case UO_Not: 10621 // This is only valid for integral types anyway, so we don't have to handle 10622 // float here. 10623 assert(Elt.getKind() == APValue::Int && 10624 "Vector operator ~ can only be int"); 10625 Elt.getInt().flipAllBits(); 10626 return Elt; 10627 case UO_LNot: { 10628 if (Elt.getKind() == APValue::Int) { 10629 Elt.getInt() = !Elt.getInt(); 10630 // operator ! on vectors returns -1 for 'truth', so negate it. 10631 Elt.getInt().negate(); 10632 return Elt; 10633 } 10634 assert(Elt.getKind() == APValue::Float && 10635 "Vector can only be int or float type"); 10636 // Float types result in an int of the same size, but -1 for true, or 0 for 10637 // false. 10638 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10639 ResultTy->isUnsignedIntegerType()}; 10640 if (Elt.getFloat().isZero()) 10641 EltResult.setAllBits(); 10642 else 10643 EltResult.clearAllBits(); 10644 10645 return APValue{EltResult}; 10646 } 10647 default: 10648 // FIXME: Implement the rest of the unary operators. 10649 return std::nullopt; 10650 } 10651 } 10652 10653 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10654 Expr *SubExpr = E->getSubExpr(); 10655 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10656 // This result element type differs in the case of negating a floating point 10657 // vector, since the result type is the a vector of the equivilant sized 10658 // integer. 10659 const QualType ResultEltTy = VD->getElementType(); 10660 UnaryOperatorKind Op = E->getOpcode(); 10661 10662 APValue SubExprValue; 10663 if (!Evaluate(SubExprValue, Info, SubExpr)) 10664 return false; 10665 10666 // FIXME: This vector evaluator someday needs to be changed to be LValue 10667 // aware/keep LValue information around, rather than dealing with just vector 10668 // types directly. Until then, we cannot handle cases where the operand to 10669 // these unary operators is an LValue. The only case I've been able to see 10670 // cause this is operator++ assigning to a member expression (only valid in 10671 // altivec compilations) in C mode, so this shouldn't limit us too much. 10672 if (SubExprValue.isLValue()) 10673 return false; 10674 10675 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10676 "Vector length doesn't match type?"); 10677 10678 SmallVector<APValue, 4> ResultElements; 10679 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10680 std::optional<APValue> Elt = handleVectorUnaryOperator( 10681 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10682 if (!Elt) 10683 return false; 10684 ResultElements.push_back(*Elt); 10685 } 10686 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10687 } 10688 10689 //===----------------------------------------------------------------------===// 10690 // Array Evaluation 10691 //===----------------------------------------------------------------------===// 10692 10693 namespace { 10694 class ArrayExprEvaluator 10695 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10696 const LValue &This; 10697 APValue &Result; 10698 public: 10699 10700 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10701 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10702 10703 bool Success(const APValue &V, const Expr *E) { 10704 assert(V.isArray() && "expected array"); 10705 Result = V; 10706 return true; 10707 } 10708 10709 bool ZeroInitialization(const Expr *E) { 10710 const ConstantArrayType *CAT = 10711 Info.Ctx.getAsConstantArrayType(E->getType()); 10712 if (!CAT) { 10713 if (E->getType()->isIncompleteArrayType()) { 10714 // We can be asked to zero-initialize a flexible array member; this 10715 // is represented as an ImplicitValueInitExpr of incomplete array 10716 // type. In this case, the array has zero elements. 10717 Result = APValue(APValue::UninitArray(), 0, 0); 10718 return true; 10719 } 10720 // FIXME: We could handle VLAs here. 10721 return Error(E); 10722 } 10723 10724 Result = APValue(APValue::UninitArray(), 0, 10725 CAT->getSize().getZExtValue()); 10726 if (!Result.hasArrayFiller()) 10727 return true; 10728 10729 // Zero-initialize all elements. 10730 LValue Subobject = This; 10731 Subobject.addArray(Info, E, CAT); 10732 ImplicitValueInitExpr VIE(CAT->getElementType()); 10733 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10734 } 10735 10736 bool VisitCallExpr(const CallExpr *E) { 10737 return handleCallExpr(E, Result, &This); 10738 } 10739 bool VisitInitListExpr(const InitListExpr *E, 10740 QualType AllocType = QualType()); 10741 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10742 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10743 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10744 const LValue &Subobject, 10745 APValue *Value, QualType Type); 10746 bool VisitStringLiteral(const StringLiteral *E, 10747 QualType AllocType = QualType()) { 10748 expandStringLiteral(Info, E, Result, AllocType); 10749 return true; 10750 } 10751 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E); 10752 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit, 10753 ArrayRef<Expr *> Args, 10754 const Expr *ArrayFiller, 10755 QualType AllocType = QualType()); 10756 }; 10757 } // end anonymous namespace 10758 10759 static bool EvaluateArray(const Expr *E, const LValue &This, 10760 APValue &Result, EvalInfo &Info) { 10761 assert(!E->isValueDependent()); 10762 assert(E->isPRValue() && E->getType()->isArrayType() && 10763 "not an array prvalue"); 10764 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10765 } 10766 10767 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10768 APValue &Result, const InitListExpr *ILE, 10769 QualType AllocType) { 10770 assert(!ILE->isValueDependent()); 10771 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10772 "not an array prvalue"); 10773 return ArrayExprEvaluator(Info, This, Result) 10774 .VisitInitListExpr(ILE, AllocType); 10775 } 10776 10777 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10778 APValue &Result, 10779 const CXXConstructExpr *CCE, 10780 QualType AllocType) { 10781 assert(!CCE->isValueDependent()); 10782 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10783 "not an array prvalue"); 10784 return ArrayExprEvaluator(Info, This, Result) 10785 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10786 } 10787 10788 // Return true iff the given array filler may depend on the element index. 10789 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10790 // For now, just allow non-class value-initialization and initialization 10791 // lists comprised of them. 10792 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10793 return false; 10794 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10795 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10796 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10797 return true; 10798 } 10799 10800 if (ILE->hasArrayFiller() && 10801 MaybeElementDependentArrayFiller(ILE->getArrayFiller())) 10802 return true; 10803 10804 return false; 10805 } 10806 return true; 10807 } 10808 10809 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10810 QualType AllocType) { 10811 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10812 AllocType.isNull() ? E->getType() : AllocType); 10813 if (!CAT) 10814 return Error(E); 10815 10816 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10817 // an appropriately-typed string literal enclosed in braces. 10818 if (E->isStringLiteralInit()) { 10819 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10820 // FIXME: Support ObjCEncodeExpr here once we support it in 10821 // ArrayExprEvaluator generally. 10822 if (!SL) 10823 return Error(E); 10824 return VisitStringLiteral(SL, AllocType); 10825 } 10826 // Any other transparent list init will need proper handling of the 10827 // AllocType; we can't just recurse to the inner initializer. 10828 assert(!E->isTransparent() && 10829 "transparent array list initialization is not string literal init?"); 10830 10831 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(), 10832 AllocType); 10833 } 10834 10835 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr( 10836 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller, 10837 QualType AllocType) { 10838 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10839 AllocType.isNull() ? ExprToVisit->getType() : AllocType); 10840 10841 bool Success = true; 10842 10843 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10844 "zero-initialized array shouldn't have any initialized elts"); 10845 APValue Filler; 10846 if (Result.isArray() && Result.hasArrayFiller()) 10847 Filler = Result.getArrayFiller(); 10848 10849 unsigned NumEltsToInit = Args.size(); 10850 unsigned NumElts = CAT->getSize().getZExtValue(); 10851 10852 // If the initializer might depend on the array index, run it for each 10853 // array element. 10854 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller)) 10855 NumEltsToInit = NumElts; 10856 10857 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10858 << NumEltsToInit << ".\n"); 10859 10860 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10861 10862 // If the array was previously zero-initialized, preserve the 10863 // zero-initialized values. 10864 if (Filler.hasValue()) { 10865 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10866 Result.getArrayInitializedElt(I) = Filler; 10867 if (Result.hasArrayFiller()) 10868 Result.getArrayFiller() = Filler; 10869 } 10870 10871 LValue Subobject = This; 10872 Subobject.addArray(Info, ExprToVisit, CAT); 10873 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10874 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller; 10875 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10876 Info, Subobject, Init) || 10877 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10878 CAT->getElementType(), 1)) { 10879 if (!Info.noteFailure()) 10880 return false; 10881 Success = false; 10882 } 10883 } 10884 10885 if (!Result.hasArrayFiller()) 10886 return Success; 10887 10888 // If we get here, we have a trivial filler, which we can just evaluate 10889 // once and splat over the rest of the array elements. 10890 assert(ArrayFiller && "no array filler for incomplete init list"); 10891 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10892 ArrayFiller) && 10893 Success; 10894 } 10895 10896 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10897 LValue CommonLV; 10898 if (E->getCommonExpr() && 10899 !Evaluate(Info.CurrentCall->createTemporary( 10900 E->getCommonExpr(), 10901 getStorageType(Info.Ctx, E->getCommonExpr()), 10902 ScopeKind::FullExpression, CommonLV), 10903 Info, E->getCommonExpr()->getSourceExpr())) 10904 return false; 10905 10906 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10907 10908 uint64_t Elements = CAT->getSize().getZExtValue(); 10909 Result = APValue(APValue::UninitArray(), Elements, Elements); 10910 10911 LValue Subobject = This; 10912 Subobject.addArray(Info, E, CAT); 10913 10914 bool Success = true; 10915 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10916 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10917 Info, Subobject, E->getSubExpr()) || 10918 !HandleLValueArrayAdjustment(Info, E, Subobject, 10919 CAT->getElementType(), 1)) { 10920 if (!Info.noteFailure()) 10921 return false; 10922 Success = false; 10923 } 10924 } 10925 10926 return Success; 10927 } 10928 10929 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10930 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10931 } 10932 10933 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10934 const LValue &Subobject, 10935 APValue *Value, 10936 QualType Type) { 10937 bool HadZeroInit = Value->hasValue(); 10938 10939 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10940 unsigned FinalSize = CAT->getSize().getZExtValue(); 10941 10942 // Preserve the array filler if we had prior zero-initialization. 10943 APValue Filler = 10944 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10945 : APValue(); 10946 10947 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 10948 if (FinalSize == 0) 10949 return true; 10950 10951 bool HasTrivialConstructor = CheckTrivialDefaultConstructor( 10952 Info, E->getExprLoc(), E->getConstructor(), 10953 E->requiresZeroInitialization()); 10954 LValue ArrayElt = Subobject; 10955 ArrayElt.addArray(Info, E, CAT); 10956 // We do the whole initialization in two passes, first for just one element, 10957 // then for the whole array. It's possible we may find out we can't do const 10958 // init in the first pass, in which case we avoid allocating a potentially 10959 // large array. We don't do more passes because expanding array requires 10960 // copying the data, which is wasteful. 10961 for (const unsigned N : {1u, FinalSize}) { 10962 unsigned OldElts = Value->getArrayInitializedElts(); 10963 if (OldElts == N) 10964 break; 10965 10966 // Expand the array to appropriate size. 10967 APValue NewValue(APValue::UninitArray(), N, FinalSize); 10968 for (unsigned I = 0; I < OldElts; ++I) 10969 NewValue.getArrayInitializedElt(I).swap( 10970 Value->getArrayInitializedElt(I)); 10971 Value->swap(NewValue); 10972 10973 if (HadZeroInit) 10974 for (unsigned I = OldElts; I < N; ++I) 10975 Value->getArrayInitializedElt(I) = Filler; 10976 10977 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) { 10978 // If we have a trivial constructor, only evaluate it once and copy 10979 // the result into all the array elements. 10980 APValue &FirstResult = Value->getArrayInitializedElt(0); 10981 for (unsigned I = OldElts; I < FinalSize; ++I) 10982 Value->getArrayInitializedElt(I) = FirstResult; 10983 } else { 10984 for (unsigned I = OldElts; I < N; ++I) { 10985 if (!VisitCXXConstructExpr(E, ArrayElt, 10986 &Value->getArrayInitializedElt(I), 10987 CAT->getElementType()) || 10988 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10989 CAT->getElementType(), 1)) 10990 return false; 10991 // When checking for const initilization any diagnostic is considered 10992 // an error. 10993 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 10994 !Info.keepEvaluatingAfterFailure()) 10995 return false; 10996 } 10997 } 10998 } 10999 11000 return true; 11001 } 11002 11003 if (!Type->isRecordType()) 11004 return Error(E); 11005 11006 return RecordExprEvaluator(Info, Subobject, *Value) 11007 .VisitCXXConstructExpr(E, Type); 11008 } 11009 11010 bool ArrayExprEvaluator::VisitCXXParenListInitExpr( 11011 const CXXParenListInitExpr *E) { 11012 assert(dyn_cast<ConstantArrayType>(E->getType()) && 11013 "Expression result is not a constant array type"); 11014 11015 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(), 11016 E->getArrayFiller()); 11017 } 11018 11019 //===----------------------------------------------------------------------===// 11020 // Integer Evaluation 11021 // 11022 // As a GNU extension, we support casting pointers to sufficiently-wide integer 11023 // types and back in constant folding. Integer values are thus represented 11024 // either as an integer-valued APValue, or as an lvalue-valued APValue. 11025 //===----------------------------------------------------------------------===// 11026 11027 namespace { 11028 class IntExprEvaluator 11029 : public ExprEvaluatorBase<IntExprEvaluator> { 11030 APValue &Result; 11031 public: 11032 IntExprEvaluator(EvalInfo &info, APValue &result) 11033 : ExprEvaluatorBaseTy(info), Result(result) {} 11034 11035 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 11036 assert(E->getType()->isIntegralOrEnumerationType() && 11037 "Invalid evaluation result."); 11038 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 11039 "Invalid evaluation result."); 11040 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 11041 "Invalid evaluation result."); 11042 Result = APValue(SI); 11043 return true; 11044 } 11045 bool Success(const llvm::APSInt &SI, const Expr *E) { 11046 return Success(SI, E, Result); 11047 } 11048 11049 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 11050 assert(E->getType()->isIntegralOrEnumerationType() && 11051 "Invalid evaluation result."); 11052 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 11053 "Invalid evaluation result."); 11054 Result = APValue(APSInt(I)); 11055 Result.getInt().setIsUnsigned( 11056 E->getType()->isUnsignedIntegerOrEnumerationType()); 11057 return true; 11058 } 11059 bool Success(const llvm::APInt &I, const Expr *E) { 11060 return Success(I, E, Result); 11061 } 11062 11063 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11064 assert(E->getType()->isIntegralOrEnumerationType() && 11065 "Invalid evaluation result."); 11066 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 11067 return true; 11068 } 11069 bool Success(uint64_t Value, const Expr *E) { 11070 return Success(Value, E, Result); 11071 } 11072 11073 bool Success(CharUnits Size, const Expr *E) { 11074 return Success(Size.getQuantity(), E); 11075 } 11076 11077 bool Success(const APValue &V, const Expr *E) { 11078 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 11079 Result = V; 11080 return true; 11081 } 11082 return Success(V.getInt(), E); 11083 } 11084 11085 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 11086 11087 //===--------------------------------------------------------------------===// 11088 // Visitor Methods 11089 //===--------------------------------------------------------------------===// 11090 11091 bool VisitIntegerLiteral(const IntegerLiteral *E) { 11092 return Success(E->getValue(), E); 11093 } 11094 bool VisitCharacterLiteral(const CharacterLiteral *E) { 11095 return Success(E->getValue(), E); 11096 } 11097 11098 bool CheckReferencedDecl(const Expr *E, const Decl *D); 11099 bool VisitDeclRefExpr(const DeclRefExpr *E) { 11100 if (CheckReferencedDecl(E, E->getDecl())) 11101 return true; 11102 11103 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 11104 } 11105 bool VisitMemberExpr(const MemberExpr *E) { 11106 if (CheckReferencedDecl(E, E->getMemberDecl())) { 11107 VisitIgnoredBaseExpression(E->getBase()); 11108 return true; 11109 } 11110 11111 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 11112 } 11113 11114 bool VisitCallExpr(const CallExpr *E); 11115 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 11116 bool VisitBinaryOperator(const BinaryOperator *E); 11117 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 11118 bool VisitUnaryOperator(const UnaryOperator *E); 11119 11120 bool VisitCastExpr(const CastExpr* E); 11121 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 11122 11123 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 11124 return Success(E->getValue(), E); 11125 } 11126 11127 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 11128 return Success(E->getValue(), E); 11129 } 11130 11131 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 11132 if (Info.ArrayInitIndex == uint64_t(-1)) { 11133 // We were asked to evaluate this subexpression independent of the 11134 // enclosing ArrayInitLoopExpr. We can't do that. 11135 Info.FFDiag(E); 11136 return false; 11137 } 11138 return Success(Info.ArrayInitIndex, E); 11139 } 11140 11141 // Note, GNU defines __null as an integer, not a pointer. 11142 bool VisitGNUNullExpr(const GNUNullExpr *E) { 11143 return ZeroInitialization(E); 11144 } 11145 11146 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 11147 return Success(E->getValue(), E); 11148 } 11149 11150 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 11151 return Success(E->getValue(), E); 11152 } 11153 11154 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 11155 return Success(E->getValue(), E); 11156 } 11157 11158 bool VisitUnaryReal(const UnaryOperator *E); 11159 bool VisitUnaryImag(const UnaryOperator *E); 11160 11161 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 11162 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 11163 bool VisitSourceLocExpr(const SourceLocExpr *E); 11164 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 11165 bool VisitRequiresExpr(const RequiresExpr *E); 11166 // FIXME: Missing: array subscript of vector, member of vector 11167 }; 11168 11169 class FixedPointExprEvaluator 11170 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 11171 APValue &Result; 11172 11173 public: 11174 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 11175 : ExprEvaluatorBaseTy(info), Result(result) {} 11176 11177 bool Success(const llvm::APInt &I, const Expr *E) { 11178 return Success( 11179 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11180 } 11181 11182 bool Success(uint64_t Value, const Expr *E) { 11183 return Success( 11184 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11185 } 11186 11187 bool Success(const APValue &V, const Expr *E) { 11188 return Success(V.getFixedPoint(), E); 11189 } 11190 11191 bool Success(const APFixedPoint &V, const Expr *E) { 11192 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 11193 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 11194 "Invalid evaluation result."); 11195 Result = APValue(V); 11196 return true; 11197 } 11198 11199 //===--------------------------------------------------------------------===// 11200 // Visitor Methods 11201 //===--------------------------------------------------------------------===// 11202 11203 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 11204 return Success(E->getValue(), E); 11205 } 11206 11207 bool VisitCastExpr(const CastExpr *E); 11208 bool VisitUnaryOperator(const UnaryOperator *E); 11209 bool VisitBinaryOperator(const BinaryOperator *E); 11210 }; 11211 } // end anonymous namespace 11212 11213 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 11214 /// produce either the integer value or a pointer. 11215 /// 11216 /// GCC has a heinous extension which folds casts between pointer types and 11217 /// pointer-sized integral types. We support this by allowing the evaluation of 11218 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 11219 /// Some simple arithmetic on such values is supported (they are treated much 11220 /// like char*). 11221 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 11222 EvalInfo &Info) { 11223 assert(!E->isValueDependent()); 11224 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 11225 return IntExprEvaluator(Info, Result).Visit(E); 11226 } 11227 11228 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 11229 assert(!E->isValueDependent()); 11230 APValue Val; 11231 if (!EvaluateIntegerOrLValue(E, Val, Info)) 11232 return false; 11233 if (!Val.isInt()) { 11234 // FIXME: It would be better to produce the diagnostic for casting 11235 // a pointer to an integer. 11236 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11237 return false; 11238 } 11239 Result = Val.getInt(); 11240 return true; 11241 } 11242 11243 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 11244 APValue Evaluated = E->EvaluateInContext( 11245 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11246 return Success(Evaluated, E); 11247 } 11248 11249 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11250 EvalInfo &Info) { 11251 assert(!E->isValueDependent()); 11252 if (E->getType()->isFixedPointType()) { 11253 APValue Val; 11254 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11255 return false; 11256 if (!Val.isFixedPoint()) 11257 return false; 11258 11259 Result = Val.getFixedPoint(); 11260 return true; 11261 } 11262 return false; 11263 } 11264 11265 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11266 EvalInfo &Info) { 11267 assert(!E->isValueDependent()); 11268 if (E->getType()->isIntegerType()) { 11269 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11270 APSInt Val; 11271 if (!EvaluateInteger(E, Val, Info)) 11272 return false; 11273 Result = APFixedPoint(Val, FXSema); 11274 return true; 11275 } else if (E->getType()->isFixedPointType()) { 11276 return EvaluateFixedPoint(E, Result, Info); 11277 } 11278 return false; 11279 } 11280 11281 /// Check whether the given declaration can be directly converted to an integral 11282 /// rvalue. If not, no diagnostic is produced; there are other things we can 11283 /// try. 11284 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11285 // Enums are integer constant exprs. 11286 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11287 // Check for signedness/width mismatches between E type and ECD value. 11288 bool SameSign = (ECD->getInitVal().isSigned() 11289 == E->getType()->isSignedIntegerOrEnumerationType()); 11290 bool SameWidth = (ECD->getInitVal().getBitWidth() 11291 == Info.Ctx.getIntWidth(E->getType())); 11292 if (SameSign && SameWidth) 11293 return Success(ECD->getInitVal(), E); 11294 else { 11295 // Get rid of mismatch (otherwise Success assertions will fail) 11296 // by computing a new value matching the type of E. 11297 llvm::APSInt Val = ECD->getInitVal(); 11298 if (!SameSign) 11299 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11300 if (!SameWidth) 11301 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11302 return Success(Val, E); 11303 } 11304 } 11305 return false; 11306 } 11307 11308 /// Values returned by __builtin_classify_type, chosen to match the values 11309 /// produced by GCC's builtin. 11310 enum class GCCTypeClass { 11311 None = -1, 11312 Void = 0, 11313 Integer = 1, 11314 // GCC reserves 2 for character types, but instead classifies them as 11315 // integers. 11316 Enum = 3, 11317 Bool = 4, 11318 Pointer = 5, 11319 // GCC reserves 6 for references, but appears to never use it (because 11320 // expressions never have reference type, presumably). 11321 PointerToDataMember = 7, 11322 RealFloat = 8, 11323 Complex = 9, 11324 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11325 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11326 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11327 // uses 12 for that purpose, same as for a class or struct. Maybe it 11328 // internally implements a pointer to member as a struct? Who knows. 11329 PointerToMemberFunction = 12, // Not a bug, see above. 11330 ClassOrStruct = 12, 11331 Union = 13, 11332 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11333 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11334 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11335 // literals. 11336 }; 11337 11338 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11339 /// as GCC. 11340 static GCCTypeClass 11341 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11342 assert(!T->isDependentType() && "unexpected dependent type"); 11343 11344 QualType CanTy = T.getCanonicalType(); 11345 11346 switch (CanTy->getTypeClass()) { 11347 #define TYPE(ID, BASE) 11348 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11349 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11350 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11351 #include "clang/AST/TypeNodes.inc" 11352 case Type::Auto: 11353 case Type::DeducedTemplateSpecialization: 11354 llvm_unreachable("unexpected non-canonical or dependent type"); 11355 11356 case Type::Builtin: 11357 switch (cast<BuiltinType>(CanTy)->getKind()) { 11358 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11359 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11360 case BuiltinType::ID: return GCCTypeClass::Integer; 11361 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11362 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11363 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11364 case BuiltinType::ID: break; 11365 #include "clang/AST/BuiltinTypes.def" 11366 case BuiltinType::Void: 11367 return GCCTypeClass::Void; 11368 11369 case BuiltinType::Bool: 11370 return GCCTypeClass::Bool; 11371 11372 case BuiltinType::Char_U: 11373 case BuiltinType::UChar: 11374 case BuiltinType::WChar_U: 11375 case BuiltinType::Char8: 11376 case BuiltinType::Char16: 11377 case BuiltinType::Char32: 11378 case BuiltinType::UShort: 11379 case BuiltinType::UInt: 11380 case BuiltinType::ULong: 11381 case BuiltinType::ULongLong: 11382 case BuiltinType::UInt128: 11383 return GCCTypeClass::Integer; 11384 11385 case BuiltinType::UShortAccum: 11386 case BuiltinType::UAccum: 11387 case BuiltinType::ULongAccum: 11388 case BuiltinType::UShortFract: 11389 case BuiltinType::UFract: 11390 case BuiltinType::ULongFract: 11391 case BuiltinType::SatUShortAccum: 11392 case BuiltinType::SatUAccum: 11393 case BuiltinType::SatULongAccum: 11394 case BuiltinType::SatUShortFract: 11395 case BuiltinType::SatUFract: 11396 case BuiltinType::SatULongFract: 11397 return GCCTypeClass::None; 11398 11399 case BuiltinType::NullPtr: 11400 11401 case BuiltinType::ObjCId: 11402 case BuiltinType::ObjCClass: 11403 case BuiltinType::ObjCSel: 11404 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11405 case BuiltinType::Id: 11406 #include "clang/Basic/OpenCLImageTypes.def" 11407 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11408 case BuiltinType::Id: 11409 #include "clang/Basic/OpenCLExtensionTypes.def" 11410 case BuiltinType::OCLSampler: 11411 case BuiltinType::OCLEvent: 11412 case BuiltinType::OCLClkEvent: 11413 case BuiltinType::OCLQueue: 11414 case BuiltinType::OCLReserveID: 11415 #define SVE_TYPE(Name, Id, SingletonId) \ 11416 case BuiltinType::Id: 11417 #include "clang/Basic/AArch64SVEACLETypes.def" 11418 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11419 case BuiltinType::Id: 11420 #include "clang/Basic/PPCTypes.def" 11421 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11422 #include "clang/Basic/RISCVVTypes.def" 11423 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11424 #include "clang/Basic/WebAssemblyReferenceTypes.def" 11425 return GCCTypeClass::None; 11426 11427 case BuiltinType::Dependent: 11428 llvm_unreachable("unexpected dependent type"); 11429 }; 11430 llvm_unreachable("unexpected placeholder type"); 11431 11432 case Type::Enum: 11433 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11434 11435 case Type::Pointer: 11436 case Type::ConstantArray: 11437 case Type::VariableArray: 11438 case Type::IncompleteArray: 11439 case Type::FunctionNoProto: 11440 case Type::FunctionProto: 11441 return GCCTypeClass::Pointer; 11442 11443 case Type::MemberPointer: 11444 return CanTy->isMemberDataPointerType() 11445 ? GCCTypeClass::PointerToDataMember 11446 : GCCTypeClass::PointerToMemberFunction; 11447 11448 case Type::Complex: 11449 return GCCTypeClass::Complex; 11450 11451 case Type::Record: 11452 return CanTy->isUnionType() ? GCCTypeClass::Union 11453 : GCCTypeClass::ClassOrStruct; 11454 11455 case Type::Atomic: 11456 // GCC classifies _Atomic T the same as T. 11457 return EvaluateBuiltinClassifyType( 11458 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11459 11460 case Type::BlockPointer: 11461 case Type::Vector: 11462 case Type::ExtVector: 11463 case Type::ConstantMatrix: 11464 case Type::ObjCObject: 11465 case Type::ObjCInterface: 11466 case Type::ObjCObjectPointer: 11467 case Type::Pipe: 11468 case Type::BitInt: 11469 // GCC classifies vectors as None. We follow its lead and classify all 11470 // other types that don't fit into the regular classification the same way. 11471 return GCCTypeClass::None; 11472 11473 case Type::LValueReference: 11474 case Type::RValueReference: 11475 llvm_unreachable("invalid type for expression"); 11476 } 11477 11478 llvm_unreachable("unexpected type class"); 11479 } 11480 11481 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11482 /// as GCC. 11483 static GCCTypeClass 11484 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11485 // If no argument was supplied, default to None. This isn't 11486 // ideal, however it is what gcc does. 11487 if (E->getNumArgs() == 0) 11488 return GCCTypeClass::None; 11489 11490 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11491 // being an ICE, but still folds it to a constant using the type of the first 11492 // argument. 11493 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11494 } 11495 11496 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11497 /// __builtin_constant_p when applied to the given pointer. 11498 /// 11499 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11500 /// or it points to the first character of a string literal. 11501 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11502 APValue::LValueBase Base = LV.getLValueBase(); 11503 if (Base.isNull()) { 11504 // A null base is acceptable. 11505 return true; 11506 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11507 if (!isa<StringLiteral>(E)) 11508 return false; 11509 return LV.getLValueOffset().isZero(); 11510 } else if (Base.is<TypeInfoLValue>()) { 11511 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11512 // evaluate to true. 11513 return true; 11514 } else { 11515 // Any other base is not constant enough for GCC. 11516 return false; 11517 } 11518 } 11519 11520 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11521 /// GCC as we can manage. 11522 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11523 // This evaluation is not permitted to have side-effects, so evaluate it in 11524 // a speculative evaluation context. 11525 SpeculativeEvaluationRAII SpeculativeEval(Info); 11526 11527 // Constant-folding is always enabled for the operand of __builtin_constant_p 11528 // (even when the enclosing evaluation context otherwise requires a strict 11529 // language-specific constant expression). 11530 FoldConstant Fold(Info, true); 11531 11532 QualType ArgType = Arg->getType(); 11533 11534 // __builtin_constant_p always has one operand. The rules which gcc follows 11535 // are not precisely documented, but are as follows: 11536 // 11537 // - If the operand is of integral, floating, complex or enumeration type, 11538 // and can be folded to a known value of that type, it returns 1. 11539 // - If the operand can be folded to a pointer to the first character 11540 // of a string literal (or such a pointer cast to an integral type) 11541 // or to a null pointer or an integer cast to a pointer, it returns 1. 11542 // 11543 // Otherwise, it returns 0. 11544 // 11545 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11546 // its support for this did not work prior to GCC 9 and is not yet well 11547 // understood. 11548 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11549 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11550 ArgType->isNullPtrType()) { 11551 APValue V; 11552 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11553 Fold.keepDiagnostics(); 11554 return false; 11555 } 11556 11557 // For a pointer (possibly cast to integer), there are special rules. 11558 if (V.getKind() == APValue::LValue) 11559 return EvaluateBuiltinConstantPForLValue(V); 11560 11561 // Otherwise, any constant value is good enough. 11562 return V.hasValue(); 11563 } 11564 11565 // Anything else isn't considered to be sufficiently constant. 11566 return false; 11567 } 11568 11569 /// Retrieves the "underlying object type" of the given expression, 11570 /// as used by __builtin_object_size. 11571 static QualType getObjectType(APValue::LValueBase B) { 11572 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11573 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11574 return VD->getType(); 11575 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11576 if (isa<CompoundLiteralExpr>(E)) 11577 return E->getType(); 11578 } else if (B.is<TypeInfoLValue>()) { 11579 return B.getTypeInfoType(); 11580 } else if (B.is<DynamicAllocLValue>()) { 11581 return B.getDynamicAllocType(); 11582 } 11583 11584 return QualType(); 11585 } 11586 11587 /// A more selective version of E->IgnoreParenCasts for 11588 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11589 /// to change the type of E. 11590 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11591 /// 11592 /// Always returns an RValue with a pointer representation. 11593 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11594 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11595 11596 auto *NoParens = E->IgnoreParens(); 11597 auto *Cast = dyn_cast<CastExpr>(NoParens); 11598 if (Cast == nullptr) 11599 return NoParens; 11600 11601 // We only conservatively allow a few kinds of casts, because this code is 11602 // inherently a simple solution that seeks to support the common case. 11603 auto CastKind = Cast->getCastKind(); 11604 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11605 CastKind != CK_AddressSpaceConversion) 11606 return NoParens; 11607 11608 auto *SubExpr = Cast->getSubExpr(); 11609 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11610 return NoParens; 11611 return ignorePointerCastsAndParens(SubExpr); 11612 } 11613 11614 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11615 /// record layout. e.g. 11616 /// struct { struct { int a, b; } fst, snd; } obj; 11617 /// obj.fst // no 11618 /// obj.snd // yes 11619 /// obj.fst.a // no 11620 /// obj.fst.b // no 11621 /// obj.snd.a // no 11622 /// obj.snd.b // yes 11623 /// 11624 /// Please note: this function is specialized for how __builtin_object_size 11625 /// views "objects". 11626 /// 11627 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11628 /// correct result, it will always return true. 11629 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11630 assert(!LVal.Designator.Invalid); 11631 11632 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11633 const RecordDecl *Parent = FD->getParent(); 11634 Invalid = Parent->isInvalidDecl(); 11635 if (Invalid || Parent->isUnion()) 11636 return true; 11637 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11638 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11639 }; 11640 11641 auto &Base = LVal.getLValueBase(); 11642 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11643 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11644 bool Invalid; 11645 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11646 return Invalid; 11647 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11648 for (auto *FD : IFD->chain()) { 11649 bool Invalid; 11650 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11651 return Invalid; 11652 } 11653 } 11654 } 11655 11656 unsigned I = 0; 11657 QualType BaseType = getType(Base); 11658 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11659 // If we don't know the array bound, conservatively assume we're looking at 11660 // the final array element. 11661 ++I; 11662 if (BaseType->isIncompleteArrayType()) 11663 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11664 else 11665 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11666 } 11667 11668 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11669 const auto &Entry = LVal.Designator.Entries[I]; 11670 if (BaseType->isArrayType()) { 11671 // Because __builtin_object_size treats arrays as objects, we can ignore 11672 // the index iff this is the last array in the Designator. 11673 if (I + 1 == E) 11674 return true; 11675 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11676 uint64_t Index = Entry.getAsArrayIndex(); 11677 if (Index + 1 != CAT->getSize()) 11678 return false; 11679 BaseType = CAT->getElementType(); 11680 } else if (BaseType->isAnyComplexType()) { 11681 const auto *CT = BaseType->castAs<ComplexType>(); 11682 uint64_t Index = Entry.getAsArrayIndex(); 11683 if (Index != 1) 11684 return false; 11685 BaseType = CT->getElementType(); 11686 } else if (auto *FD = getAsField(Entry)) { 11687 bool Invalid; 11688 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11689 return Invalid; 11690 BaseType = FD->getType(); 11691 } else { 11692 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11693 return false; 11694 } 11695 } 11696 return true; 11697 } 11698 11699 /// Tests to see if the LValue has a user-specified designator (that isn't 11700 /// necessarily valid). Note that this always returns 'true' if the LValue has 11701 /// an unsized array as its first designator entry, because there's currently no 11702 /// way to tell if the user typed *foo or foo[0]. 11703 static bool refersToCompleteObject(const LValue &LVal) { 11704 if (LVal.Designator.Invalid) 11705 return false; 11706 11707 if (!LVal.Designator.Entries.empty()) 11708 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11709 11710 if (!LVal.InvalidBase) 11711 return true; 11712 11713 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11714 // the LValueBase. 11715 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11716 return !E || !isa<MemberExpr>(E); 11717 } 11718 11719 /// Attempts to detect a user writing into a piece of memory that's impossible 11720 /// to figure out the size of by just using types. 11721 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11722 const SubobjectDesignator &Designator = LVal.Designator; 11723 // Notes: 11724 // - Users can only write off of the end when we have an invalid base. Invalid 11725 // bases imply we don't know where the memory came from. 11726 // - We used to be a bit more aggressive here; we'd only be conservative if 11727 // the array at the end was flexible, or if it had 0 or 1 elements. This 11728 // broke some common standard library extensions (PR30346), but was 11729 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11730 // with some sort of list. OTOH, it seems that GCC is always 11731 // conservative with the last element in structs (if it's an array), so our 11732 // current behavior is more compatible than an explicit list approach would 11733 // be. 11734 auto isFlexibleArrayMember = [&] { 11735 using FAMKind = LangOptions::StrictFlexArraysLevelKind; 11736 FAMKind StrictFlexArraysLevel = 11737 Ctx.getLangOpts().getStrictFlexArraysLevel(); 11738 11739 if (Designator.isMostDerivedAnUnsizedArray()) 11740 return true; 11741 11742 if (StrictFlexArraysLevel == FAMKind::Default) 11743 return true; 11744 11745 if (Designator.getMostDerivedArraySize() == 0 && 11746 StrictFlexArraysLevel != FAMKind::IncompleteOnly) 11747 return true; 11748 11749 if (Designator.getMostDerivedArraySize() == 1 && 11750 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete) 11751 return true; 11752 11753 return false; 11754 }; 11755 11756 return LVal.InvalidBase && 11757 Designator.Entries.size() == Designator.MostDerivedPathLength && 11758 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() && 11759 isDesignatorAtObjectEnd(Ctx, LVal); 11760 } 11761 11762 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11763 /// Fails if the conversion would cause loss of precision. 11764 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11765 CharUnits &Result) { 11766 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11767 if (Int.ugt(CharUnitsMax)) 11768 return false; 11769 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11770 return true; 11771 } 11772 11773 /// If we're evaluating the object size of an instance of a struct that 11774 /// contains a flexible array member, add the size of the initializer. 11775 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, 11776 const LValue &LV, CharUnits &Size) { 11777 if (!T.isNull() && T->isStructureType() && 11778 T->getAsStructureType()->getDecl()->hasFlexibleArrayMember()) 11779 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>()) 11780 if (const auto *VD = dyn_cast<VarDecl>(V)) 11781 if (VD->hasInit()) 11782 Size += VD->getFlexibleArrayInitChars(Info.Ctx); 11783 } 11784 11785 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11786 /// determine how many bytes exist from the beginning of the object to either 11787 /// the end of the current subobject, or the end of the object itself, depending 11788 /// on what the LValue looks like + the value of Type. 11789 /// 11790 /// If this returns false, the value of Result is undefined. 11791 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11792 unsigned Type, const LValue &LVal, 11793 CharUnits &EndOffset) { 11794 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11795 11796 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11797 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11798 return false; 11799 return HandleSizeof(Info, ExprLoc, Ty, Result); 11800 }; 11801 11802 // We want to evaluate the size of the entire object. This is a valid fallback 11803 // for when Type=1 and the designator is invalid, because we're asked for an 11804 // upper-bound. 11805 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11806 // Type=3 wants a lower bound, so we can't fall back to this. 11807 if (Type == 3 && !DetermineForCompleteObject) 11808 return false; 11809 11810 llvm::APInt APEndOffset; 11811 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11812 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11813 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11814 11815 if (LVal.InvalidBase) 11816 return false; 11817 11818 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11819 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset); 11820 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset); 11821 return Ret; 11822 } 11823 11824 // We want to evaluate the size of a subobject. 11825 const SubobjectDesignator &Designator = LVal.Designator; 11826 11827 // The following is a moderately common idiom in C: 11828 // 11829 // struct Foo { int a; char c[1]; }; 11830 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11831 // strcpy(&F->c[0], Bar); 11832 // 11833 // In order to not break too much legacy code, we need to support it. 11834 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11835 // If we can resolve this to an alloc_size call, we can hand that back, 11836 // because we know for certain how many bytes there are to write to. 11837 llvm::APInt APEndOffset; 11838 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11839 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11840 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11841 11842 // If we cannot determine the size of the initial allocation, then we can't 11843 // given an accurate upper-bound. However, we are still able to give 11844 // conservative lower-bounds for Type=3. 11845 if (Type == 1) 11846 return false; 11847 } 11848 11849 CharUnits BytesPerElem; 11850 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11851 return false; 11852 11853 // According to the GCC documentation, we want the size of the subobject 11854 // denoted by the pointer. But that's not quite right -- what we actually 11855 // want is the size of the immediately-enclosing array, if there is one. 11856 int64_t ElemsRemaining; 11857 if (Designator.MostDerivedIsArrayElement && 11858 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11859 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11860 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11861 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11862 } else { 11863 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11864 } 11865 11866 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11867 return true; 11868 } 11869 11870 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11871 /// returns true and stores the result in @p Size. 11872 /// 11873 /// If @p WasError is non-null, this will report whether the failure to evaluate 11874 /// is to be treated as an Error in IntExprEvaluator. 11875 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11876 EvalInfo &Info, uint64_t &Size) { 11877 // Determine the denoted object. 11878 LValue LVal; 11879 { 11880 // The operand of __builtin_object_size is never evaluated for side-effects. 11881 // If there are any, but we can determine the pointed-to object anyway, then 11882 // ignore the side-effects. 11883 SpeculativeEvaluationRAII SpeculativeEval(Info); 11884 IgnoreSideEffectsRAII Fold(Info); 11885 11886 if (E->isGLValue()) { 11887 // It's possible for us to be given GLValues if we're called via 11888 // Expr::tryEvaluateObjectSize. 11889 APValue RVal; 11890 if (!EvaluateAsRValue(Info, E, RVal)) 11891 return false; 11892 LVal.setFrom(Info.Ctx, RVal); 11893 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11894 /*InvalidBaseOK=*/true)) 11895 return false; 11896 } 11897 11898 // If we point to before the start of the object, there are no accessible 11899 // bytes. 11900 if (LVal.getLValueOffset().isNegative()) { 11901 Size = 0; 11902 return true; 11903 } 11904 11905 CharUnits EndOffset; 11906 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11907 return false; 11908 11909 // If we've fallen outside of the end offset, just pretend there's nothing to 11910 // write to/read from. 11911 if (EndOffset <= LVal.getLValueOffset()) 11912 Size = 0; 11913 else 11914 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11915 return true; 11916 } 11917 11918 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11919 if (!IsConstantEvaluatedBuiltinCall(E)) 11920 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11921 return VisitBuiltinCallExpr(E, E->getBuiltinCallee()); 11922 } 11923 11924 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11925 APValue &Val, APSInt &Alignment) { 11926 QualType SrcTy = E->getArg(0)->getType(); 11927 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11928 return false; 11929 // Even though we are evaluating integer expressions we could get a pointer 11930 // argument for the __builtin_is_aligned() case. 11931 if (SrcTy->isPointerType()) { 11932 LValue Ptr; 11933 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11934 return false; 11935 Ptr.moveInto(Val); 11936 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11937 Info.FFDiag(E->getArg(0)); 11938 return false; 11939 } else { 11940 APSInt SrcInt; 11941 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11942 return false; 11943 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11944 "Bit widths must be the same"); 11945 Val = APValue(SrcInt); 11946 } 11947 assert(Val.hasValue()); 11948 return true; 11949 } 11950 11951 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11952 unsigned BuiltinOp) { 11953 switch (BuiltinOp) { 11954 default: 11955 return false; 11956 11957 case Builtin::BI__builtin_dynamic_object_size: 11958 case Builtin::BI__builtin_object_size: { 11959 // The type was checked when we built the expression. 11960 unsigned Type = 11961 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11962 assert(Type <= 3 && "unexpected type"); 11963 11964 uint64_t Size; 11965 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11966 return Success(Size, E); 11967 11968 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11969 return Success((Type & 2) ? 0 : -1, E); 11970 11971 // Expression had no side effects, but we couldn't statically determine the 11972 // size of the referenced object. 11973 switch (Info.EvalMode) { 11974 case EvalInfo::EM_ConstantExpression: 11975 case EvalInfo::EM_ConstantFold: 11976 case EvalInfo::EM_IgnoreSideEffects: 11977 // Leave it to IR generation. 11978 return Error(E); 11979 case EvalInfo::EM_ConstantExpressionUnevaluated: 11980 // Reduce it to a constant now. 11981 return Success((Type & 2) ? 0 : -1, E); 11982 } 11983 11984 llvm_unreachable("unexpected EvalMode"); 11985 } 11986 11987 case Builtin::BI__builtin_os_log_format_buffer_size: { 11988 analyze_os_log::OSLogBufferLayout Layout; 11989 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11990 return Success(Layout.size().getQuantity(), E); 11991 } 11992 11993 case Builtin::BI__builtin_is_aligned: { 11994 APValue Src; 11995 APSInt Alignment; 11996 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11997 return false; 11998 if (Src.isLValue()) { 11999 // If we evaluated a pointer, check the minimum known alignment. 12000 LValue Ptr; 12001 Ptr.setFrom(Info.Ctx, Src); 12002 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 12003 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 12004 // We can return true if the known alignment at the computed offset is 12005 // greater than the requested alignment. 12006 assert(PtrAlign.isPowerOfTwo()); 12007 assert(Alignment.isPowerOf2()); 12008 if (PtrAlign.getQuantity() >= Alignment) 12009 return Success(1, E); 12010 // If the alignment is not known to be sufficient, some cases could still 12011 // be aligned at run time. However, if the requested alignment is less or 12012 // equal to the base alignment and the offset is not aligned, we know that 12013 // the run-time value can never be aligned. 12014 if (BaseAlignment.getQuantity() >= Alignment && 12015 PtrAlign.getQuantity() < Alignment) 12016 return Success(0, E); 12017 // Otherwise we can't infer whether the value is sufficiently aligned. 12018 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 12019 // in cases where we can't fully evaluate the pointer. 12020 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 12021 << Alignment; 12022 return false; 12023 } 12024 assert(Src.isInt()); 12025 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 12026 } 12027 case Builtin::BI__builtin_align_up: { 12028 APValue Src; 12029 APSInt Alignment; 12030 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 12031 return false; 12032 if (!Src.isInt()) 12033 return Error(E); 12034 APSInt AlignedVal = 12035 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 12036 Src.getInt().isUnsigned()); 12037 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 12038 return Success(AlignedVal, E); 12039 } 12040 case Builtin::BI__builtin_align_down: { 12041 APValue Src; 12042 APSInt Alignment; 12043 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 12044 return false; 12045 if (!Src.isInt()) 12046 return Error(E); 12047 APSInt AlignedVal = 12048 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 12049 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 12050 return Success(AlignedVal, E); 12051 } 12052 12053 case Builtin::BI__builtin_bitreverse8: 12054 case Builtin::BI__builtin_bitreverse16: 12055 case Builtin::BI__builtin_bitreverse32: 12056 case Builtin::BI__builtin_bitreverse64: { 12057 APSInt Val; 12058 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12059 return false; 12060 12061 return Success(Val.reverseBits(), E); 12062 } 12063 12064 case Builtin::BI__builtin_bswap16: 12065 case Builtin::BI__builtin_bswap32: 12066 case Builtin::BI__builtin_bswap64: { 12067 APSInt Val; 12068 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12069 return false; 12070 12071 return Success(Val.byteSwap(), E); 12072 } 12073 12074 case Builtin::BI__builtin_classify_type: 12075 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 12076 12077 case Builtin::BI__builtin_clrsb: 12078 case Builtin::BI__builtin_clrsbl: 12079 case Builtin::BI__builtin_clrsbll: { 12080 APSInt Val; 12081 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12082 return false; 12083 12084 return Success(Val.getBitWidth() - Val.getSignificantBits(), E); 12085 } 12086 12087 case Builtin::BI__builtin_clz: 12088 case Builtin::BI__builtin_clzl: 12089 case Builtin::BI__builtin_clzll: 12090 case Builtin::BI__builtin_clzs: { 12091 APSInt Val; 12092 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12093 return false; 12094 if (!Val) 12095 return Error(E); 12096 12097 return Success(Val.countl_zero(), E); 12098 } 12099 12100 case Builtin::BI__builtin_constant_p: { 12101 const Expr *Arg = E->getArg(0); 12102 if (EvaluateBuiltinConstantP(Info, Arg)) 12103 return Success(true, E); 12104 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 12105 // Outside a constant context, eagerly evaluate to false in the presence 12106 // of side-effects in order to avoid -Wunsequenced false-positives in 12107 // a branch on __builtin_constant_p(expr). 12108 return Success(false, E); 12109 } 12110 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12111 return false; 12112 } 12113 12114 case Builtin::BI__builtin_is_constant_evaluated: { 12115 const auto *Callee = Info.CurrentCall->getCallee(); 12116 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 12117 (Info.CallStackDepth == 1 || 12118 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 12119 Callee->getIdentifier() && 12120 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 12121 // FIXME: Find a better way to avoid duplicated diagnostics. 12122 if (Info.EvalStatus.Diag) 12123 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 12124 : Info.CurrentCall->CallLoc, 12125 diag::warn_is_constant_evaluated_always_true_constexpr) 12126 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 12127 : "std::is_constant_evaluated"); 12128 } 12129 12130 return Success(Info.InConstantContext, E); 12131 } 12132 12133 case Builtin::BI__builtin_ctz: 12134 case Builtin::BI__builtin_ctzl: 12135 case Builtin::BI__builtin_ctzll: 12136 case Builtin::BI__builtin_ctzs: { 12137 APSInt Val; 12138 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12139 return false; 12140 if (!Val) 12141 return Error(E); 12142 12143 return Success(Val.countr_zero(), E); 12144 } 12145 12146 case Builtin::BI__builtin_eh_return_data_regno: { 12147 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 12148 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 12149 return Success(Operand, E); 12150 } 12151 12152 case Builtin::BI__builtin_expect: 12153 case Builtin::BI__builtin_expect_with_probability: 12154 return Visit(E->getArg(0)); 12155 12156 case Builtin::BI__builtin_ffs: 12157 case Builtin::BI__builtin_ffsl: 12158 case Builtin::BI__builtin_ffsll: { 12159 APSInt Val; 12160 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12161 return false; 12162 12163 unsigned N = Val.countr_zero(); 12164 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 12165 } 12166 12167 case Builtin::BI__builtin_fpclassify: { 12168 APFloat Val(0.0); 12169 if (!EvaluateFloat(E->getArg(5), Val, Info)) 12170 return false; 12171 unsigned Arg; 12172 switch (Val.getCategory()) { 12173 case APFloat::fcNaN: Arg = 0; break; 12174 case APFloat::fcInfinity: Arg = 1; break; 12175 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 12176 case APFloat::fcZero: Arg = 4; break; 12177 } 12178 return Visit(E->getArg(Arg)); 12179 } 12180 12181 case Builtin::BI__builtin_isinf_sign: { 12182 APFloat Val(0.0); 12183 return EvaluateFloat(E->getArg(0), Val, Info) && 12184 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 12185 } 12186 12187 case Builtin::BI__builtin_isinf: { 12188 APFloat Val(0.0); 12189 return EvaluateFloat(E->getArg(0), Val, Info) && 12190 Success(Val.isInfinity() ? 1 : 0, E); 12191 } 12192 12193 case Builtin::BI__builtin_isfinite: { 12194 APFloat Val(0.0); 12195 return EvaluateFloat(E->getArg(0), Val, Info) && 12196 Success(Val.isFinite() ? 1 : 0, E); 12197 } 12198 12199 case Builtin::BI__builtin_isnan: { 12200 APFloat Val(0.0); 12201 return EvaluateFloat(E->getArg(0), Val, Info) && 12202 Success(Val.isNaN() ? 1 : 0, E); 12203 } 12204 12205 case Builtin::BI__builtin_isnormal: { 12206 APFloat Val(0.0); 12207 return EvaluateFloat(E->getArg(0), Val, Info) && 12208 Success(Val.isNormal() ? 1 : 0, E); 12209 } 12210 12211 case Builtin::BI__builtin_isfpclass: { 12212 APSInt MaskVal; 12213 if (!EvaluateInteger(E->getArg(1), MaskVal, Info)) 12214 return false; 12215 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue()); 12216 APFloat Val(0.0); 12217 return EvaluateFloat(E->getArg(0), Val, Info) && 12218 Success((Val.classify() & Test) ? 1 : 0, E); 12219 } 12220 12221 case Builtin::BI__builtin_parity: 12222 case Builtin::BI__builtin_parityl: 12223 case Builtin::BI__builtin_parityll: { 12224 APSInt Val; 12225 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12226 return false; 12227 12228 return Success(Val.popcount() % 2, E); 12229 } 12230 12231 case Builtin::BI__builtin_popcount: 12232 case Builtin::BI__builtin_popcountl: 12233 case Builtin::BI__builtin_popcountll: { 12234 APSInt Val; 12235 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12236 return false; 12237 12238 return Success(Val.popcount(), E); 12239 } 12240 12241 case Builtin::BI__builtin_rotateleft8: 12242 case Builtin::BI__builtin_rotateleft16: 12243 case Builtin::BI__builtin_rotateleft32: 12244 case Builtin::BI__builtin_rotateleft64: 12245 case Builtin::BI_rotl8: // Microsoft variants of rotate right 12246 case Builtin::BI_rotl16: 12247 case Builtin::BI_rotl: 12248 case Builtin::BI_lrotl: 12249 case Builtin::BI_rotl64: { 12250 APSInt Val, Amt; 12251 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12252 !EvaluateInteger(E->getArg(1), Amt, Info)) 12253 return false; 12254 12255 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 12256 } 12257 12258 case Builtin::BI__builtin_rotateright8: 12259 case Builtin::BI__builtin_rotateright16: 12260 case Builtin::BI__builtin_rotateright32: 12261 case Builtin::BI__builtin_rotateright64: 12262 case Builtin::BI_rotr8: // Microsoft variants of rotate right 12263 case Builtin::BI_rotr16: 12264 case Builtin::BI_rotr: 12265 case Builtin::BI_lrotr: 12266 case Builtin::BI_rotr64: { 12267 APSInt Val, Amt; 12268 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12269 !EvaluateInteger(E->getArg(1), Amt, Info)) 12270 return false; 12271 12272 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 12273 } 12274 12275 case Builtin::BIstrlen: 12276 case Builtin::BIwcslen: 12277 // A call to strlen is not a constant expression. 12278 if (Info.getLangOpts().CPlusPlus11) 12279 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12280 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 12281 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 12282 else 12283 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12284 [[fallthrough]]; 12285 case Builtin::BI__builtin_strlen: 12286 case Builtin::BI__builtin_wcslen: { 12287 // As an extension, we support __builtin_strlen() as a constant expression, 12288 // and support folding strlen() to a constant. 12289 uint64_t StrLen; 12290 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 12291 return Success(StrLen, E); 12292 return false; 12293 } 12294 12295 case Builtin::BIstrcmp: 12296 case Builtin::BIwcscmp: 12297 case Builtin::BIstrncmp: 12298 case Builtin::BIwcsncmp: 12299 case Builtin::BImemcmp: 12300 case Builtin::BIbcmp: 12301 case Builtin::BIwmemcmp: 12302 // A call to strlen is not a constant expression. 12303 if (Info.getLangOpts().CPlusPlus11) 12304 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12305 << /*isConstexpr*/ 0 << /*isConstructor*/ 0 12306 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str(); 12307 else 12308 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12309 [[fallthrough]]; 12310 case Builtin::BI__builtin_strcmp: 12311 case Builtin::BI__builtin_wcscmp: 12312 case Builtin::BI__builtin_strncmp: 12313 case Builtin::BI__builtin_wcsncmp: 12314 case Builtin::BI__builtin_memcmp: 12315 case Builtin::BI__builtin_bcmp: 12316 case Builtin::BI__builtin_wmemcmp: { 12317 LValue String1, String2; 12318 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12319 !EvaluatePointer(E->getArg(1), String2, Info)) 12320 return false; 12321 12322 uint64_t MaxLength = uint64_t(-1); 12323 if (BuiltinOp != Builtin::BIstrcmp && 12324 BuiltinOp != Builtin::BIwcscmp && 12325 BuiltinOp != Builtin::BI__builtin_strcmp && 12326 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12327 APSInt N; 12328 if (!EvaluateInteger(E->getArg(2), N, Info)) 12329 return false; 12330 MaxLength = N.getExtValue(); 12331 } 12332 12333 // Empty substrings compare equal by definition. 12334 if (MaxLength == 0u) 12335 return Success(0, E); 12336 12337 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12338 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12339 String1.Designator.Invalid || String2.Designator.Invalid) 12340 return false; 12341 12342 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12343 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12344 12345 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12346 BuiltinOp == Builtin::BIbcmp || 12347 BuiltinOp == Builtin::BI__builtin_memcmp || 12348 BuiltinOp == Builtin::BI__builtin_bcmp; 12349 12350 assert(IsRawByte || 12351 (Info.Ctx.hasSameUnqualifiedType( 12352 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12353 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12354 12355 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12356 // 'char8_t', but no other types. 12357 if (IsRawByte && 12358 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12359 // FIXME: Consider using our bit_cast implementation to support this. 12360 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12361 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str() 12362 << CharTy1 << CharTy2; 12363 return false; 12364 } 12365 12366 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12367 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12368 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12369 Char1.isInt() && Char2.isInt(); 12370 }; 12371 const auto &AdvanceElems = [&] { 12372 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12373 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12374 }; 12375 12376 bool StopAtNull = 12377 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12378 BuiltinOp != Builtin::BIwmemcmp && 12379 BuiltinOp != Builtin::BI__builtin_memcmp && 12380 BuiltinOp != Builtin::BI__builtin_bcmp && 12381 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12382 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12383 BuiltinOp == Builtin::BIwcsncmp || 12384 BuiltinOp == Builtin::BIwmemcmp || 12385 BuiltinOp == Builtin::BI__builtin_wcscmp || 12386 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12387 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12388 12389 for (; MaxLength; --MaxLength) { 12390 APValue Char1, Char2; 12391 if (!ReadCurElems(Char1, Char2)) 12392 return false; 12393 if (Char1.getInt().ne(Char2.getInt())) { 12394 if (IsWide) // wmemcmp compares with wchar_t signedness. 12395 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12396 // memcmp always compares unsigned chars. 12397 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12398 } 12399 if (StopAtNull && !Char1.getInt()) 12400 return Success(0, E); 12401 assert(!(StopAtNull && !Char2.getInt())); 12402 if (!AdvanceElems()) 12403 return false; 12404 } 12405 // We hit the strncmp / memcmp limit. 12406 return Success(0, E); 12407 } 12408 12409 case Builtin::BI__atomic_always_lock_free: 12410 case Builtin::BI__atomic_is_lock_free: 12411 case Builtin::BI__c11_atomic_is_lock_free: { 12412 APSInt SizeVal; 12413 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12414 return false; 12415 12416 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12417 // of two less than or equal to the maximum inline atomic width, we know it 12418 // is lock-free. If the size isn't a power of two, or greater than the 12419 // maximum alignment where we promote atomics, we know it is not lock-free 12420 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12421 // the answer can only be determined at runtime; for example, 16-byte 12422 // atomics have lock-free implementations on some, but not all, 12423 // x86-64 processors. 12424 12425 // Check power-of-two. 12426 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12427 if (Size.isPowerOfTwo()) { 12428 // Check against inlining width. 12429 unsigned InlineWidthBits = 12430 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12431 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12432 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12433 Size == CharUnits::One() || 12434 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12435 Expr::NPC_NeverValueDependent)) 12436 // OK, we will inline appropriately-aligned operations of this size, 12437 // and _Atomic(T) is appropriately-aligned. 12438 return Success(1, E); 12439 12440 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12441 castAs<PointerType>()->getPointeeType(); 12442 if (!PointeeType->isIncompleteType() && 12443 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12444 // OK, we will inline operations on this object. 12445 return Success(1, E); 12446 } 12447 } 12448 } 12449 12450 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12451 Success(0, E) : Error(E); 12452 } 12453 case Builtin::BI__builtin_add_overflow: 12454 case Builtin::BI__builtin_sub_overflow: 12455 case Builtin::BI__builtin_mul_overflow: 12456 case Builtin::BI__builtin_sadd_overflow: 12457 case Builtin::BI__builtin_uadd_overflow: 12458 case Builtin::BI__builtin_uaddl_overflow: 12459 case Builtin::BI__builtin_uaddll_overflow: 12460 case Builtin::BI__builtin_usub_overflow: 12461 case Builtin::BI__builtin_usubl_overflow: 12462 case Builtin::BI__builtin_usubll_overflow: 12463 case Builtin::BI__builtin_umul_overflow: 12464 case Builtin::BI__builtin_umull_overflow: 12465 case Builtin::BI__builtin_umulll_overflow: 12466 case Builtin::BI__builtin_saddl_overflow: 12467 case Builtin::BI__builtin_saddll_overflow: 12468 case Builtin::BI__builtin_ssub_overflow: 12469 case Builtin::BI__builtin_ssubl_overflow: 12470 case Builtin::BI__builtin_ssubll_overflow: 12471 case Builtin::BI__builtin_smul_overflow: 12472 case Builtin::BI__builtin_smull_overflow: 12473 case Builtin::BI__builtin_smulll_overflow: { 12474 LValue ResultLValue; 12475 APSInt LHS, RHS; 12476 12477 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12478 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12479 !EvaluateInteger(E->getArg(1), RHS, Info) || 12480 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12481 return false; 12482 12483 APSInt Result; 12484 bool DidOverflow = false; 12485 12486 // If the types don't have to match, enlarge all 3 to the largest of them. 12487 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12488 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12489 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12490 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12491 ResultType->isSignedIntegerOrEnumerationType(); 12492 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12493 ResultType->isSignedIntegerOrEnumerationType(); 12494 uint64_t LHSSize = LHS.getBitWidth(); 12495 uint64_t RHSSize = RHS.getBitWidth(); 12496 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12497 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12498 12499 // Add an additional bit if the signedness isn't uniformly agreed to. We 12500 // could do this ONLY if there is a signed and an unsigned that both have 12501 // MaxBits, but the code to check that is pretty nasty. The issue will be 12502 // caught in the shrink-to-result later anyway. 12503 if (IsSigned && !AllSigned) 12504 ++MaxBits; 12505 12506 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12507 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12508 Result = APSInt(MaxBits, !IsSigned); 12509 } 12510 12511 // Find largest int. 12512 switch (BuiltinOp) { 12513 default: 12514 llvm_unreachable("Invalid value for BuiltinOp"); 12515 case Builtin::BI__builtin_add_overflow: 12516 case Builtin::BI__builtin_sadd_overflow: 12517 case Builtin::BI__builtin_saddl_overflow: 12518 case Builtin::BI__builtin_saddll_overflow: 12519 case Builtin::BI__builtin_uadd_overflow: 12520 case Builtin::BI__builtin_uaddl_overflow: 12521 case Builtin::BI__builtin_uaddll_overflow: 12522 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12523 : LHS.uadd_ov(RHS, DidOverflow); 12524 break; 12525 case Builtin::BI__builtin_sub_overflow: 12526 case Builtin::BI__builtin_ssub_overflow: 12527 case Builtin::BI__builtin_ssubl_overflow: 12528 case Builtin::BI__builtin_ssubll_overflow: 12529 case Builtin::BI__builtin_usub_overflow: 12530 case Builtin::BI__builtin_usubl_overflow: 12531 case Builtin::BI__builtin_usubll_overflow: 12532 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12533 : LHS.usub_ov(RHS, DidOverflow); 12534 break; 12535 case Builtin::BI__builtin_mul_overflow: 12536 case Builtin::BI__builtin_smul_overflow: 12537 case Builtin::BI__builtin_smull_overflow: 12538 case Builtin::BI__builtin_smulll_overflow: 12539 case Builtin::BI__builtin_umul_overflow: 12540 case Builtin::BI__builtin_umull_overflow: 12541 case Builtin::BI__builtin_umulll_overflow: 12542 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12543 : LHS.umul_ov(RHS, DidOverflow); 12544 break; 12545 } 12546 12547 // In the case where multiple sizes are allowed, truncate and see if 12548 // the values are the same. 12549 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12550 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12551 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12552 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12553 // since it will give us the behavior of a TruncOrSelf in the case where 12554 // its parameter <= its size. We previously set Result to be at least the 12555 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12556 // will work exactly like TruncOrSelf. 12557 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12558 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12559 12560 if (!APSInt::isSameValue(Temp, Result)) 12561 DidOverflow = true; 12562 Result = Temp; 12563 } 12564 12565 APValue APV{Result}; 12566 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12567 return false; 12568 return Success(DidOverflow, E); 12569 } 12570 } 12571 } 12572 12573 /// Determine whether this is a pointer past the end of the complete 12574 /// object referred to by the lvalue. 12575 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12576 const LValue &LV) { 12577 // A null pointer can be viewed as being "past the end" but we don't 12578 // choose to look at it that way here. 12579 if (!LV.getLValueBase()) 12580 return false; 12581 12582 // If the designator is valid and refers to a subobject, we're not pointing 12583 // past the end. 12584 if (!LV.getLValueDesignator().Invalid && 12585 !LV.getLValueDesignator().isOnePastTheEnd()) 12586 return false; 12587 12588 // A pointer to an incomplete type might be past-the-end if the type's size is 12589 // zero. We cannot tell because the type is incomplete. 12590 QualType Ty = getType(LV.getLValueBase()); 12591 if (Ty->isIncompleteType()) 12592 return true; 12593 12594 // We're a past-the-end pointer if we point to the byte after the object, 12595 // no matter what our type or path is. 12596 auto Size = Ctx.getTypeSizeInChars(Ty); 12597 return LV.getLValueOffset() == Size; 12598 } 12599 12600 namespace { 12601 12602 /// Data recursive integer evaluator of certain binary operators. 12603 /// 12604 /// We use a data recursive algorithm for binary operators so that we are able 12605 /// to handle extreme cases of chained binary operators without causing stack 12606 /// overflow. 12607 class DataRecursiveIntBinOpEvaluator { 12608 struct EvalResult { 12609 APValue Val; 12610 bool Failed; 12611 12612 EvalResult() : Failed(false) { } 12613 12614 void swap(EvalResult &RHS) { 12615 Val.swap(RHS.Val); 12616 Failed = RHS.Failed; 12617 RHS.Failed = false; 12618 } 12619 }; 12620 12621 struct Job { 12622 const Expr *E; 12623 EvalResult LHSResult; // meaningful only for binary operator expression. 12624 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12625 12626 Job() = default; 12627 Job(Job &&) = default; 12628 12629 void startSpeculativeEval(EvalInfo &Info) { 12630 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12631 } 12632 12633 private: 12634 SpeculativeEvaluationRAII SpecEvalRAII; 12635 }; 12636 12637 SmallVector<Job, 16> Queue; 12638 12639 IntExprEvaluator &IntEval; 12640 EvalInfo &Info; 12641 APValue &FinalResult; 12642 12643 public: 12644 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12645 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12646 12647 /// True if \param E is a binary operator that we are going to handle 12648 /// data recursively. 12649 /// We handle binary operators that are comma, logical, or that have operands 12650 /// with integral or enumeration type. 12651 static bool shouldEnqueue(const BinaryOperator *E) { 12652 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12653 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12654 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12655 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12656 } 12657 12658 bool Traverse(const BinaryOperator *E) { 12659 enqueue(E); 12660 EvalResult PrevResult; 12661 while (!Queue.empty()) 12662 process(PrevResult); 12663 12664 if (PrevResult.Failed) return false; 12665 12666 FinalResult.swap(PrevResult.Val); 12667 return true; 12668 } 12669 12670 private: 12671 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12672 return IntEval.Success(Value, E, Result); 12673 } 12674 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12675 return IntEval.Success(Value, E, Result); 12676 } 12677 bool Error(const Expr *E) { 12678 return IntEval.Error(E); 12679 } 12680 bool Error(const Expr *E, diag::kind D) { 12681 return IntEval.Error(E, D); 12682 } 12683 12684 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12685 return Info.CCEDiag(E, D); 12686 } 12687 12688 // Returns true if visiting the RHS is necessary, false otherwise. 12689 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12690 bool &SuppressRHSDiags); 12691 12692 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12693 const BinaryOperator *E, APValue &Result); 12694 12695 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12696 Result.Failed = !Evaluate(Result.Val, Info, E); 12697 if (Result.Failed) 12698 Result.Val = APValue(); 12699 } 12700 12701 void process(EvalResult &Result); 12702 12703 void enqueue(const Expr *E) { 12704 E = E->IgnoreParens(); 12705 Queue.resize(Queue.size()+1); 12706 Queue.back().E = E; 12707 Queue.back().Kind = Job::AnyExprKind; 12708 } 12709 }; 12710 12711 } 12712 12713 bool DataRecursiveIntBinOpEvaluator:: 12714 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12715 bool &SuppressRHSDiags) { 12716 if (E->getOpcode() == BO_Comma) { 12717 // Ignore LHS but note if we could not evaluate it. 12718 if (LHSResult.Failed) 12719 return Info.noteSideEffect(); 12720 return true; 12721 } 12722 12723 if (E->isLogicalOp()) { 12724 bool LHSAsBool; 12725 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12726 // We were able to evaluate the LHS, see if we can get away with not 12727 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12728 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12729 Success(LHSAsBool, E, LHSResult.Val); 12730 return false; // Ignore RHS 12731 } 12732 } else { 12733 LHSResult.Failed = true; 12734 12735 // Since we weren't able to evaluate the left hand side, it 12736 // might have had side effects. 12737 if (!Info.noteSideEffect()) 12738 return false; 12739 12740 // We can't evaluate the LHS; however, sometimes the result 12741 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12742 // Don't ignore RHS and suppress diagnostics from this arm. 12743 SuppressRHSDiags = true; 12744 } 12745 12746 return true; 12747 } 12748 12749 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12750 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12751 12752 if (LHSResult.Failed && !Info.noteFailure()) 12753 return false; // Ignore RHS; 12754 12755 return true; 12756 } 12757 12758 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12759 bool IsSub) { 12760 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12761 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12762 // offsets. 12763 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12764 CharUnits &Offset = LVal.getLValueOffset(); 12765 uint64_t Offset64 = Offset.getQuantity(); 12766 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12767 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12768 : Offset64 + Index64); 12769 } 12770 12771 bool DataRecursiveIntBinOpEvaluator:: 12772 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12773 const BinaryOperator *E, APValue &Result) { 12774 if (E->getOpcode() == BO_Comma) { 12775 if (RHSResult.Failed) 12776 return false; 12777 Result = RHSResult.Val; 12778 return true; 12779 } 12780 12781 if (E->isLogicalOp()) { 12782 bool lhsResult, rhsResult; 12783 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12784 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12785 12786 if (LHSIsOK) { 12787 if (RHSIsOK) { 12788 if (E->getOpcode() == BO_LOr) 12789 return Success(lhsResult || rhsResult, E, Result); 12790 else 12791 return Success(lhsResult && rhsResult, E, Result); 12792 } 12793 } else { 12794 if (RHSIsOK) { 12795 // We can't evaluate the LHS; however, sometimes the result 12796 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12797 if (rhsResult == (E->getOpcode() == BO_LOr)) 12798 return Success(rhsResult, E, Result); 12799 } 12800 } 12801 12802 return false; 12803 } 12804 12805 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12806 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12807 12808 if (LHSResult.Failed || RHSResult.Failed) 12809 return false; 12810 12811 const APValue &LHSVal = LHSResult.Val; 12812 const APValue &RHSVal = RHSResult.Val; 12813 12814 // Handle cases like (unsigned long)&a + 4. 12815 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12816 Result = LHSVal; 12817 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12818 return true; 12819 } 12820 12821 // Handle cases like 4 + (unsigned long)&a 12822 if (E->getOpcode() == BO_Add && 12823 RHSVal.isLValue() && LHSVal.isInt()) { 12824 Result = RHSVal; 12825 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12826 return true; 12827 } 12828 12829 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12830 // Handle (intptr_t)&&A - (intptr_t)&&B. 12831 if (!LHSVal.getLValueOffset().isZero() || 12832 !RHSVal.getLValueOffset().isZero()) 12833 return false; 12834 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12835 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12836 if (!LHSExpr || !RHSExpr) 12837 return false; 12838 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12839 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12840 if (!LHSAddrExpr || !RHSAddrExpr) 12841 return false; 12842 // Make sure both labels come from the same function. 12843 if (LHSAddrExpr->getLabel()->getDeclContext() != 12844 RHSAddrExpr->getLabel()->getDeclContext()) 12845 return false; 12846 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12847 return true; 12848 } 12849 12850 // All the remaining cases expect both operands to be an integer 12851 if (!LHSVal.isInt() || !RHSVal.isInt()) 12852 return Error(E); 12853 12854 // Set up the width and signedness manually, in case it can't be deduced 12855 // from the operation we're performing. 12856 // FIXME: Don't do this in the cases where we can deduce it. 12857 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12858 E->getType()->isUnsignedIntegerOrEnumerationType()); 12859 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12860 RHSVal.getInt(), Value)) 12861 return false; 12862 return Success(Value, E, Result); 12863 } 12864 12865 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12866 Job &job = Queue.back(); 12867 12868 switch (job.Kind) { 12869 case Job::AnyExprKind: { 12870 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12871 if (shouldEnqueue(Bop)) { 12872 job.Kind = Job::BinOpKind; 12873 enqueue(Bop->getLHS()); 12874 return; 12875 } 12876 } 12877 12878 EvaluateExpr(job.E, Result); 12879 Queue.pop_back(); 12880 return; 12881 } 12882 12883 case Job::BinOpKind: { 12884 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12885 bool SuppressRHSDiags = false; 12886 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12887 Queue.pop_back(); 12888 return; 12889 } 12890 if (SuppressRHSDiags) 12891 job.startSpeculativeEval(Info); 12892 job.LHSResult.swap(Result); 12893 job.Kind = Job::BinOpVisitedLHSKind; 12894 enqueue(Bop->getRHS()); 12895 return; 12896 } 12897 12898 case Job::BinOpVisitedLHSKind: { 12899 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12900 EvalResult RHS; 12901 RHS.swap(Result); 12902 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12903 Queue.pop_back(); 12904 return; 12905 } 12906 } 12907 12908 llvm_unreachable("Invalid Job::Kind!"); 12909 } 12910 12911 namespace { 12912 enum class CmpResult { 12913 Unequal, 12914 Less, 12915 Equal, 12916 Greater, 12917 Unordered, 12918 }; 12919 } 12920 12921 template <class SuccessCB, class AfterCB> 12922 static bool 12923 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12924 SuccessCB &&Success, AfterCB &&DoAfter) { 12925 assert(!E->isValueDependent()); 12926 assert(E->isComparisonOp() && "expected comparison operator"); 12927 assert((E->getOpcode() == BO_Cmp || 12928 E->getType()->isIntegralOrEnumerationType()) && 12929 "unsupported binary expression evaluation"); 12930 auto Error = [&](const Expr *E) { 12931 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12932 return false; 12933 }; 12934 12935 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12936 bool IsEquality = E->isEqualityOp(); 12937 12938 QualType LHSTy = E->getLHS()->getType(); 12939 QualType RHSTy = E->getRHS()->getType(); 12940 12941 if (LHSTy->isIntegralOrEnumerationType() && 12942 RHSTy->isIntegralOrEnumerationType()) { 12943 APSInt LHS, RHS; 12944 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12945 if (!LHSOK && !Info.noteFailure()) 12946 return false; 12947 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12948 return false; 12949 if (LHS < RHS) 12950 return Success(CmpResult::Less, E); 12951 if (LHS > RHS) 12952 return Success(CmpResult::Greater, E); 12953 return Success(CmpResult::Equal, E); 12954 } 12955 12956 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12957 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12958 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12959 12960 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12961 if (!LHSOK && !Info.noteFailure()) 12962 return false; 12963 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12964 return false; 12965 if (LHSFX < RHSFX) 12966 return Success(CmpResult::Less, E); 12967 if (LHSFX > RHSFX) 12968 return Success(CmpResult::Greater, E); 12969 return Success(CmpResult::Equal, E); 12970 } 12971 12972 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12973 ComplexValue LHS, RHS; 12974 bool LHSOK; 12975 if (E->isAssignmentOp()) { 12976 LValue LV; 12977 EvaluateLValue(E->getLHS(), LV, Info); 12978 LHSOK = false; 12979 } else if (LHSTy->isRealFloatingType()) { 12980 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12981 if (LHSOK) { 12982 LHS.makeComplexFloat(); 12983 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12984 } 12985 } else { 12986 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12987 } 12988 if (!LHSOK && !Info.noteFailure()) 12989 return false; 12990 12991 if (E->getRHS()->getType()->isRealFloatingType()) { 12992 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12993 return false; 12994 RHS.makeComplexFloat(); 12995 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12996 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12997 return false; 12998 12999 if (LHS.isComplexFloat()) { 13000 APFloat::cmpResult CR_r = 13001 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 13002 APFloat::cmpResult CR_i = 13003 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 13004 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 13005 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 13006 } else { 13007 assert(IsEquality && "invalid complex comparison"); 13008 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 13009 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 13010 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 13011 } 13012 } 13013 13014 if (LHSTy->isRealFloatingType() && 13015 RHSTy->isRealFloatingType()) { 13016 APFloat RHS(0.0), LHS(0.0); 13017 13018 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 13019 if (!LHSOK && !Info.noteFailure()) 13020 return false; 13021 13022 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 13023 return false; 13024 13025 assert(E->isComparisonOp() && "Invalid binary operator!"); 13026 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 13027 if (!Info.InConstantContext && 13028 APFloatCmpResult == APFloat::cmpUnordered && 13029 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 13030 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 13031 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 13032 return false; 13033 } 13034 auto GetCmpRes = [&]() { 13035 switch (APFloatCmpResult) { 13036 case APFloat::cmpEqual: 13037 return CmpResult::Equal; 13038 case APFloat::cmpLessThan: 13039 return CmpResult::Less; 13040 case APFloat::cmpGreaterThan: 13041 return CmpResult::Greater; 13042 case APFloat::cmpUnordered: 13043 return CmpResult::Unordered; 13044 } 13045 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 13046 }; 13047 return Success(GetCmpRes(), E); 13048 } 13049 13050 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 13051 LValue LHSValue, RHSValue; 13052 13053 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13054 if (!LHSOK && !Info.noteFailure()) 13055 return false; 13056 13057 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13058 return false; 13059 13060 // Reject differing bases from the normal codepath; we special-case 13061 // comparisons to null. 13062 if (!HasSameBase(LHSValue, RHSValue)) { 13063 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) { 13064 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType()); 13065 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType()); 13066 Info.FFDiag(E, DiagID) 13067 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS); 13068 return false; 13069 }; 13070 // Inequalities and subtractions between unrelated pointers have 13071 // unspecified or undefined behavior. 13072 if (!IsEquality) 13073 return DiagComparison( 13074 diag::note_constexpr_pointer_comparison_unspecified); 13075 // A constant address may compare equal to the address of a symbol. 13076 // The one exception is that address of an object cannot compare equal 13077 // to a null pointer constant. 13078 // TODO: Should we restrict this to actual null pointers, and exclude the 13079 // case of zero cast to pointer type? 13080 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 13081 (!RHSValue.Base && !RHSValue.Offset.isZero())) 13082 return DiagComparison(diag::note_constexpr_pointer_constant_comparison, 13083 !RHSValue.Base); 13084 // It's implementation-defined whether distinct literals will have 13085 // distinct addresses. In clang, the result of such a comparison is 13086 // unspecified, so it is not a constant expression. However, we do know 13087 // that the address of a literal will be non-null. 13088 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 13089 LHSValue.Base && RHSValue.Base) 13090 return DiagComparison(diag::note_constexpr_literal_comparison); 13091 // We can't tell whether weak symbols will end up pointing to the same 13092 // object. 13093 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 13094 return DiagComparison(diag::note_constexpr_pointer_weak_comparison, 13095 !IsWeakLValue(LHSValue)); 13096 // We can't compare the address of the start of one object with the 13097 // past-the-end address of another object, per C++ DR1652. 13098 if (LHSValue.Base && LHSValue.Offset.isZero() && 13099 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) 13100 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, 13101 true); 13102 if (RHSValue.Base && RHSValue.Offset.isZero() && 13103 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)) 13104 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end, 13105 false); 13106 // We can't tell whether an object is at the same address as another 13107 // zero sized object. 13108 if ((RHSValue.Base && isZeroSized(LHSValue)) || 13109 (LHSValue.Base && isZeroSized(RHSValue))) 13110 return DiagComparison( 13111 diag::note_constexpr_pointer_comparison_zero_sized); 13112 return Success(CmpResult::Unequal, E); 13113 } 13114 13115 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13116 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13117 13118 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13119 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13120 13121 // C++11 [expr.rel]p3: 13122 // Pointers to void (after pointer conversions) can be compared, with a 13123 // result defined as follows: If both pointers represent the same 13124 // address or are both the null pointer value, the result is true if the 13125 // operator is <= or >= and false otherwise; otherwise the result is 13126 // unspecified. 13127 // We interpret this as applying to pointers to *cv* void. 13128 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 13129 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 13130 13131 // C++11 [expr.rel]p2: 13132 // - If two pointers point to non-static data members of the same object, 13133 // or to subobjects or array elements fo such members, recursively, the 13134 // pointer to the later declared member compares greater provided the 13135 // two members have the same access control and provided their class is 13136 // not a union. 13137 // [...] 13138 // - Otherwise pointer comparisons are unspecified. 13139 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 13140 bool WasArrayIndex; 13141 unsigned Mismatch = FindDesignatorMismatch( 13142 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 13143 // At the point where the designators diverge, the comparison has a 13144 // specified value if: 13145 // - we are comparing array indices 13146 // - we are comparing fields of a union, or fields with the same access 13147 // Otherwise, the result is unspecified and thus the comparison is not a 13148 // constant expression. 13149 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 13150 Mismatch < RHSDesignator.Entries.size()) { 13151 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 13152 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 13153 if (!LF && !RF) 13154 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 13155 else if (!LF) 13156 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 13157 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 13158 << RF->getParent() << RF; 13159 else if (!RF) 13160 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 13161 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 13162 << LF->getParent() << LF; 13163 else if (!LF->getParent()->isUnion() && 13164 LF->getAccess() != RF->getAccess()) 13165 Info.CCEDiag(E, 13166 diag::note_constexpr_pointer_comparison_differing_access) 13167 << LF << LF->getAccess() << RF << RF->getAccess() 13168 << LF->getParent(); 13169 } 13170 } 13171 13172 // The comparison here must be unsigned, and performed with the same 13173 // width as the pointer. 13174 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 13175 uint64_t CompareLHS = LHSOffset.getQuantity(); 13176 uint64_t CompareRHS = RHSOffset.getQuantity(); 13177 assert(PtrSize <= 64 && "Unexpected pointer width"); 13178 uint64_t Mask = ~0ULL >> (64 - PtrSize); 13179 CompareLHS &= Mask; 13180 CompareRHS &= Mask; 13181 13182 // If there is a base and this is a relational operator, we can only 13183 // compare pointers within the object in question; otherwise, the result 13184 // depends on where the object is located in memory. 13185 if (!LHSValue.Base.isNull() && IsRelational) { 13186 QualType BaseTy = getType(LHSValue.Base); 13187 if (BaseTy->isIncompleteType()) 13188 return Error(E); 13189 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 13190 uint64_t OffsetLimit = Size.getQuantity(); 13191 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 13192 return Error(E); 13193 } 13194 13195 if (CompareLHS < CompareRHS) 13196 return Success(CmpResult::Less, E); 13197 if (CompareLHS > CompareRHS) 13198 return Success(CmpResult::Greater, E); 13199 return Success(CmpResult::Equal, E); 13200 } 13201 13202 if (LHSTy->isMemberPointerType()) { 13203 assert(IsEquality && "unexpected member pointer operation"); 13204 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 13205 13206 MemberPtr LHSValue, RHSValue; 13207 13208 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 13209 if (!LHSOK && !Info.noteFailure()) 13210 return false; 13211 13212 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13213 return false; 13214 13215 // If either operand is a pointer to a weak function, the comparison is not 13216 // constant. 13217 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) { 13218 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison) 13219 << LHSValue.getDecl(); 13220 return false; 13221 } 13222 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) { 13223 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison) 13224 << RHSValue.getDecl(); 13225 return false; 13226 } 13227 13228 // C++11 [expr.eq]p2: 13229 // If both operands are null, they compare equal. Otherwise if only one is 13230 // null, they compare unequal. 13231 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 13232 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 13233 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13234 } 13235 13236 // Otherwise if either is a pointer to a virtual member function, the 13237 // result is unspecified. 13238 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 13239 if (MD->isVirtual()) 13240 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13241 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 13242 if (MD->isVirtual()) 13243 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 13244 13245 // Otherwise they compare equal if and only if they would refer to the 13246 // same member of the same most derived object or the same subobject if 13247 // they were dereferenced with a hypothetical object of the associated 13248 // class type. 13249 bool Equal = LHSValue == RHSValue; 13250 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13251 } 13252 13253 if (LHSTy->isNullPtrType()) { 13254 assert(E->isComparisonOp() && "unexpected nullptr operation"); 13255 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 13256 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 13257 // are compared, the result is true of the operator is <=, >= or ==, and 13258 // false otherwise. 13259 return Success(CmpResult::Equal, E); 13260 } 13261 13262 return DoAfter(); 13263 } 13264 13265 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 13266 if (!CheckLiteralType(Info, E)) 13267 return false; 13268 13269 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13270 ComparisonCategoryResult CCR; 13271 switch (CR) { 13272 case CmpResult::Unequal: 13273 llvm_unreachable("should never produce Unequal for three-way comparison"); 13274 case CmpResult::Less: 13275 CCR = ComparisonCategoryResult::Less; 13276 break; 13277 case CmpResult::Equal: 13278 CCR = ComparisonCategoryResult::Equal; 13279 break; 13280 case CmpResult::Greater: 13281 CCR = ComparisonCategoryResult::Greater; 13282 break; 13283 case CmpResult::Unordered: 13284 CCR = ComparisonCategoryResult::Unordered; 13285 break; 13286 } 13287 // Evaluation succeeded. Lookup the information for the comparison category 13288 // type and fetch the VarDecl for the result. 13289 const ComparisonCategoryInfo &CmpInfo = 13290 Info.Ctx.CompCategories.getInfoForType(E->getType()); 13291 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 13292 // Check and evaluate the result as a constant expression. 13293 LValue LV; 13294 LV.set(VD); 13295 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13296 return false; 13297 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 13298 ConstantExprKind::Normal); 13299 }; 13300 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13301 return ExprEvaluatorBaseTy::VisitBinCmp(E); 13302 }); 13303 } 13304 13305 bool RecordExprEvaluator::VisitCXXParenListInitExpr( 13306 const CXXParenListInitExpr *E) { 13307 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs()); 13308 } 13309 13310 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13311 // We don't support assignment in C. C++ assignments don't get here because 13312 // assignment is an lvalue in C++. 13313 if (E->isAssignmentOp()) { 13314 Error(E); 13315 if (!Info.noteFailure()) 13316 return false; 13317 } 13318 13319 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 13320 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 13321 13322 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 13323 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13324 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13325 13326 if (E->isComparisonOp()) { 13327 // Evaluate builtin binary comparisons by evaluating them as three-way 13328 // comparisons and then translating the result. 13329 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13330 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13331 "should only produce Unequal for equality comparisons"); 13332 bool IsEqual = CR == CmpResult::Equal, 13333 IsLess = CR == CmpResult::Less, 13334 IsGreater = CR == CmpResult::Greater; 13335 auto Op = E->getOpcode(); 13336 switch (Op) { 13337 default: 13338 llvm_unreachable("unsupported binary operator"); 13339 case BO_EQ: 13340 case BO_NE: 13341 return Success(IsEqual == (Op == BO_EQ), E); 13342 case BO_LT: 13343 return Success(IsLess, E); 13344 case BO_GT: 13345 return Success(IsGreater, E); 13346 case BO_LE: 13347 return Success(IsEqual || IsLess, E); 13348 case BO_GE: 13349 return Success(IsEqual || IsGreater, E); 13350 } 13351 }; 13352 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13353 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13354 }); 13355 } 13356 13357 QualType LHSTy = E->getLHS()->getType(); 13358 QualType RHSTy = E->getRHS()->getType(); 13359 13360 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13361 E->getOpcode() == BO_Sub) { 13362 LValue LHSValue, RHSValue; 13363 13364 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13365 if (!LHSOK && !Info.noteFailure()) 13366 return false; 13367 13368 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13369 return false; 13370 13371 // Reject differing bases from the normal codepath; we special-case 13372 // comparisons to null. 13373 if (!HasSameBase(LHSValue, RHSValue)) { 13374 // Handle &&A - &&B. 13375 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13376 return Error(E); 13377 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13378 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13379 if (!LHSExpr || !RHSExpr) 13380 return Error(E); 13381 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13382 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13383 if (!LHSAddrExpr || !RHSAddrExpr) 13384 return Error(E); 13385 // Make sure both labels come from the same function. 13386 if (LHSAddrExpr->getLabel()->getDeclContext() != 13387 RHSAddrExpr->getLabel()->getDeclContext()) 13388 return Error(E); 13389 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13390 } 13391 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13392 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13393 13394 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13395 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13396 13397 // C++11 [expr.add]p6: 13398 // Unless both pointers point to elements of the same array object, or 13399 // one past the last element of the array object, the behavior is 13400 // undefined. 13401 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13402 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13403 RHSDesignator)) 13404 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13405 13406 QualType Type = E->getLHS()->getType(); 13407 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13408 13409 CharUnits ElementSize; 13410 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13411 return false; 13412 13413 // As an extension, a type may have zero size (empty struct or union in 13414 // C, array of zero length). Pointer subtraction in such cases has 13415 // undefined behavior, so is not constant. 13416 if (ElementSize.isZero()) { 13417 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13418 << ElementType; 13419 return false; 13420 } 13421 13422 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13423 // and produce incorrect results when it overflows. Such behavior 13424 // appears to be non-conforming, but is common, so perhaps we should 13425 // assume the standard intended for such cases to be undefined behavior 13426 // and check for them. 13427 13428 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13429 // overflow in the final conversion to ptrdiff_t. 13430 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13431 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13432 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13433 false); 13434 APSInt TrueResult = (LHS - RHS) / ElemSize; 13435 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13436 13437 if (Result.extend(65) != TrueResult && 13438 !HandleOverflow(Info, E, TrueResult, E->getType())) 13439 return false; 13440 return Success(Result, E); 13441 } 13442 13443 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13444 } 13445 13446 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13447 /// a result as the expression's type. 13448 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13449 const UnaryExprOrTypeTraitExpr *E) { 13450 switch(E->getKind()) { 13451 case UETT_PreferredAlignOf: 13452 case UETT_AlignOf: { 13453 if (E->isArgumentType()) 13454 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13455 E); 13456 else 13457 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13458 E); 13459 } 13460 13461 case UETT_VecStep: { 13462 QualType Ty = E->getTypeOfArgument(); 13463 13464 if (Ty->isVectorType()) { 13465 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13466 13467 // The vec_step built-in functions that take a 3-component 13468 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13469 if (n == 3) 13470 n = 4; 13471 13472 return Success(n, E); 13473 } else 13474 return Success(1, E); 13475 } 13476 13477 case UETT_SizeOf: { 13478 QualType SrcTy = E->getTypeOfArgument(); 13479 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13480 // the result is the size of the referenced type." 13481 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13482 SrcTy = Ref->getPointeeType(); 13483 13484 CharUnits Sizeof; 13485 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13486 return false; 13487 return Success(Sizeof, E); 13488 } 13489 case UETT_OpenMPRequiredSimdAlign: 13490 assert(E->isArgumentType()); 13491 return Success( 13492 Info.Ctx.toCharUnitsFromBits( 13493 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13494 .getQuantity(), 13495 E); 13496 } 13497 13498 llvm_unreachable("unknown expr/type trait"); 13499 } 13500 13501 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13502 CharUnits Result; 13503 unsigned n = OOE->getNumComponents(); 13504 if (n == 0) 13505 return Error(OOE); 13506 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13507 for (unsigned i = 0; i != n; ++i) { 13508 OffsetOfNode ON = OOE->getComponent(i); 13509 switch (ON.getKind()) { 13510 case OffsetOfNode::Array: { 13511 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13512 APSInt IdxResult; 13513 if (!EvaluateInteger(Idx, IdxResult, Info)) 13514 return false; 13515 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13516 if (!AT) 13517 return Error(OOE); 13518 CurrentType = AT->getElementType(); 13519 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13520 Result += IdxResult.getSExtValue() * ElementSize; 13521 break; 13522 } 13523 13524 case OffsetOfNode::Field: { 13525 FieldDecl *MemberDecl = ON.getField(); 13526 const RecordType *RT = CurrentType->getAs<RecordType>(); 13527 if (!RT) 13528 return Error(OOE); 13529 RecordDecl *RD = RT->getDecl(); 13530 if (RD->isInvalidDecl()) return false; 13531 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13532 unsigned i = MemberDecl->getFieldIndex(); 13533 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13534 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13535 CurrentType = MemberDecl->getType().getNonReferenceType(); 13536 break; 13537 } 13538 13539 case OffsetOfNode::Identifier: 13540 llvm_unreachable("dependent __builtin_offsetof"); 13541 13542 case OffsetOfNode::Base: { 13543 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13544 if (BaseSpec->isVirtual()) 13545 return Error(OOE); 13546 13547 // Find the layout of the class whose base we are looking into. 13548 const RecordType *RT = CurrentType->getAs<RecordType>(); 13549 if (!RT) 13550 return Error(OOE); 13551 RecordDecl *RD = RT->getDecl(); 13552 if (RD->isInvalidDecl()) return false; 13553 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13554 13555 // Find the base class itself. 13556 CurrentType = BaseSpec->getType(); 13557 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13558 if (!BaseRT) 13559 return Error(OOE); 13560 13561 // Add the offset to the base. 13562 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13563 break; 13564 } 13565 } 13566 } 13567 return Success(Result, OOE); 13568 } 13569 13570 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13571 switch (E->getOpcode()) { 13572 default: 13573 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13574 // See C99 6.6p3. 13575 return Error(E); 13576 case UO_Extension: 13577 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13578 // If so, we could clear the diagnostic ID. 13579 return Visit(E->getSubExpr()); 13580 case UO_Plus: 13581 // The result is just the value. 13582 return Visit(E->getSubExpr()); 13583 case UO_Minus: { 13584 if (!Visit(E->getSubExpr())) 13585 return false; 13586 if (!Result.isInt()) return Error(E); 13587 const APSInt &Value = Result.getInt(); 13588 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { 13589 if (Info.checkingForUndefinedBehavior()) 13590 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13591 diag::warn_integer_constant_overflow) 13592 << toString(Value, 10) << E->getType(); 13593 13594 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13595 E->getType())) 13596 return false; 13597 } 13598 return Success(-Value, E); 13599 } 13600 case UO_Not: { 13601 if (!Visit(E->getSubExpr())) 13602 return false; 13603 if (!Result.isInt()) return Error(E); 13604 return Success(~Result.getInt(), E); 13605 } 13606 case UO_LNot: { 13607 bool bres; 13608 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13609 return false; 13610 return Success(!bres, E); 13611 } 13612 } 13613 } 13614 13615 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13616 /// result type is integer. 13617 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13618 const Expr *SubExpr = E->getSubExpr(); 13619 QualType DestType = E->getType(); 13620 QualType SrcType = SubExpr->getType(); 13621 13622 switch (E->getCastKind()) { 13623 case CK_BaseToDerived: 13624 case CK_DerivedToBase: 13625 case CK_UncheckedDerivedToBase: 13626 case CK_Dynamic: 13627 case CK_ToUnion: 13628 case CK_ArrayToPointerDecay: 13629 case CK_FunctionToPointerDecay: 13630 case CK_NullToPointer: 13631 case CK_NullToMemberPointer: 13632 case CK_BaseToDerivedMemberPointer: 13633 case CK_DerivedToBaseMemberPointer: 13634 case CK_ReinterpretMemberPointer: 13635 case CK_ConstructorConversion: 13636 case CK_IntegralToPointer: 13637 case CK_ToVoid: 13638 case CK_VectorSplat: 13639 case CK_IntegralToFloating: 13640 case CK_FloatingCast: 13641 case CK_CPointerToObjCPointerCast: 13642 case CK_BlockPointerToObjCPointerCast: 13643 case CK_AnyPointerToBlockPointerCast: 13644 case CK_ObjCObjectLValueCast: 13645 case CK_FloatingRealToComplex: 13646 case CK_FloatingComplexToReal: 13647 case CK_FloatingComplexCast: 13648 case CK_FloatingComplexToIntegralComplex: 13649 case CK_IntegralRealToComplex: 13650 case CK_IntegralComplexCast: 13651 case CK_IntegralComplexToFloatingComplex: 13652 case CK_BuiltinFnToFnPtr: 13653 case CK_ZeroToOCLOpaqueType: 13654 case CK_NonAtomicToAtomic: 13655 case CK_AddressSpaceConversion: 13656 case CK_IntToOCLSampler: 13657 case CK_FloatingToFixedPoint: 13658 case CK_FixedPointToFloating: 13659 case CK_FixedPointCast: 13660 case CK_IntegralToFixedPoint: 13661 case CK_MatrixCast: 13662 llvm_unreachable("invalid cast kind for integral value"); 13663 13664 case CK_BitCast: 13665 case CK_Dependent: 13666 case CK_LValueBitCast: 13667 case CK_ARCProduceObject: 13668 case CK_ARCConsumeObject: 13669 case CK_ARCReclaimReturnedObject: 13670 case CK_ARCExtendBlockObject: 13671 case CK_CopyAndAutoreleaseBlockObject: 13672 return Error(E); 13673 13674 case CK_UserDefinedConversion: 13675 case CK_LValueToRValue: 13676 case CK_AtomicToNonAtomic: 13677 case CK_NoOp: 13678 case CK_LValueToRValueBitCast: 13679 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13680 13681 case CK_MemberPointerToBoolean: 13682 case CK_PointerToBoolean: 13683 case CK_IntegralToBoolean: 13684 case CK_FloatingToBoolean: 13685 case CK_BooleanToSignedIntegral: 13686 case CK_FloatingComplexToBoolean: 13687 case CK_IntegralComplexToBoolean: { 13688 bool BoolResult; 13689 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13690 return false; 13691 uint64_t IntResult = BoolResult; 13692 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13693 IntResult = (uint64_t)-1; 13694 return Success(IntResult, E); 13695 } 13696 13697 case CK_FixedPointToIntegral: { 13698 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13699 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13700 return false; 13701 bool Overflowed; 13702 llvm::APSInt Result = Src.convertToInt( 13703 Info.Ctx.getIntWidth(DestType), 13704 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13705 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13706 return false; 13707 return Success(Result, E); 13708 } 13709 13710 case CK_FixedPointToBoolean: { 13711 // Unsigned padding does not affect this. 13712 APValue Val; 13713 if (!Evaluate(Val, Info, SubExpr)) 13714 return false; 13715 return Success(Val.getFixedPoint().getBoolValue(), E); 13716 } 13717 13718 case CK_IntegralCast: { 13719 if (!Visit(SubExpr)) 13720 return false; 13721 13722 if (!Result.isInt()) { 13723 // Allow casts of address-of-label differences if they are no-ops 13724 // or narrowing. (The narrowing case isn't actually guaranteed to 13725 // be constant-evaluatable except in some narrow cases which are hard 13726 // to detect here. We let it through on the assumption the user knows 13727 // what they are doing.) 13728 if (Result.isAddrLabelDiff()) 13729 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13730 // Only allow casts of lvalues if they are lossless. 13731 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13732 } 13733 13734 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext && 13735 Info.EvalMode == EvalInfo::EM_ConstantExpression && 13736 DestType->isEnumeralType()) { 13737 13738 bool ConstexprVar = true; 13739 13740 // We know if we are here that we are in a context that we might require 13741 // a constant expression or a context that requires a constant 13742 // value. But if we are initializing a value we don't know if it is a 13743 // constexpr variable or not. We can check the EvaluatingDecl to determine 13744 // if it constexpr or not. If not then we don't want to emit a diagnostic. 13745 if (const auto *VD = dyn_cast_or_null<VarDecl>( 13746 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) 13747 ConstexprVar = VD->isConstexpr(); 13748 13749 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType()); 13750 const EnumDecl *ED = ET->getDecl(); 13751 // Check that the value is within the range of the enumeration values. 13752 // 13753 // This corressponds to [expr.static.cast]p10 which says: 13754 // A value of integral or enumeration type can be explicitly converted 13755 // to a complete enumeration type ... If the enumeration type does not 13756 // have a fixed underlying type, the value is unchanged if the original 13757 // value is within the range of the enumeration values ([dcl.enum]), and 13758 // otherwise, the behavior is undefined. 13759 // 13760 // This was resolved as part of DR2338 which has CD5 status. 13761 if (!ED->isFixed()) { 13762 llvm::APInt Min; 13763 llvm::APInt Max; 13764 13765 ED->getValueRange(Max, Min); 13766 --Max; 13767 13768 if (ED->getNumNegativeBits() && ConstexprVar && 13769 (Max.slt(Result.getInt().getSExtValue()) || 13770 Min.sgt(Result.getInt().getSExtValue()))) 13771 Info.Ctx.getDiagnostics().Report( 13772 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range) 13773 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue() 13774 << Max.getSExtValue() << ED; 13775 else if (!ED->getNumNegativeBits() && ConstexprVar && 13776 Max.ult(Result.getInt().getZExtValue())) 13777 Info.Ctx.getDiagnostics().Report( 13778 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range) 13779 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue() 13780 << Max.getZExtValue() << ED; 13781 } 13782 } 13783 13784 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13785 Result.getInt()), E); 13786 } 13787 13788 case CK_PointerToIntegral: { 13789 CCEDiag(E, diag::note_constexpr_invalid_cast) 13790 << 2 << Info.Ctx.getLangOpts().CPlusPlus; 13791 13792 LValue LV; 13793 if (!EvaluatePointer(SubExpr, LV, Info)) 13794 return false; 13795 13796 if (LV.getLValueBase()) { 13797 // Only allow based lvalue casts if they are lossless. 13798 // FIXME: Allow a larger integer size than the pointer size, and allow 13799 // narrowing back down to pointer width in subsequent integral casts. 13800 // FIXME: Check integer type's active bits, not its type size. 13801 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13802 return Error(E); 13803 13804 LV.Designator.setInvalid(); 13805 LV.moveInto(Result); 13806 return true; 13807 } 13808 13809 APSInt AsInt; 13810 APValue V; 13811 LV.moveInto(V); 13812 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13813 llvm_unreachable("Can't cast this!"); 13814 13815 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13816 } 13817 13818 case CK_IntegralComplexToReal: { 13819 ComplexValue C; 13820 if (!EvaluateComplex(SubExpr, C, Info)) 13821 return false; 13822 return Success(C.getComplexIntReal(), E); 13823 } 13824 13825 case CK_FloatingToIntegral: { 13826 APFloat F(0.0); 13827 if (!EvaluateFloat(SubExpr, F, Info)) 13828 return false; 13829 13830 APSInt Value; 13831 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13832 return false; 13833 return Success(Value, E); 13834 } 13835 } 13836 13837 llvm_unreachable("unknown cast resulting in integral value"); 13838 } 13839 13840 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13841 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13842 ComplexValue LV; 13843 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13844 return false; 13845 if (!LV.isComplexInt()) 13846 return Error(E); 13847 return Success(LV.getComplexIntReal(), E); 13848 } 13849 13850 return Visit(E->getSubExpr()); 13851 } 13852 13853 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13854 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13855 ComplexValue LV; 13856 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13857 return false; 13858 if (!LV.isComplexInt()) 13859 return Error(E); 13860 return Success(LV.getComplexIntImag(), E); 13861 } 13862 13863 VisitIgnoredValue(E->getSubExpr()); 13864 return Success(0, E); 13865 } 13866 13867 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13868 return Success(E->getPackLength(), E); 13869 } 13870 13871 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13872 return Success(E->getValue(), E); 13873 } 13874 13875 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13876 const ConceptSpecializationExpr *E) { 13877 return Success(E->isSatisfied(), E); 13878 } 13879 13880 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13881 return Success(E->isSatisfied(), E); 13882 } 13883 13884 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13885 switch (E->getOpcode()) { 13886 default: 13887 // Invalid unary operators 13888 return Error(E); 13889 case UO_Plus: 13890 // The result is just the value. 13891 return Visit(E->getSubExpr()); 13892 case UO_Minus: { 13893 if (!Visit(E->getSubExpr())) return false; 13894 if (!Result.isFixedPoint()) 13895 return Error(E); 13896 bool Overflowed; 13897 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13898 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13899 return false; 13900 return Success(Negated, E); 13901 } 13902 case UO_LNot: { 13903 bool bres; 13904 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13905 return false; 13906 return Success(!bres, E); 13907 } 13908 } 13909 } 13910 13911 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13912 const Expr *SubExpr = E->getSubExpr(); 13913 QualType DestType = E->getType(); 13914 assert(DestType->isFixedPointType() && 13915 "Expected destination type to be a fixed point type"); 13916 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13917 13918 switch (E->getCastKind()) { 13919 case CK_FixedPointCast: { 13920 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13921 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13922 return false; 13923 bool Overflowed; 13924 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13925 if (Overflowed) { 13926 if (Info.checkingForUndefinedBehavior()) 13927 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13928 diag::warn_fixedpoint_constant_overflow) 13929 << Result.toString() << E->getType(); 13930 if (!HandleOverflow(Info, E, Result, E->getType())) 13931 return false; 13932 } 13933 return Success(Result, E); 13934 } 13935 case CK_IntegralToFixedPoint: { 13936 APSInt Src; 13937 if (!EvaluateInteger(SubExpr, Src, Info)) 13938 return false; 13939 13940 bool Overflowed; 13941 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13942 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13943 13944 if (Overflowed) { 13945 if (Info.checkingForUndefinedBehavior()) 13946 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13947 diag::warn_fixedpoint_constant_overflow) 13948 << IntResult.toString() << E->getType(); 13949 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13950 return false; 13951 } 13952 13953 return Success(IntResult, E); 13954 } 13955 case CK_FloatingToFixedPoint: { 13956 APFloat Src(0.0); 13957 if (!EvaluateFloat(SubExpr, Src, Info)) 13958 return false; 13959 13960 bool Overflowed; 13961 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13962 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13963 13964 if (Overflowed) { 13965 if (Info.checkingForUndefinedBehavior()) 13966 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13967 diag::warn_fixedpoint_constant_overflow) 13968 << Result.toString() << E->getType(); 13969 if (!HandleOverflow(Info, E, Result, E->getType())) 13970 return false; 13971 } 13972 13973 return Success(Result, E); 13974 } 13975 case CK_NoOp: 13976 case CK_LValueToRValue: 13977 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13978 default: 13979 return Error(E); 13980 } 13981 } 13982 13983 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13984 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13985 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13986 13987 const Expr *LHS = E->getLHS(); 13988 const Expr *RHS = E->getRHS(); 13989 FixedPointSemantics ResultFXSema = 13990 Info.Ctx.getFixedPointSemantics(E->getType()); 13991 13992 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13993 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13994 return false; 13995 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13996 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13997 return false; 13998 13999 bool OpOverflow = false, ConversionOverflow = false; 14000 APFixedPoint Result(LHSFX.getSemantics()); 14001 switch (E->getOpcode()) { 14002 case BO_Add: { 14003 Result = LHSFX.add(RHSFX, &OpOverflow) 14004 .convert(ResultFXSema, &ConversionOverflow); 14005 break; 14006 } 14007 case BO_Sub: { 14008 Result = LHSFX.sub(RHSFX, &OpOverflow) 14009 .convert(ResultFXSema, &ConversionOverflow); 14010 break; 14011 } 14012 case BO_Mul: { 14013 Result = LHSFX.mul(RHSFX, &OpOverflow) 14014 .convert(ResultFXSema, &ConversionOverflow); 14015 break; 14016 } 14017 case BO_Div: { 14018 if (RHSFX.getValue() == 0) { 14019 Info.FFDiag(E, diag::note_expr_divide_by_zero); 14020 return false; 14021 } 14022 Result = LHSFX.div(RHSFX, &OpOverflow) 14023 .convert(ResultFXSema, &ConversionOverflow); 14024 break; 14025 } 14026 case BO_Shl: 14027 case BO_Shr: { 14028 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 14029 llvm::APSInt RHSVal = RHSFX.getValue(); 14030 14031 unsigned ShiftBW = 14032 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 14033 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 14034 // Embedded-C 4.1.6.2.2: 14035 // The right operand must be nonnegative and less than the total number 14036 // of (nonpadding) bits of the fixed-point operand ... 14037 if (RHSVal.isNegative()) 14038 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 14039 else if (Amt != RHSVal) 14040 Info.CCEDiag(E, diag::note_constexpr_large_shift) 14041 << RHSVal << E->getType() << ShiftBW; 14042 14043 if (E->getOpcode() == BO_Shl) 14044 Result = LHSFX.shl(Amt, &OpOverflow); 14045 else 14046 Result = LHSFX.shr(Amt, &OpOverflow); 14047 break; 14048 } 14049 default: 14050 return false; 14051 } 14052 if (OpOverflow || ConversionOverflow) { 14053 if (Info.checkingForUndefinedBehavior()) 14054 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 14055 diag::warn_fixedpoint_constant_overflow) 14056 << Result.toString() << E->getType(); 14057 if (!HandleOverflow(Info, E, Result, E->getType())) 14058 return false; 14059 } 14060 return Success(Result, E); 14061 } 14062 14063 //===----------------------------------------------------------------------===// 14064 // Float Evaluation 14065 //===----------------------------------------------------------------------===// 14066 14067 namespace { 14068 class FloatExprEvaluator 14069 : public ExprEvaluatorBase<FloatExprEvaluator> { 14070 APFloat &Result; 14071 public: 14072 FloatExprEvaluator(EvalInfo &info, APFloat &result) 14073 : ExprEvaluatorBaseTy(info), Result(result) {} 14074 14075 bool Success(const APValue &V, const Expr *e) { 14076 Result = V.getFloat(); 14077 return true; 14078 } 14079 14080 bool ZeroInitialization(const Expr *E) { 14081 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 14082 return true; 14083 } 14084 14085 bool VisitCallExpr(const CallExpr *E); 14086 14087 bool VisitUnaryOperator(const UnaryOperator *E); 14088 bool VisitBinaryOperator(const BinaryOperator *E); 14089 bool VisitFloatingLiteral(const FloatingLiteral *E); 14090 bool VisitCastExpr(const CastExpr *E); 14091 14092 bool VisitUnaryReal(const UnaryOperator *E); 14093 bool VisitUnaryImag(const UnaryOperator *E); 14094 14095 // FIXME: Missing: array subscript of vector, member of vector 14096 }; 14097 } // end anonymous namespace 14098 14099 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 14100 assert(!E->isValueDependent()); 14101 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 14102 return FloatExprEvaluator(Info, Result).Visit(E); 14103 } 14104 14105 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 14106 QualType ResultTy, 14107 const Expr *Arg, 14108 bool SNaN, 14109 llvm::APFloat &Result) { 14110 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 14111 if (!S) return false; 14112 14113 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 14114 14115 llvm::APInt fill; 14116 14117 // Treat empty strings as if they were zero. 14118 if (S->getString().empty()) 14119 fill = llvm::APInt(32, 0); 14120 else if (S->getString().getAsInteger(0, fill)) 14121 return false; 14122 14123 if (Context.getTargetInfo().isNan2008()) { 14124 if (SNaN) 14125 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 14126 else 14127 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 14128 } else { 14129 // Prior to IEEE 754-2008, architectures were allowed to choose whether 14130 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 14131 // a different encoding to what became a standard in 2008, and for pre- 14132 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 14133 // sNaN. This is now known as "legacy NaN" encoding. 14134 if (SNaN) 14135 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 14136 else 14137 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 14138 } 14139 14140 return true; 14141 } 14142 14143 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 14144 if (!IsConstantEvaluatedBuiltinCall(E)) 14145 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14146 14147 switch (E->getBuiltinCallee()) { 14148 default: 14149 return false; 14150 14151 case Builtin::BI__builtin_huge_val: 14152 case Builtin::BI__builtin_huge_valf: 14153 case Builtin::BI__builtin_huge_vall: 14154 case Builtin::BI__builtin_huge_valf16: 14155 case Builtin::BI__builtin_huge_valf128: 14156 case Builtin::BI__builtin_inf: 14157 case Builtin::BI__builtin_inff: 14158 case Builtin::BI__builtin_infl: 14159 case Builtin::BI__builtin_inff16: 14160 case Builtin::BI__builtin_inff128: { 14161 const llvm::fltSemantics &Sem = 14162 Info.Ctx.getFloatTypeSemantics(E->getType()); 14163 Result = llvm::APFloat::getInf(Sem); 14164 return true; 14165 } 14166 14167 case Builtin::BI__builtin_nans: 14168 case Builtin::BI__builtin_nansf: 14169 case Builtin::BI__builtin_nansl: 14170 case Builtin::BI__builtin_nansf16: 14171 case Builtin::BI__builtin_nansf128: 14172 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 14173 true, Result)) 14174 return Error(E); 14175 return true; 14176 14177 case Builtin::BI__builtin_nan: 14178 case Builtin::BI__builtin_nanf: 14179 case Builtin::BI__builtin_nanl: 14180 case Builtin::BI__builtin_nanf16: 14181 case Builtin::BI__builtin_nanf128: 14182 // If this is __builtin_nan() turn this into a nan, otherwise we 14183 // can't constant fold it. 14184 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 14185 false, Result)) 14186 return Error(E); 14187 return true; 14188 14189 case Builtin::BI__builtin_fabs: 14190 case Builtin::BI__builtin_fabsf: 14191 case Builtin::BI__builtin_fabsl: 14192 case Builtin::BI__builtin_fabsf128: 14193 // The C standard says "fabs raises no floating-point exceptions, 14194 // even if x is a signaling NaN. The returned value is independent of 14195 // the current rounding direction mode." Therefore constant folding can 14196 // proceed without regard to the floating point settings. 14197 // Reference, WG14 N2478 F.10.4.3 14198 if (!EvaluateFloat(E->getArg(0), Result, Info)) 14199 return false; 14200 14201 if (Result.isNegative()) 14202 Result.changeSign(); 14203 return true; 14204 14205 case Builtin::BI__arithmetic_fence: 14206 return EvaluateFloat(E->getArg(0), Result, Info); 14207 14208 // FIXME: Builtin::BI__builtin_powi 14209 // FIXME: Builtin::BI__builtin_powif 14210 // FIXME: Builtin::BI__builtin_powil 14211 14212 case Builtin::BI__builtin_copysign: 14213 case Builtin::BI__builtin_copysignf: 14214 case Builtin::BI__builtin_copysignl: 14215 case Builtin::BI__builtin_copysignf128: { 14216 APFloat RHS(0.); 14217 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14218 !EvaluateFloat(E->getArg(1), RHS, Info)) 14219 return false; 14220 Result.copySign(RHS); 14221 return true; 14222 } 14223 14224 case Builtin::BI__builtin_fmax: 14225 case Builtin::BI__builtin_fmaxf: 14226 case Builtin::BI__builtin_fmaxl: 14227 case Builtin::BI__builtin_fmaxf16: 14228 case Builtin::BI__builtin_fmaxf128: { 14229 // TODO: Handle sNaN. 14230 APFloat RHS(0.); 14231 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14232 !EvaluateFloat(E->getArg(1), RHS, Info)) 14233 return false; 14234 // When comparing zeroes, return +0.0 if one of the zeroes is positive. 14235 if (Result.isZero() && RHS.isZero() && Result.isNegative()) 14236 Result = RHS; 14237 else if (Result.isNaN() || RHS > Result) 14238 Result = RHS; 14239 return true; 14240 } 14241 14242 case Builtin::BI__builtin_fmin: 14243 case Builtin::BI__builtin_fminf: 14244 case Builtin::BI__builtin_fminl: 14245 case Builtin::BI__builtin_fminf16: 14246 case Builtin::BI__builtin_fminf128: { 14247 // TODO: Handle sNaN. 14248 APFloat RHS(0.); 14249 if (!EvaluateFloat(E->getArg(0), Result, Info) || 14250 !EvaluateFloat(E->getArg(1), RHS, Info)) 14251 return false; 14252 // When comparing zeroes, return -0.0 if one of the zeroes is negative. 14253 if (Result.isZero() && RHS.isZero() && RHS.isNegative()) 14254 Result = RHS; 14255 else if (Result.isNaN() || RHS < Result) 14256 Result = RHS; 14257 return true; 14258 } 14259 } 14260 } 14261 14262 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 14263 if (E->getSubExpr()->getType()->isAnyComplexType()) { 14264 ComplexValue CV; 14265 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 14266 return false; 14267 Result = CV.FloatReal; 14268 return true; 14269 } 14270 14271 return Visit(E->getSubExpr()); 14272 } 14273 14274 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 14275 if (E->getSubExpr()->getType()->isAnyComplexType()) { 14276 ComplexValue CV; 14277 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 14278 return false; 14279 Result = CV.FloatImag; 14280 return true; 14281 } 14282 14283 VisitIgnoredValue(E->getSubExpr()); 14284 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 14285 Result = llvm::APFloat::getZero(Sem); 14286 return true; 14287 } 14288 14289 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14290 switch (E->getOpcode()) { 14291 default: return Error(E); 14292 case UO_Plus: 14293 return EvaluateFloat(E->getSubExpr(), Result, Info); 14294 case UO_Minus: 14295 // In C standard, WG14 N2478 F.3 p4 14296 // "the unary - raises no floating point exceptions, 14297 // even if the operand is signalling." 14298 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 14299 return false; 14300 Result.changeSign(); 14301 return true; 14302 } 14303 } 14304 14305 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14306 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14307 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14308 14309 APFloat RHS(0.0); 14310 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 14311 if (!LHSOK && !Info.noteFailure()) 14312 return false; 14313 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 14314 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 14315 } 14316 14317 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 14318 Result = E->getValue(); 14319 return true; 14320 } 14321 14322 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 14323 const Expr* SubExpr = E->getSubExpr(); 14324 14325 switch (E->getCastKind()) { 14326 default: 14327 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14328 14329 case CK_IntegralToFloating: { 14330 APSInt IntResult; 14331 const FPOptions FPO = E->getFPFeaturesInEffect( 14332 Info.Ctx.getLangOpts()); 14333 return EvaluateInteger(SubExpr, IntResult, Info) && 14334 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 14335 IntResult, E->getType(), Result); 14336 } 14337 14338 case CK_FixedPointToFloating: { 14339 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 14340 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 14341 return false; 14342 Result = 14343 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 14344 return true; 14345 } 14346 14347 case CK_FloatingCast: { 14348 if (!Visit(SubExpr)) 14349 return false; 14350 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 14351 Result); 14352 } 14353 14354 case CK_FloatingComplexToReal: { 14355 ComplexValue V; 14356 if (!EvaluateComplex(SubExpr, V, Info)) 14357 return false; 14358 Result = V.getComplexFloatReal(); 14359 return true; 14360 } 14361 } 14362 } 14363 14364 //===----------------------------------------------------------------------===// 14365 // Complex Evaluation (for float and integer) 14366 //===----------------------------------------------------------------------===// 14367 14368 namespace { 14369 class ComplexExprEvaluator 14370 : public ExprEvaluatorBase<ComplexExprEvaluator> { 14371 ComplexValue &Result; 14372 14373 public: 14374 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 14375 : ExprEvaluatorBaseTy(info), Result(Result) {} 14376 14377 bool Success(const APValue &V, const Expr *e) { 14378 Result.setFrom(V); 14379 return true; 14380 } 14381 14382 bool ZeroInitialization(const Expr *E); 14383 14384 //===--------------------------------------------------------------------===// 14385 // Visitor Methods 14386 //===--------------------------------------------------------------------===// 14387 14388 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 14389 bool VisitCastExpr(const CastExpr *E); 14390 bool VisitBinaryOperator(const BinaryOperator *E); 14391 bool VisitUnaryOperator(const UnaryOperator *E); 14392 bool VisitInitListExpr(const InitListExpr *E); 14393 bool VisitCallExpr(const CallExpr *E); 14394 }; 14395 } // end anonymous namespace 14396 14397 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 14398 EvalInfo &Info) { 14399 assert(!E->isValueDependent()); 14400 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 14401 return ComplexExprEvaluator(Info, Result).Visit(E); 14402 } 14403 14404 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 14405 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 14406 if (ElemTy->isRealFloatingType()) { 14407 Result.makeComplexFloat(); 14408 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 14409 Result.FloatReal = Zero; 14410 Result.FloatImag = Zero; 14411 } else { 14412 Result.makeComplexInt(); 14413 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 14414 Result.IntReal = Zero; 14415 Result.IntImag = Zero; 14416 } 14417 return true; 14418 } 14419 14420 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 14421 const Expr* SubExpr = E->getSubExpr(); 14422 14423 if (SubExpr->getType()->isRealFloatingType()) { 14424 Result.makeComplexFloat(); 14425 APFloat &Imag = Result.FloatImag; 14426 if (!EvaluateFloat(SubExpr, Imag, Info)) 14427 return false; 14428 14429 Result.FloatReal = APFloat(Imag.getSemantics()); 14430 return true; 14431 } else { 14432 assert(SubExpr->getType()->isIntegerType() && 14433 "Unexpected imaginary literal."); 14434 14435 Result.makeComplexInt(); 14436 APSInt &Imag = Result.IntImag; 14437 if (!EvaluateInteger(SubExpr, Imag, Info)) 14438 return false; 14439 14440 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14441 return true; 14442 } 14443 } 14444 14445 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14446 14447 switch (E->getCastKind()) { 14448 case CK_BitCast: 14449 case CK_BaseToDerived: 14450 case CK_DerivedToBase: 14451 case CK_UncheckedDerivedToBase: 14452 case CK_Dynamic: 14453 case CK_ToUnion: 14454 case CK_ArrayToPointerDecay: 14455 case CK_FunctionToPointerDecay: 14456 case CK_NullToPointer: 14457 case CK_NullToMemberPointer: 14458 case CK_BaseToDerivedMemberPointer: 14459 case CK_DerivedToBaseMemberPointer: 14460 case CK_MemberPointerToBoolean: 14461 case CK_ReinterpretMemberPointer: 14462 case CK_ConstructorConversion: 14463 case CK_IntegralToPointer: 14464 case CK_PointerToIntegral: 14465 case CK_PointerToBoolean: 14466 case CK_ToVoid: 14467 case CK_VectorSplat: 14468 case CK_IntegralCast: 14469 case CK_BooleanToSignedIntegral: 14470 case CK_IntegralToBoolean: 14471 case CK_IntegralToFloating: 14472 case CK_FloatingToIntegral: 14473 case CK_FloatingToBoolean: 14474 case CK_FloatingCast: 14475 case CK_CPointerToObjCPointerCast: 14476 case CK_BlockPointerToObjCPointerCast: 14477 case CK_AnyPointerToBlockPointerCast: 14478 case CK_ObjCObjectLValueCast: 14479 case CK_FloatingComplexToReal: 14480 case CK_FloatingComplexToBoolean: 14481 case CK_IntegralComplexToReal: 14482 case CK_IntegralComplexToBoolean: 14483 case CK_ARCProduceObject: 14484 case CK_ARCConsumeObject: 14485 case CK_ARCReclaimReturnedObject: 14486 case CK_ARCExtendBlockObject: 14487 case CK_CopyAndAutoreleaseBlockObject: 14488 case CK_BuiltinFnToFnPtr: 14489 case CK_ZeroToOCLOpaqueType: 14490 case CK_NonAtomicToAtomic: 14491 case CK_AddressSpaceConversion: 14492 case CK_IntToOCLSampler: 14493 case CK_FloatingToFixedPoint: 14494 case CK_FixedPointToFloating: 14495 case CK_FixedPointCast: 14496 case CK_FixedPointToBoolean: 14497 case CK_FixedPointToIntegral: 14498 case CK_IntegralToFixedPoint: 14499 case CK_MatrixCast: 14500 llvm_unreachable("invalid cast kind for complex value"); 14501 14502 case CK_LValueToRValue: 14503 case CK_AtomicToNonAtomic: 14504 case CK_NoOp: 14505 case CK_LValueToRValueBitCast: 14506 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14507 14508 case CK_Dependent: 14509 case CK_LValueBitCast: 14510 case CK_UserDefinedConversion: 14511 return Error(E); 14512 14513 case CK_FloatingRealToComplex: { 14514 APFloat &Real = Result.FloatReal; 14515 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14516 return false; 14517 14518 Result.makeComplexFloat(); 14519 Result.FloatImag = APFloat(Real.getSemantics()); 14520 return true; 14521 } 14522 14523 case CK_FloatingComplexCast: { 14524 if (!Visit(E->getSubExpr())) 14525 return false; 14526 14527 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14528 QualType From 14529 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14530 14531 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14532 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14533 } 14534 14535 case CK_FloatingComplexToIntegralComplex: { 14536 if (!Visit(E->getSubExpr())) 14537 return false; 14538 14539 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14540 QualType From 14541 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14542 Result.makeComplexInt(); 14543 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14544 To, Result.IntReal) && 14545 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14546 To, Result.IntImag); 14547 } 14548 14549 case CK_IntegralRealToComplex: { 14550 APSInt &Real = Result.IntReal; 14551 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14552 return false; 14553 14554 Result.makeComplexInt(); 14555 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14556 return true; 14557 } 14558 14559 case CK_IntegralComplexCast: { 14560 if (!Visit(E->getSubExpr())) 14561 return false; 14562 14563 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14564 QualType From 14565 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14566 14567 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14568 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14569 return true; 14570 } 14571 14572 case CK_IntegralComplexToFloatingComplex: { 14573 if (!Visit(E->getSubExpr())) 14574 return false; 14575 14576 const FPOptions FPO = E->getFPFeaturesInEffect( 14577 Info.Ctx.getLangOpts()); 14578 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14579 QualType From 14580 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14581 Result.makeComplexFloat(); 14582 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14583 To, Result.FloatReal) && 14584 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14585 To, Result.FloatImag); 14586 } 14587 } 14588 14589 llvm_unreachable("unknown cast resulting in complex value"); 14590 } 14591 14592 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14593 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14594 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14595 14596 // Track whether the LHS or RHS is real at the type system level. When this is 14597 // the case we can simplify our evaluation strategy. 14598 bool LHSReal = false, RHSReal = false; 14599 14600 bool LHSOK; 14601 if (E->getLHS()->getType()->isRealFloatingType()) { 14602 LHSReal = true; 14603 APFloat &Real = Result.FloatReal; 14604 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14605 if (LHSOK) { 14606 Result.makeComplexFloat(); 14607 Result.FloatImag = APFloat(Real.getSemantics()); 14608 } 14609 } else { 14610 LHSOK = Visit(E->getLHS()); 14611 } 14612 if (!LHSOK && !Info.noteFailure()) 14613 return false; 14614 14615 ComplexValue RHS; 14616 if (E->getRHS()->getType()->isRealFloatingType()) { 14617 RHSReal = true; 14618 APFloat &Real = RHS.FloatReal; 14619 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14620 return false; 14621 RHS.makeComplexFloat(); 14622 RHS.FloatImag = APFloat(Real.getSemantics()); 14623 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14624 return false; 14625 14626 assert(!(LHSReal && RHSReal) && 14627 "Cannot have both operands of a complex operation be real."); 14628 switch (E->getOpcode()) { 14629 default: return Error(E); 14630 case BO_Add: 14631 if (Result.isComplexFloat()) { 14632 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14633 APFloat::rmNearestTiesToEven); 14634 if (LHSReal) 14635 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14636 else if (!RHSReal) 14637 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14638 APFloat::rmNearestTiesToEven); 14639 } else { 14640 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14641 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14642 } 14643 break; 14644 case BO_Sub: 14645 if (Result.isComplexFloat()) { 14646 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14647 APFloat::rmNearestTiesToEven); 14648 if (LHSReal) { 14649 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14650 Result.getComplexFloatImag().changeSign(); 14651 } else if (!RHSReal) { 14652 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14653 APFloat::rmNearestTiesToEven); 14654 } 14655 } else { 14656 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14657 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14658 } 14659 break; 14660 case BO_Mul: 14661 if (Result.isComplexFloat()) { 14662 // This is an implementation of complex multiplication according to the 14663 // constraints laid out in C11 Annex G. The implementation uses the 14664 // following naming scheme: 14665 // (a + ib) * (c + id) 14666 ComplexValue LHS = Result; 14667 APFloat &A = LHS.getComplexFloatReal(); 14668 APFloat &B = LHS.getComplexFloatImag(); 14669 APFloat &C = RHS.getComplexFloatReal(); 14670 APFloat &D = RHS.getComplexFloatImag(); 14671 APFloat &ResR = Result.getComplexFloatReal(); 14672 APFloat &ResI = Result.getComplexFloatImag(); 14673 if (LHSReal) { 14674 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14675 ResR = A * C; 14676 ResI = A * D; 14677 } else if (RHSReal) { 14678 ResR = C * A; 14679 ResI = C * B; 14680 } else { 14681 // In the fully general case, we need to handle NaNs and infinities 14682 // robustly. 14683 APFloat AC = A * C; 14684 APFloat BD = B * D; 14685 APFloat AD = A * D; 14686 APFloat BC = B * C; 14687 ResR = AC - BD; 14688 ResI = AD + BC; 14689 if (ResR.isNaN() && ResI.isNaN()) { 14690 bool Recalc = false; 14691 if (A.isInfinity() || B.isInfinity()) { 14692 A = APFloat::copySign( 14693 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14694 B = APFloat::copySign( 14695 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14696 if (C.isNaN()) 14697 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14698 if (D.isNaN()) 14699 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14700 Recalc = true; 14701 } 14702 if (C.isInfinity() || D.isInfinity()) { 14703 C = APFloat::copySign( 14704 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14705 D = APFloat::copySign( 14706 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14707 if (A.isNaN()) 14708 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14709 if (B.isNaN()) 14710 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14711 Recalc = true; 14712 } 14713 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14714 AD.isInfinity() || BC.isInfinity())) { 14715 if (A.isNaN()) 14716 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14717 if (B.isNaN()) 14718 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14719 if (C.isNaN()) 14720 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14721 if (D.isNaN()) 14722 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14723 Recalc = true; 14724 } 14725 if (Recalc) { 14726 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14727 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14728 } 14729 } 14730 } 14731 } else { 14732 ComplexValue LHS = Result; 14733 Result.getComplexIntReal() = 14734 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14735 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14736 Result.getComplexIntImag() = 14737 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14738 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14739 } 14740 break; 14741 case BO_Div: 14742 if (Result.isComplexFloat()) { 14743 // This is an implementation of complex division according to the 14744 // constraints laid out in C11 Annex G. The implementation uses the 14745 // following naming scheme: 14746 // (a + ib) / (c + id) 14747 ComplexValue LHS = Result; 14748 APFloat &A = LHS.getComplexFloatReal(); 14749 APFloat &B = LHS.getComplexFloatImag(); 14750 APFloat &C = RHS.getComplexFloatReal(); 14751 APFloat &D = RHS.getComplexFloatImag(); 14752 APFloat &ResR = Result.getComplexFloatReal(); 14753 APFloat &ResI = Result.getComplexFloatImag(); 14754 if (RHSReal) { 14755 ResR = A / C; 14756 ResI = B / C; 14757 } else { 14758 if (LHSReal) { 14759 // No real optimizations we can do here, stub out with zero. 14760 B = APFloat::getZero(A.getSemantics()); 14761 } 14762 int DenomLogB = 0; 14763 APFloat MaxCD = maxnum(abs(C), abs(D)); 14764 if (MaxCD.isFinite()) { 14765 DenomLogB = ilogb(MaxCD); 14766 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14767 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14768 } 14769 APFloat Denom = C * C + D * D; 14770 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14771 APFloat::rmNearestTiesToEven); 14772 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14773 APFloat::rmNearestTiesToEven); 14774 if (ResR.isNaN() && ResI.isNaN()) { 14775 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14776 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14777 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14778 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14779 D.isFinite()) { 14780 A = APFloat::copySign( 14781 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14782 B = APFloat::copySign( 14783 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14784 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14785 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14786 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14787 C = APFloat::copySign( 14788 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14789 D = APFloat::copySign( 14790 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14791 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14792 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14793 } 14794 } 14795 } 14796 } else { 14797 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14798 return Error(E, diag::note_expr_divide_by_zero); 14799 14800 ComplexValue LHS = Result; 14801 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14802 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14803 Result.getComplexIntReal() = 14804 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14805 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14806 Result.getComplexIntImag() = 14807 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14808 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14809 } 14810 break; 14811 } 14812 14813 return true; 14814 } 14815 14816 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14817 // Get the operand value into 'Result'. 14818 if (!Visit(E->getSubExpr())) 14819 return false; 14820 14821 switch (E->getOpcode()) { 14822 default: 14823 return Error(E); 14824 case UO_Extension: 14825 return true; 14826 case UO_Plus: 14827 // The result is always just the subexpr. 14828 return true; 14829 case UO_Minus: 14830 if (Result.isComplexFloat()) { 14831 Result.getComplexFloatReal().changeSign(); 14832 Result.getComplexFloatImag().changeSign(); 14833 } 14834 else { 14835 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14836 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14837 } 14838 return true; 14839 case UO_Not: 14840 if (Result.isComplexFloat()) 14841 Result.getComplexFloatImag().changeSign(); 14842 else 14843 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14844 return true; 14845 } 14846 } 14847 14848 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14849 if (E->getNumInits() == 2) { 14850 if (E->getType()->isComplexType()) { 14851 Result.makeComplexFloat(); 14852 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14853 return false; 14854 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14855 return false; 14856 } else { 14857 Result.makeComplexInt(); 14858 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14859 return false; 14860 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14861 return false; 14862 } 14863 return true; 14864 } 14865 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14866 } 14867 14868 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14869 if (!IsConstantEvaluatedBuiltinCall(E)) 14870 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14871 14872 switch (E->getBuiltinCallee()) { 14873 case Builtin::BI__builtin_complex: 14874 Result.makeComplexFloat(); 14875 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14876 return false; 14877 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14878 return false; 14879 return true; 14880 14881 default: 14882 return false; 14883 } 14884 } 14885 14886 //===----------------------------------------------------------------------===// 14887 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14888 // implicit conversion. 14889 //===----------------------------------------------------------------------===// 14890 14891 namespace { 14892 class AtomicExprEvaluator : 14893 public ExprEvaluatorBase<AtomicExprEvaluator> { 14894 const LValue *This; 14895 APValue &Result; 14896 public: 14897 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14898 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14899 14900 bool Success(const APValue &V, const Expr *E) { 14901 Result = V; 14902 return true; 14903 } 14904 14905 bool ZeroInitialization(const Expr *E) { 14906 ImplicitValueInitExpr VIE( 14907 E->getType()->castAs<AtomicType>()->getValueType()); 14908 // For atomic-qualified class (and array) types in C++, initialize the 14909 // _Atomic-wrapped subobject directly, in-place. 14910 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14911 : Evaluate(Result, Info, &VIE); 14912 } 14913 14914 bool VisitCastExpr(const CastExpr *E) { 14915 switch (E->getCastKind()) { 14916 default: 14917 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14918 case CK_NullToPointer: 14919 VisitIgnoredValue(E->getSubExpr()); 14920 return ZeroInitialization(E); 14921 case CK_NonAtomicToAtomic: 14922 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14923 : Evaluate(Result, Info, E->getSubExpr()); 14924 } 14925 } 14926 }; 14927 } // end anonymous namespace 14928 14929 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14930 EvalInfo &Info) { 14931 assert(!E->isValueDependent()); 14932 assert(E->isPRValue() && E->getType()->isAtomicType()); 14933 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14934 } 14935 14936 //===----------------------------------------------------------------------===// 14937 // Void expression evaluation, primarily for a cast to void on the LHS of a 14938 // comma operator 14939 //===----------------------------------------------------------------------===// 14940 14941 namespace { 14942 class VoidExprEvaluator 14943 : public ExprEvaluatorBase<VoidExprEvaluator> { 14944 public: 14945 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14946 14947 bool Success(const APValue &V, const Expr *e) { return true; } 14948 14949 bool ZeroInitialization(const Expr *E) { return true; } 14950 14951 bool VisitCastExpr(const CastExpr *E) { 14952 switch (E->getCastKind()) { 14953 default: 14954 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14955 case CK_ToVoid: 14956 VisitIgnoredValue(E->getSubExpr()); 14957 return true; 14958 } 14959 } 14960 14961 bool VisitCallExpr(const CallExpr *E) { 14962 if (!IsConstantEvaluatedBuiltinCall(E)) 14963 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14964 14965 switch (E->getBuiltinCallee()) { 14966 case Builtin::BI__assume: 14967 case Builtin::BI__builtin_assume: 14968 // The argument is not evaluated! 14969 return true; 14970 14971 case Builtin::BI__builtin_operator_delete: 14972 return HandleOperatorDeleteCall(Info, E); 14973 14974 default: 14975 return false; 14976 } 14977 } 14978 14979 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14980 }; 14981 } // end anonymous namespace 14982 14983 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14984 // We cannot speculatively evaluate a delete expression. 14985 if (Info.SpeculativeEvaluationDepth) 14986 return false; 14987 14988 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14989 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14990 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14991 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14992 return false; 14993 } 14994 14995 const Expr *Arg = E->getArgument(); 14996 14997 LValue Pointer; 14998 if (!EvaluatePointer(Arg, Pointer, Info)) 14999 return false; 15000 if (Pointer.Designator.Invalid) 15001 return false; 15002 15003 // Deleting a null pointer has no effect. 15004 if (Pointer.isNullPointer()) { 15005 // This is the only case where we need to produce an extension warning: 15006 // the only other way we can succeed is if we find a dynamic allocation, 15007 // and we will have warned when we allocated it in that case. 15008 if (!Info.getLangOpts().CPlusPlus20) 15009 Info.CCEDiag(E, diag::note_constexpr_new); 15010 return true; 15011 } 15012 15013 std::optional<DynAlloc *> Alloc = CheckDeleteKind( 15014 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 15015 if (!Alloc) 15016 return false; 15017 QualType AllocType = Pointer.Base.getDynamicAllocType(); 15018 15019 // For the non-array case, the designator must be empty if the static type 15020 // does not have a virtual destructor. 15021 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 15022 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 15023 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 15024 << Arg->getType()->getPointeeType() << AllocType; 15025 return false; 15026 } 15027 15028 // For a class type with a virtual destructor, the selected operator delete 15029 // is the one looked up when building the destructor. 15030 if (!E->isArrayForm() && !E->isGlobalDelete()) { 15031 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 15032 if (VirtualDelete && 15033 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 15034 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 15035 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 15036 return false; 15037 } 15038 } 15039 15040 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 15041 (*Alloc)->Value, AllocType)) 15042 return false; 15043 15044 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 15045 // The element was already erased. This means the destructor call also 15046 // deleted the object. 15047 // FIXME: This probably results in undefined behavior before we get this 15048 // far, and should be diagnosed elsewhere first. 15049 Info.FFDiag(E, diag::note_constexpr_double_delete); 15050 return false; 15051 } 15052 15053 return true; 15054 } 15055 15056 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 15057 assert(!E->isValueDependent()); 15058 assert(E->isPRValue() && E->getType()->isVoidType()); 15059 return VoidExprEvaluator(Info).Visit(E); 15060 } 15061 15062 //===----------------------------------------------------------------------===// 15063 // Top level Expr::EvaluateAsRValue method. 15064 //===----------------------------------------------------------------------===// 15065 15066 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 15067 assert(!E->isValueDependent()); 15068 // In C, function designators are not lvalues, but we evaluate them as if they 15069 // are. 15070 QualType T = E->getType(); 15071 if (E->isGLValue() || T->isFunctionType()) { 15072 LValue LV; 15073 if (!EvaluateLValue(E, LV, Info)) 15074 return false; 15075 LV.moveInto(Result); 15076 } else if (T->isVectorType()) { 15077 if (!EvaluateVector(E, Result, Info)) 15078 return false; 15079 } else if (T->isIntegralOrEnumerationType()) { 15080 if (!IntExprEvaluator(Info, Result).Visit(E)) 15081 return false; 15082 } else if (T->hasPointerRepresentation()) { 15083 LValue LV; 15084 if (!EvaluatePointer(E, LV, Info)) 15085 return false; 15086 LV.moveInto(Result); 15087 } else if (T->isRealFloatingType()) { 15088 llvm::APFloat F(0.0); 15089 if (!EvaluateFloat(E, F, Info)) 15090 return false; 15091 Result = APValue(F); 15092 } else if (T->isAnyComplexType()) { 15093 ComplexValue C; 15094 if (!EvaluateComplex(E, C, Info)) 15095 return false; 15096 C.moveInto(Result); 15097 } else if (T->isFixedPointType()) { 15098 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 15099 } else if (T->isMemberPointerType()) { 15100 MemberPtr P; 15101 if (!EvaluateMemberPointer(E, P, Info)) 15102 return false; 15103 P.moveInto(Result); 15104 return true; 15105 } else if (T->isArrayType()) { 15106 LValue LV; 15107 APValue &Value = 15108 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 15109 if (!EvaluateArray(E, LV, Value, Info)) 15110 return false; 15111 Result = Value; 15112 } else if (T->isRecordType()) { 15113 LValue LV; 15114 APValue &Value = 15115 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 15116 if (!EvaluateRecord(E, LV, Value, Info)) 15117 return false; 15118 Result = Value; 15119 } else if (T->isVoidType()) { 15120 if (!Info.getLangOpts().CPlusPlus11) 15121 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 15122 << E->getType(); 15123 if (!EvaluateVoid(E, Info)) 15124 return false; 15125 } else if (T->isAtomicType()) { 15126 QualType Unqual = T.getAtomicUnqualifiedType(); 15127 if (Unqual->isArrayType() || Unqual->isRecordType()) { 15128 LValue LV; 15129 APValue &Value = Info.CurrentCall->createTemporary( 15130 E, Unqual, ScopeKind::FullExpression, LV); 15131 if (!EvaluateAtomic(E, &LV, Value, Info)) 15132 return false; 15133 Result = Value; 15134 } else { 15135 if (!EvaluateAtomic(E, nullptr, Result, Info)) 15136 return false; 15137 } 15138 } else if (Info.getLangOpts().CPlusPlus11) { 15139 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 15140 return false; 15141 } else { 15142 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 15143 return false; 15144 } 15145 15146 return true; 15147 } 15148 15149 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 15150 /// cases, the in-place evaluation is essential, since later initializers for 15151 /// an object can indirectly refer to subobjects which were initialized earlier. 15152 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 15153 const Expr *E, bool AllowNonLiteralTypes) { 15154 assert(!E->isValueDependent()); 15155 15156 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 15157 return false; 15158 15159 if (E->isPRValue()) { 15160 // Evaluate arrays and record types in-place, so that later initializers can 15161 // refer to earlier-initialized members of the object. 15162 QualType T = E->getType(); 15163 if (T->isArrayType()) 15164 return EvaluateArray(E, This, Result, Info); 15165 else if (T->isRecordType()) 15166 return EvaluateRecord(E, This, Result, Info); 15167 else if (T->isAtomicType()) { 15168 QualType Unqual = T.getAtomicUnqualifiedType(); 15169 if (Unqual->isArrayType() || Unqual->isRecordType()) 15170 return EvaluateAtomic(E, &This, Result, Info); 15171 } 15172 } 15173 15174 // For any other type, in-place evaluation is unimportant. 15175 return Evaluate(Result, Info, E); 15176 } 15177 15178 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 15179 /// lvalue-to-rvalue cast if it is an lvalue. 15180 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 15181 assert(!E->isValueDependent()); 15182 15183 if (E->getType().isNull()) 15184 return false; 15185 15186 if (!CheckLiteralType(Info, E)) 15187 return false; 15188 15189 if (Info.EnableNewConstInterp) { 15190 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 15191 return false; 15192 } else { 15193 if (!::Evaluate(Result, Info, E)) 15194 return false; 15195 } 15196 15197 // Implicit lvalue-to-rvalue cast. 15198 if (E->isGLValue()) { 15199 LValue LV; 15200 LV.setFrom(Info.Ctx, Result); 15201 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 15202 return false; 15203 } 15204 15205 // Check this core constant expression is a constant expression. 15206 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 15207 ConstantExprKind::Normal) && 15208 CheckMemoryLeaks(Info); 15209 } 15210 15211 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 15212 const ASTContext &Ctx, bool &IsConst) { 15213 // Fast-path evaluations of integer literals, since we sometimes see files 15214 // containing vast quantities of these. 15215 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 15216 Result.Val = APValue(APSInt(L->getValue(), 15217 L->getType()->isUnsignedIntegerType())); 15218 IsConst = true; 15219 return true; 15220 } 15221 15222 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) { 15223 Result.Val = APValue(APSInt(APInt(1, L->getValue()))); 15224 IsConst = true; 15225 return true; 15226 } 15227 15228 // This case should be rare, but we need to check it before we check on 15229 // the type below. 15230 if (Exp->getType().isNull()) { 15231 IsConst = false; 15232 return true; 15233 } 15234 15235 return false; 15236 } 15237 15238 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 15239 Expr::SideEffectsKind SEK) { 15240 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 15241 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 15242 } 15243 15244 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 15245 const ASTContext &Ctx, EvalInfo &Info) { 15246 assert(!E->isValueDependent()); 15247 bool IsConst; 15248 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 15249 return IsConst; 15250 15251 return EvaluateAsRValue(Info, E, Result.Val); 15252 } 15253 15254 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 15255 const ASTContext &Ctx, 15256 Expr::SideEffectsKind AllowSideEffects, 15257 EvalInfo &Info) { 15258 assert(!E->isValueDependent()); 15259 if (!E->getType()->isIntegralOrEnumerationType()) 15260 return false; 15261 15262 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 15263 !ExprResult.Val.isInt() || 15264 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15265 return false; 15266 15267 return true; 15268 } 15269 15270 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 15271 const ASTContext &Ctx, 15272 Expr::SideEffectsKind AllowSideEffects, 15273 EvalInfo &Info) { 15274 assert(!E->isValueDependent()); 15275 if (!E->getType()->isFixedPointType()) 15276 return false; 15277 15278 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 15279 return false; 15280 15281 if (!ExprResult.Val.isFixedPoint() || 15282 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15283 return false; 15284 15285 return true; 15286 } 15287 15288 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 15289 /// any crazy technique (that has nothing to do with language standards) that 15290 /// we want to. If this function returns true, it returns the folded constant 15291 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 15292 /// will be applied to the result. 15293 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 15294 bool InConstantContext) const { 15295 assert(!isValueDependent() && 15296 "Expression evaluator can't be called on a dependent expression."); 15297 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue"); 15298 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15299 Info.InConstantContext = InConstantContext; 15300 return ::EvaluateAsRValue(this, Result, Ctx, Info); 15301 } 15302 15303 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 15304 bool InConstantContext) const { 15305 assert(!isValueDependent() && 15306 "Expression evaluator can't be called on a dependent expression."); 15307 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition"); 15308 EvalResult Scratch; 15309 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 15310 HandleConversionToBool(Scratch.Val, Result); 15311 } 15312 15313 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 15314 SideEffectsKind AllowSideEffects, 15315 bool InConstantContext) const { 15316 assert(!isValueDependent() && 15317 "Expression evaluator can't be called on a dependent expression."); 15318 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt"); 15319 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15320 Info.InConstantContext = InConstantContext; 15321 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 15322 } 15323 15324 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 15325 SideEffectsKind AllowSideEffects, 15326 bool InConstantContext) const { 15327 assert(!isValueDependent() && 15328 "Expression evaluator can't be called on a dependent expression."); 15329 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint"); 15330 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 15331 Info.InConstantContext = InConstantContext; 15332 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 15333 } 15334 15335 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 15336 SideEffectsKind AllowSideEffects, 15337 bool InConstantContext) const { 15338 assert(!isValueDependent() && 15339 "Expression evaluator can't be called on a dependent expression."); 15340 15341 if (!getType()->isRealFloatingType()) 15342 return false; 15343 15344 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat"); 15345 EvalResult ExprResult; 15346 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 15347 !ExprResult.Val.isFloat() || 15348 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 15349 return false; 15350 15351 Result = ExprResult.Val.getFloat(); 15352 return true; 15353 } 15354 15355 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 15356 bool InConstantContext) const { 15357 assert(!isValueDependent() && 15358 "Expression evaluator can't be called on a dependent expression."); 15359 15360 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue"); 15361 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 15362 Info.InConstantContext = InConstantContext; 15363 LValue LV; 15364 CheckedTemporaries CheckedTemps; 15365 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 15366 Result.HasSideEffects || 15367 !CheckLValueConstantExpression(Info, getExprLoc(), 15368 Ctx.getLValueReferenceType(getType()), LV, 15369 ConstantExprKind::Normal, CheckedTemps)) 15370 return false; 15371 15372 LV.moveInto(Result.Val); 15373 return true; 15374 } 15375 15376 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 15377 APValue DestroyedValue, QualType Type, 15378 SourceLocation Loc, Expr::EvalStatus &EStatus, 15379 bool IsConstantDestruction) { 15380 EvalInfo Info(Ctx, EStatus, 15381 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 15382 : EvalInfo::EM_ConstantFold); 15383 Info.setEvaluatingDecl(Base, DestroyedValue, 15384 EvalInfo::EvaluatingDeclKind::Dtor); 15385 Info.InConstantContext = IsConstantDestruction; 15386 15387 LValue LVal; 15388 LVal.set(Base); 15389 15390 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 15391 EStatus.HasSideEffects) 15392 return false; 15393 15394 if (!Info.discardCleanups()) 15395 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15396 15397 return true; 15398 } 15399 15400 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 15401 ConstantExprKind Kind) const { 15402 assert(!isValueDependent() && 15403 "Expression evaluator can't be called on a dependent expression."); 15404 bool IsConst; 15405 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue()) 15406 return true; 15407 15408 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr"); 15409 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 15410 EvalInfo Info(Ctx, Result, EM); 15411 Info.InConstantContext = true; 15412 15413 // The type of the object we're initializing is 'const T' for a class NTTP. 15414 QualType T = getType(); 15415 if (Kind == ConstantExprKind::ClassTemplateArgument) 15416 T.addConst(); 15417 15418 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 15419 // represent the result of the evaluation. CheckConstantExpression ensures 15420 // this doesn't escape. 15421 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 15422 APValue::LValueBase Base(&BaseMTE); 15423 15424 Info.setEvaluatingDecl(Base, Result.Val); 15425 LValue LVal; 15426 LVal.set(Base); 15427 15428 { 15429 // C++23 [intro.execution]/p5 15430 // A full-expression is [...] a constant-expression 15431 // So we need to make sure temporary objects are destroyed after having 15432 // evaluating the expression (per C++23 [class.temporary]/p4). 15433 FullExpressionRAII Scope(Info); 15434 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 15435 Result.HasSideEffects || !Scope.destroy()) 15436 return false; 15437 } 15438 15439 if (!Info.discardCleanups()) 15440 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15441 15442 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 15443 Result.Val, Kind)) 15444 return false; 15445 if (!CheckMemoryLeaks(Info)) 15446 return false; 15447 15448 // If this is a class template argument, it's required to have constant 15449 // destruction too. 15450 if (Kind == ConstantExprKind::ClassTemplateArgument && 15451 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15452 true) || 15453 Result.HasSideEffects)) { 15454 // FIXME: Prefix a note to indicate that the problem is lack of constant 15455 // destruction. 15456 return false; 15457 } 15458 15459 return true; 15460 } 15461 15462 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15463 const VarDecl *VD, 15464 SmallVectorImpl<PartialDiagnosticAt> &Notes, 15465 bool IsConstantInitialization) const { 15466 assert(!isValueDependent() && 15467 "Expression evaluator can't be called on a dependent expression."); 15468 15469 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] { 15470 std::string Name; 15471 llvm::raw_string_ostream OS(Name); 15472 VD->printQualifiedName(OS); 15473 return Name; 15474 }); 15475 15476 Expr::EvalStatus EStatus; 15477 EStatus.Diag = &Notes; 15478 15479 EvalInfo Info(Ctx, EStatus, 15480 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus) 15481 ? EvalInfo::EM_ConstantExpression 15482 : EvalInfo::EM_ConstantFold); 15483 Info.setEvaluatingDecl(VD, Value); 15484 Info.InConstantContext = IsConstantInitialization; 15485 15486 if (Info.EnableNewConstInterp) { 15487 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15488 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15489 return false; 15490 } else { 15491 LValue LVal; 15492 LVal.set(VD); 15493 15494 if (!EvaluateInPlace(Value, Info, LVal, this, 15495 /*AllowNonLiteralTypes=*/true) || 15496 EStatus.HasSideEffects) 15497 return false; 15498 15499 // At this point, any lifetime-extended temporaries are completely 15500 // initialized. 15501 Info.performLifetimeExtension(); 15502 15503 if (!Info.discardCleanups()) 15504 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15505 } 15506 15507 SourceLocation DeclLoc = VD->getLocation(); 15508 QualType DeclTy = VD->getType(); 15509 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15510 ConstantExprKind::Normal) && 15511 CheckMemoryLeaks(Info); 15512 } 15513 15514 bool VarDecl::evaluateDestruction( 15515 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15516 Expr::EvalStatus EStatus; 15517 EStatus.Diag = &Notes; 15518 15519 // Only treat the destruction as constant destruction if we formally have 15520 // constant initialization (or are usable in a constant expression). 15521 bool IsConstantDestruction = hasConstantInitialization(); 15522 15523 // Make a copy of the value for the destructor to mutate, if we know it. 15524 // Otherwise, treat the value as default-initialized; if the destructor works 15525 // anyway, then the destruction is constant (and must be essentially empty). 15526 APValue DestroyedValue; 15527 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15528 DestroyedValue = *getEvaluatedValue(); 15529 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15530 return false; 15531 15532 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15533 getType(), getLocation(), EStatus, 15534 IsConstantDestruction) || 15535 EStatus.HasSideEffects) 15536 return false; 15537 15538 ensureEvaluatedStmt()->HasConstantDestruction = true; 15539 return true; 15540 } 15541 15542 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15543 /// constant folded, but discard the result. 15544 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15545 assert(!isValueDependent() && 15546 "Expression evaluator can't be called on a dependent expression."); 15547 15548 EvalResult Result; 15549 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15550 !hasUnacceptableSideEffect(Result, SEK); 15551 } 15552 15553 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15554 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15555 assert(!isValueDependent() && 15556 "Expression evaluator can't be called on a dependent expression."); 15557 15558 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt"); 15559 EvalResult EVResult; 15560 EVResult.Diag = Diag; 15561 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15562 Info.InConstantContext = true; 15563 15564 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15565 (void)Result; 15566 assert(Result && "Could not evaluate expression"); 15567 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15568 15569 return EVResult.Val.getInt(); 15570 } 15571 15572 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15573 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15574 assert(!isValueDependent() && 15575 "Expression evaluator can't be called on a dependent expression."); 15576 15577 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow"); 15578 EvalResult EVResult; 15579 EVResult.Diag = Diag; 15580 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15581 Info.InConstantContext = true; 15582 Info.CheckingForUndefinedBehavior = true; 15583 15584 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15585 (void)Result; 15586 assert(Result && "Could not evaluate expression"); 15587 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15588 15589 return EVResult.Val.getInt(); 15590 } 15591 15592 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15593 assert(!isValueDependent() && 15594 "Expression evaluator can't be called on a dependent expression."); 15595 15596 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow"); 15597 bool IsConst; 15598 EvalResult EVResult; 15599 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15600 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15601 Info.CheckingForUndefinedBehavior = true; 15602 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15603 } 15604 } 15605 15606 bool Expr::EvalResult::isGlobalLValue() const { 15607 assert(Val.isLValue()); 15608 return IsGlobalLValue(Val.getLValueBase()); 15609 } 15610 15611 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15612 /// an integer constant expression. 15613 15614 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15615 /// comma, etc 15616 15617 // CheckICE - This function does the fundamental ICE checking: the returned 15618 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15619 // and a (possibly null) SourceLocation indicating the location of the problem. 15620 // 15621 // Note that to reduce code duplication, this helper does no evaluation 15622 // itself; the caller checks whether the expression is evaluatable, and 15623 // in the rare cases where CheckICE actually cares about the evaluated 15624 // value, it calls into Evaluate. 15625 15626 namespace { 15627 15628 enum ICEKind { 15629 /// This expression is an ICE. 15630 IK_ICE, 15631 /// This expression is not an ICE, but if it isn't evaluated, it's 15632 /// a legal subexpression for an ICE. This return value is used to handle 15633 /// the comma operator in C99 mode, and non-constant subexpressions. 15634 IK_ICEIfUnevaluated, 15635 /// This expression is not an ICE, and is not a legal subexpression for one. 15636 IK_NotICE 15637 }; 15638 15639 struct ICEDiag { 15640 ICEKind Kind; 15641 SourceLocation Loc; 15642 15643 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15644 }; 15645 15646 } 15647 15648 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15649 15650 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15651 15652 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15653 Expr::EvalResult EVResult; 15654 Expr::EvalStatus Status; 15655 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15656 15657 Info.InConstantContext = true; 15658 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15659 !EVResult.Val.isInt()) 15660 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15661 15662 return NoDiag(); 15663 } 15664 15665 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15666 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15667 if (!E->getType()->isIntegralOrEnumerationType()) 15668 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15669 15670 switch (E->getStmtClass()) { 15671 #define ABSTRACT_STMT(Node) 15672 #define STMT(Node, Base) case Expr::Node##Class: 15673 #define EXPR(Node, Base) 15674 #include "clang/AST/StmtNodes.inc" 15675 case Expr::PredefinedExprClass: 15676 case Expr::FloatingLiteralClass: 15677 case Expr::ImaginaryLiteralClass: 15678 case Expr::StringLiteralClass: 15679 case Expr::ArraySubscriptExprClass: 15680 case Expr::MatrixSubscriptExprClass: 15681 case Expr::OMPArraySectionExprClass: 15682 case Expr::OMPArrayShapingExprClass: 15683 case Expr::OMPIteratorExprClass: 15684 case Expr::MemberExprClass: 15685 case Expr::CompoundAssignOperatorClass: 15686 case Expr::CompoundLiteralExprClass: 15687 case Expr::ExtVectorElementExprClass: 15688 case Expr::DesignatedInitExprClass: 15689 case Expr::ArrayInitLoopExprClass: 15690 case Expr::ArrayInitIndexExprClass: 15691 case Expr::NoInitExprClass: 15692 case Expr::DesignatedInitUpdateExprClass: 15693 case Expr::ImplicitValueInitExprClass: 15694 case Expr::ParenListExprClass: 15695 case Expr::VAArgExprClass: 15696 case Expr::AddrLabelExprClass: 15697 case Expr::StmtExprClass: 15698 case Expr::CXXMemberCallExprClass: 15699 case Expr::CUDAKernelCallExprClass: 15700 case Expr::CXXAddrspaceCastExprClass: 15701 case Expr::CXXDynamicCastExprClass: 15702 case Expr::CXXTypeidExprClass: 15703 case Expr::CXXUuidofExprClass: 15704 case Expr::MSPropertyRefExprClass: 15705 case Expr::MSPropertySubscriptExprClass: 15706 case Expr::CXXNullPtrLiteralExprClass: 15707 case Expr::UserDefinedLiteralClass: 15708 case Expr::CXXThisExprClass: 15709 case Expr::CXXThrowExprClass: 15710 case Expr::CXXNewExprClass: 15711 case Expr::CXXDeleteExprClass: 15712 case Expr::CXXPseudoDestructorExprClass: 15713 case Expr::UnresolvedLookupExprClass: 15714 case Expr::TypoExprClass: 15715 case Expr::RecoveryExprClass: 15716 case Expr::DependentScopeDeclRefExprClass: 15717 case Expr::CXXConstructExprClass: 15718 case Expr::CXXInheritedCtorInitExprClass: 15719 case Expr::CXXStdInitializerListExprClass: 15720 case Expr::CXXBindTemporaryExprClass: 15721 case Expr::ExprWithCleanupsClass: 15722 case Expr::CXXTemporaryObjectExprClass: 15723 case Expr::CXXUnresolvedConstructExprClass: 15724 case Expr::CXXDependentScopeMemberExprClass: 15725 case Expr::UnresolvedMemberExprClass: 15726 case Expr::ObjCStringLiteralClass: 15727 case Expr::ObjCBoxedExprClass: 15728 case Expr::ObjCArrayLiteralClass: 15729 case Expr::ObjCDictionaryLiteralClass: 15730 case Expr::ObjCEncodeExprClass: 15731 case Expr::ObjCMessageExprClass: 15732 case Expr::ObjCSelectorExprClass: 15733 case Expr::ObjCProtocolExprClass: 15734 case Expr::ObjCIvarRefExprClass: 15735 case Expr::ObjCPropertyRefExprClass: 15736 case Expr::ObjCSubscriptRefExprClass: 15737 case Expr::ObjCIsaExprClass: 15738 case Expr::ObjCAvailabilityCheckExprClass: 15739 case Expr::ShuffleVectorExprClass: 15740 case Expr::ConvertVectorExprClass: 15741 case Expr::BlockExprClass: 15742 case Expr::NoStmtClass: 15743 case Expr::OpaqueValueExprClass: 15744 case Expr::PackExpansionExprClass: 15745 case Expr::SubstNonTypeTemplateParmPackExprClass: 15746 case Expr::FunctionParmPackExprClass: 15747 case Expr::AsTypeExprClass: 15748 case Expr::ObjCIndirectCopyRestoreExprClass: 15749 case Expr::MaterializeTemporaryExprClass: 15750 case Expr::PseudoObjectExprClass: 15751 case Expr::AtomicExprClass: 15752 case Expr::LambdaExprClass: 15753 case Expr::CXXFoldExprClass: 15754 case Expr::CoawaitExprClass: 15755 case Expr::DependentCoawaitExprClass: 15756 case Expr::CoyieldExprClass: 15757 case Expr::SYCLUniqueStableNameExprClass: 15758 case Expr::CXXParenListInitExprClass: 15759 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15760 15761 case Expr::InitListExprClass: { 15762 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15763 // form "T x = { a };" is equivalent to "T x = a;". 15764 // Unless we're initializing a reference, T is a scalar as it is known to be 15765 // of integral or enumeration type. 15766 if (E->isPRValue()) 15767 if (cast<InitListExpr>(E)->getNumInits() == 1) 15768 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15769 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15770 } 15771 15772 case Expr::SizeOfPackExprClass: 15773 case Expr::GNUNullExprClass: 15774 case Expr::SourceLocExprClass: 15775 return NoDiag(); 15776 15777 case Expr::SubstNonTypeTemplateParmExprClass: 15778 return 15779 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15780 15781 case Expr::ConstantExprClass: 15782 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15783 15784 case Expr::ParenExprClass: 15785 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15786 case Expr::GenericSelectionExprClass: 15787 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15788 case Expr::IntegerLiteralClass: 15789 case Expr::FixedPointLiteralClass: 15790 case Expr::CharacterLiteralClass: 15791 case Expr::ObjCBoolLiteralExprClass: 15792 case Expr::CXXBoolLiteralExprClass: 15793 case Expr::CXXScalarValueInitExprClass: 15794 case Expr::TypeTraitExprClass: 15795 case Expr::ConceptSpecializationExprClass: 15796 case Expr::RequiresExprClass: 15797 case Expr::ArrayTypeTraitExprClass: 15798 case Expr::ExpressionTraitExprClass: 15799 case Expr::CXXNoexceptExprClass: 15800 return NoDiag(); 15801 case Expr::CallExprClass: 15802 case Expr::CXXOperatorCallExprClass: { 15803 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15804 // constant expressions, but they can never be ICEs because an ICE cannot 15805 // contain an operand of (pointer to) function type. 15806 const CallExpr *CE = cast<CallExpr>(E); 15807 if (CE->getBuiltinCallee()) 15808 return CheckEvalInICE(E, Ctx); 15809 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15810 } 15811 case Expr::CXXRewrittenBinaryOperatorClass: 15812 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15813 Ctx); 15814 case Expr::DeclRefExprClass: { 15815 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15816 if (isa<EnumConstantDecl>(D)) 15817 return NoDiag(); 15818 15819 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15820 // integer variables in constant expressions: 15821 // 15822 // C++ 7.1.5.1p2 15823 // A variable of non-volatile const-qualified integral or enumeration 15824 // type initialized by an ICE can be used in ICEs. 15825 // 15826 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15827 // that mode, use of reference variables should not be allowed. 15828 const VarDecl *VD = dyn_cast<VarDecl>(D); 15829 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15830 !VD->getType()->isReferenceType()) 15831 return NoDiag(); 15832 15833 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15834 } 15835 case Expr::UnaryOperatorClass: { 15836 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15837 switch (Exp->getOpcode()) { 15838 case UO_PostInc: 15839 case UO_PostDec: 15840 case UO_PreInc: 15841 case UO_PreDec: 15842 case UO_AddrOf: 15843 case UO_Deref: 15844 case UO_Coawait: 15845 // C99 6.6/3 allows increment and decrement within unevaluated 15846 // subexpressions of constant expressions, but they can never be ICEs 15847 // because an ICE cannot contain an lvalue operand. 15848 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15849 case UO_Extension: 15850 case UO_LNot: 15851 case UO_Plus: 15852 case UO_Minus: 15853 case UO_Not: 15854 case UO_Real: 15855 case UO_Imag: 15856 return CheckICE(Exp->getSubExpr(), Ctx); 15857 } 15858 llvm_unreachable("invalid unary operator class"); 15859 } 15860 case Expr::OffsetOfExprClass: { 15861 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15862 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15863 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15864 // compliance: we should warn earlier for offsetof expressions with 15865 // array subscripts that aren't ICEs, and if the array subscripts 15866 // are ICEs, the value of the offsetof must be an integer constant. 15867 return CheckEvalInICE(E, Ctx); 15868 } 15869 case Expr::UnaryExprOrTypeTraitExprClass: { 15870 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15871 if ((Exp->getKind() == UETT_SizeOf) && 15872 Exp->getTypeOfArgument()->isVariableArrayType()) 15873 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15874 return NoDiag(); 15875 } 15876 case Expr::BinaryOperatorClass: { 15877 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15878 switch (Exp->getOpcode()) { 15879 case BO_PtrMemD: 15880 case BO_PtrMemI: 15881 case BO_Assign: 15882 case BO_MulAssign: 15883 case BO_DivAssign: 15884 case BO_RemAssign: 15885 case BO_AddAssign: 15886 case BO_SubAssign: 15887 case BO_ShlAssign: 15888 case BO_ShrAssign: 15889 case BO_AndAssign: 15890 case BO_XorAssign: 15891 case BO_OrAssign: 15892 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15893 // constant expressions, but they can never be ICEs because an ICE cannot 15894 // contain an lvalue operand. 15895 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15896 15897 case BO_Mul: 15898 case BO_Div: 15899 case BO_Rem: 15900 case BO_Add: 15901 case BO_Sub: 15902 case BO_Shl: 15903 case BO_Shr: 15904 case BO_LT: 15905 case BO_GT: 15906 case BO_LE: 15907 case BO_GE: 15908 case BO_EQ: 15909 case BO_NE: 15910 case BO_And: 15911 case BO_Xor: 15912 case BO_Or: 15913 case BO_Comma: 15914 case BO_Cmp: { 15915 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15916 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15917 if (Exp->getOpcode() == BO_Div || 15918 Exp->getOpcode() == BO_Rem) { 15919 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15920 // we don't evaluate one. 15921 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15922 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15923 if (REval == 0) 15924 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15925 if (REval.isSigned() && REval.isAllOnes()) { 15926 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15927 if (LEval.isMinSignedValue()) 15928 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15929 } 15930 } 15931 } 15932 if (Exp->getOpcode() == BO_Comma) { 15933 if (Ctx.getLangOpts().C99) { 15934 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15935 // if it isn't evaluated. 15936 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15937 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15938 } else { 15939 // In both C89 and C++, commas in ICEs are illegal. 15940 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15941 } 15942 } 15943 return Worst(LHSResult, RHSResult); 15944 } 15945 case BO_LAnd: 15946 case BO_LOr: { 15947 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15948 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15949 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15950 // Rare case where the RHS has a comma "side-effect"; we need 15951 // to actually check the condition to see whether the side 15952 // with the comma is evaluated. 15953 if ((Exp->getOpcode() == BO_LAnd) != 15954 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15955 return RHSResult; 15956 return NoDiag(); 15957 } 15958 15959 return Worst(LHSResult, RHSResult); 15960 } 15961 } 15962 llvm_unreachable("invalid binary operator kind"); 15963 } 15964 case Expr::ImplicitCastExprClass: 15965 case Expr::CStyleCastExprClass: 15966 case Expr::CXXFunctionalCastExprClass: 15967 case Expr::CXXStaticCastExprClass: 15968 case Expr::CXXReinterpretCastExprClass: 15969 case Expr::CXXConstCastExprClass: 15970 case Expr::ObjCBridgedCastExprClass: { 15971 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15972 if (isa<ExplicitCastExpr>(E)) { 15973 if (const FloatingLiteral *FL 15974 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15975 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15976 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15977 APSInt IgnoredVal(DestWidth, !DestSigned); 15978 bool Ignored; 15979 // If the value does not fit in the destination type, the behavior is 15980 // undefined, so we are not required to treat it as a constant 15981 // expression. 15982 if (FL->getValue().convertToInteger(IgnoredVal, 15983 llvm::APFloat::rmTowardZero, 15984 &Ignored) & APFloat::opInvalidOp) 15985 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15986 return NoDiag(); 15987 } 15988 } 15989 switch (cast<CastExpr>(E)->getCastKind()) { 15990 case CK_LValueToRValue: 15991 case CK_AtomicToNonAtomic: 15992 case CK_NonAtomicToAtomic: 15993 case CK_NoOp: 15994 case CK_IntegralToBoolean: 15995 case CK_IntegralCast: 15996 return CheckICE(SubExpr, Ctx); 15997 default: 15998 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15999 } 16000 } 16001 case Expr::BinaryConditionalOperatorClass: { 16002 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 16003 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 16004 if (CommonResult.Kind == IK_NotICE) return CommonResult; 16005 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 16006 if (FalseResult.Kind == IK_NotICE) return FalseResult; 16007 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 16008 if (FalseResult.Kind == IK_ICEIfUnevaluated && 16009 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 16010 return FalseResult; 16011 } 16012 case Expr::ConditionalOperatorClass: { 16013 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 16014 // If the condition (ignoring parens) is a __builtin_constant_p call, 16015 // then only the true side is actually considered in an integer constant 16016 // expression, and it is fully evaluated. This is an important GNU 16017 // extension. See GCC PR38377 for discussion. 16018 if (const CallExpr *CallCE 16019 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 16020 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 16021 return CheckEvalInICE(E, Ctx); 16022 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 16023 if (CondResult.Kind == IK_NotICE) 16024 return CondResult; 16025 16026 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 16027 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 16028 16029 if (TrueResult.Kind == IK_NotICE) 16030 return TrueResult; 16031 if (FalseResult.Kind == IK_NotICE) 16032 return FalseResult; 16033 if (CondResult.Kind == IK_ICEIfUnevaluated) 16034 return CondResult; 16035 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 16036 return NoDiag(); 16037 // Rare case where the diagnostics depend on which side is evaluated 16038 // Note that if we get here, CondResult is 0, and at least one of 16039 // TrueResult and FalseResult is non-zero. 16040 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 16041 return FalseResult; 16042 return TrueResult; 16043 } 16044 case Expr::CXXDefaultArgExprClass: 16045 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 16046 case Expr::CXXDefaultInitExprClass: 16047 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 16048 case Expr::ChooseExprClass: { 16049 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 16050 } 16051 case Expr::BuiltinBitCastExprClass: { 16052 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 16053 return ICEDiag(IK_NotICE, E->getBeginLoc()); 16054 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 16055 } 16056 } 16057 16058 llvm_unreachable("Invalid StmtClass!"); 16059 } 16060 16061 /// Evaluate an expression as a C++11 integral constant expression. 16062 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 16063 const Expr *E, 16064 llvm::APSInt *Value, 16065 SourceLocation *Loc) { 16066 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16067 if (Loc) *Loc = E->getExprLoc(); 16068 return false; 16069 } 16070 16071 APValue Result; 16072 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 16073 return false; 16074 16075 if (!Result.isInt()) { 16076 if (Loc) *Loc = E->getExprLoc(); 16077 return false; 16078 } 16079 16080 if (Value) *Value = Result.getInt(); 16081 return true; 16082 } 16083 16084 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 16085 SourceLocation *Loc) const { 16086 assert(!isValueDependent() && 16087 "Expression evaluator can't be called on a dependent expression."); 16088 16089 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr"); 16090 16091 if (Ctx.getLangOpts().CPlusPlus11) 16092 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 16093 16094 ICEDiag D = CheckICE(this, Ctx); 16095 if (D.Kind != IK_ICE) { 16096 if (Loc) *Loc = D.Loc; 16097 return false; 16098 } 16099 return true; 16100 } 16101 16102 std::optional<llvm::APSInt> 16103 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc, 16104 bool isEvaluated) const { 16105 if (isValueDependent()) { 16106 // Expression evaluator can't succeed on a dependent expression. 16107 return std::nullopt; 16108 } 16109 16110 APSInt Value; 16111 16112 if (Ctx.getLangOpts().CPlusPlus11) { 16113 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 16114 return Value; 16115 return std::nullopt; 16116 } 16117 16118 if (!isIntegerConstantExpr(Ctx, Loc)) 16119 return std::nullopt; 16120 16121 // The only possible side-effects here are due to UB discovered in the 16122 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 16123 // required to treat the expression as an ICE, so we produce the folded 16124 // value. 16125 EvalResult ExprResult; 16126 Expr::EvalStatus Status; 16127 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 16128 Info.InConstantContext = true; 16129 16130 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 16131 llvm_unreachable("ICE cannot be evaluated!"); 16132 16133 return ExprResult.Val.getInt(); 16134 } 16135 16136 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 16137 assert(!isValueDependent() && 16138 "Expression evaluator can't be called on a dependent expression."); 16139 16140 return CheckICE(this, Ctx).Kind == IK_ICE; 16141 } 16142 16143 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 16144 SourceLocation *Loc) const { 16145 assert(!isValueDependent() && 16146 "Expression evaluator can't be called on a dependent expression."); 16147 16148 // We support this checking in C++98 mode in order to diagnose compatibility 16149 // issues. 16150 assert(Ctx.getLangOpts().CPlusPlus); 16151 16152 // Build evaluation settings. 16153 Expr::EvalStatus Status; 16154 SmallVector<PartialDiagnosticAt, 8> Diags; 16155 Status.Diag = &Diags; 16156 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 16157 16158 APValue Scratch; 16159 bool IsConstExpr = 16160 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 16161 // FIXME: We don't produce a diagnostic for this, but the callers that 16162 // call us on arbitrary full-expressions should generally not care. 16163 Info.discardCleanups() && !Status.HasSideEffects; 16164 16165 if (!Diags.empty()) { 16166 IsConstExpr = false; 16167 if (Loc) *Loc = Diags[0].first; 16168 } else if (!IsConstExpr) { 16169 // FIXME: This shouldn't happen. 16170 if (Loc) *Loc = getExprLoc(); 16171 } 16172 16173 return IsConstExpr; 16174 } 16175 16176 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 16177 const FunctionDecl *Callee, 16178 ArrayRef<const Expr*> Args, 16179 const Expr *This) const { 16180 assert(!isValueDependent() && 16181 "Expression evaluator can't be called on a dependent expression."); 16182 16183 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] { 16184 std::string Name; 16185 llvm::raw_string_ostream OS(Name); 16186 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(), 16187 /*Qualified=*/true); 16188 return Name; 16189 }); 16190 16191 Expr::EvalStatus Status; 16192 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 16193 Info.InConstantContext = true; 16194 16195 LValue ThisVal; 16196 const LValue *ThisPtr = nullptr; 16197 if (This) { 16198 #ifndef NDEBUG 16199 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 16200 assert(MD && "Don't provide `this` for non-methods."); 16201 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 16202 #endif 16203 if (!This->isValueDependent() && 16204 EvaluateObjectArgument(Info, This, ThisVal) && 16205 !Info.EvalStatus.HasSideEffects) 16206 ThisPtr = &ThisVal; 16207 16208 // Ignore any side-effects from a failed evaluation. This is safe because 16209 // they can't interfere with any other argument evaluation. 16210 Info.EvalStatus.HasSideEffects = false; 16211 } 16212 16213 CallRef Call = Info.CurrentCall->createCall(Callee); 16214 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 16215 I != E; ++I) { 16216 unsigned Idx = I - Args.begin(); 16217 if (Idx >= Callee->getNumParams()) 16218 break; 16219 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 16220 if ((*I)->isValueDependent() || 16221 !EvaluateCallArg(PVD, *I, Call, Info) || 16222 Info.EvalStatus.HasSideEffects) { 16223 // If evaluation fails, throw away the argument entirely. 16224 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 16225 *Slot = APValue(); 16226 } 16227 16228 // Ignore any side-effects from a failed evaluation. This is safe because 16229 // they can't interfere with any other argument evaluation. 16230 Info.EvalStatus.HasSideEffects = false; 16231 } 16232 16233 // Parameter cleanups happen in the caller and are not part of this 16234 // evaluation. 16235 Info.discardCleanups(); 16236 Info.EvalStatus.HasSideEffects = false; 16237 16238 // Build fake call to Callee. 16239 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This, 16240 Call); 16241 // FIXME: Missing ExprWithCleanups in enable_if conditions? 16242 FullExpressionRAII Scope(Info); 16243 return Evaluate(Value, Info, this) && Scope.destroy() && 16244 !Info.EvalStatus.HasSideEffects; 16245 } 16246 16247 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 16248 SmallVectorImpl< 16249 PartialDiagnosticAt> &Diags) { 16250 // FIXME: It would be useful to check constexpr function templates, but at the 16251 // moment the constant expression evaluator cannot cope with the non-rigorous 16252 // ASTs which we build for dependent expressions. 16253 if (FD->isDependentContext()) 16254 return true; 16255 16256 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] { 16257 std::string Name; 16258 llvm::raw_string_ostream OS(Name); 16259 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(), 16260 /*Qualified=*/true); 16261 return Name; 16262 }); 16263 16264 Expr::EvalStatus Status; 16265 Status.Diag = &Diags; 16266 16267 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 16268 Info.InConstantContext = true; 16269 Info.CheckingPotentialConstantExpression = true; 16270 16271 // The constexpr VM attempts to compile all methods to bytecode here. 16272 if (Info.EnableNewConstInterp) { 16273 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 16274 return Diags.empty(); 16275 } 16276 16277 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 16278 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 16279 16280 // Fabricate an arbitrary expression on the stack and pretend that it 16281 // is a temporary being used as the 'this' pointer. 16282 LValue This; 16283 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 16284 This.set({&VIE, Info.CurrentCall->Index}); 16285 16286 ArrayRef<const Expr*> Args; 16287 16288 APValue Scratch; 16289 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 16290 // Evaluate the call as a constant initializer, to allow the construction 16291 // of objects of non-literal types. 16292 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 16293 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 16294 } else { 16295 SourceLocation Loc = FD->getLocation(); 16296 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 16297 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch, 16298 /*ResultSlot=*/nullptr); 16299 } 16300 16301 return Diags.empty(); 16302 } 16303 16304 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 16305 const FunctionDecl *FD, 16306 SmallVectorImpl< 16307 PartialDiagnosticAt> &Diags) { 16308 assert(!E->isValueDependent() && 16309 "Expression evaluator can't be called on a dependent expression."); 16310 16311 Expr::EvalStatus Status; 16312 Status.Diag = &Diags; 16313 16314 EvalInfo Info(FD->getASTContext(), Status, 16315 EvalInfo::EM_ConstantExpressionUnevaluated); 16316 Info.InConstantContext = true; 16317 Info.CheckingPotentialConstantExpression = true; 16318 16319 // Fabricate a call stack frame to give the arguments a plausible cover story. 16320 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr, 16321 /*CallExpr=*/nullptr, CallRef()); 16322 16323 APValue ResultScratch; 16324 Evaluate(ResultScratch, Info, E); 16325 return Diags.empty(); 16326 } 16327 16328 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 16329 unsigned Type) const { 16330 if (!getType()->isPointerType()) 16331 return false; 16332 16333 Expr::EvalStatus Status; 16334 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 16335 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 16336 } 16337 16338 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 16339 EvalInfo &Info) { 16340 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 16341 return false; 16342 16343 LValue String; 16344 16345 if (!EvaluatePointer(E, String, Info)) 16346 return false; 16347 16348 QualType CharTy = E->getType()->getPointeeType(); 16349 16350 // Fast path: if it's a string literal, search the string value. 16351 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 16352 String.getLValueBase().dyn_cast<const Expr *>())) { 16353 StringRef Str = S->getBytes(); 16354 int64_t Off = String.Offset.getQuantity(); 16355 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 16356 S->getCharByteWidth() == 1 && 16357 // FIXME: Add fast-path for wchar_t too. 16358 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 16359 Str = Str.substr(Off); 16360 16361 StringRef::size_type Pos = Str.find(0); 16362 if (Pos != StringRef::npos) 16363 Str = Str.substr(0, Pos); 16364 16365 Result = Str.size(); 16366 return true; 16367 } 16368 16369 // Fall through to slow path. 16370 } 16371 16372 // Slow path: scan the bytes of the string looking for the terminating 0. 16373 for (uint64_t Strlen = 0; /**/; ++Strlen) { 16374 APValue Char; 16375 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 16376 !Char.isInt()) 16377 return false; 16378 if (!Char.getInt()) { 16379 Result = Strlen; 16380 return true; 16381 } 16382 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 16383 return false; 16384 } 16385 } 16386 16387 bool Expr::EvaluateCharRangeAsString(std::string &Result, 16388 const Expr *SizeExpression, 16389 const Expr *PtrExpression, ASTContext &Ctx, 16390 EvalResult &Status) const { 16391 LValue String; 16392 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 16393 Info.InConstantContext = true; 16394 16395 FullExpressionRAII Scope(Info); 16396 APSInt SizeValue; 16397 if (!::EvaluateInteger(SizeExpression, SizeValue, Info)) 16398 return false; 16399 16400 int64_t Size = SizeValue.getExtValue(); 16401 16402 if (!::EvaluatePointer(PtrExpression, String, Info)) 16403 return false; 16404 16405 QualType CharTy = PtrExpression->getType()->getPointeeType(); 16406 for (int64_t I = 0; I < Size; ++I) { 16407 APValue Char; 16408 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String, 16409 Char)) 16410 return false; 16411 16412 APSInt C = Char.getInt(); 16413 Result.push_back(static_cast<char>(C.getExtValue())); 16414 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1)) 16415 return false; 16416 } 16417 if (!Scope.destroy()) 16418 return false; 16419 16420 if (!CheckMemoryLeaks(Info)) 16421 return false; 16422 16423 return true; 16424 } 16425 16426 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 16427 Expr::EvalStatus Status; 16428 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 16429 return EvaluateBuiltinStrLen(this, Result, Info); 16430 } 16431