1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isPRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 112 return DirectCallee->getAttr<AllocSizeAttr>(); 113 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 114 return IndirectCallee->getAttr<AllocSizeAttr>(); 115 return nullptr; 116 } 117 118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 119 /// This will look through a single cast. 120 /// 121 /// Returns null if we couldn't unwrap a function with alloc_size. 122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 123 if (!E->getType()->isPointerType()) 124 return nullptr; 125 126 E = E->IgnoreParens(); 127 // If we're doing a variable assignment from e.g. malloc(N), there will 128 // probably be a cast of some kind. In exotic cases, we might also see a 129 // top-level ExprWithCleanups. Ignore them either way. 130 if (const auto *FE = dyn_cast<FullExpr>(E)) 131 E = FE->getSubExpr()->IgnoreParens(); 132 133 if (const auto *Cast = dyn_cast<CastExpr>(E)) 134 E = Cast->getSubExpr()->IgnoreParens(); 135 136 if (const auto *CE = dyn_cast<CallExpr>(E)) 137 return getAllocSizeAttr(CE) ? CE : nullptr; 138 return nullptr; 139 } 140 141 /// Determines whether or not the given Base contains a call to a function 142 /// with the alloc_size attribute. 143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 144 const auto *E = Base.dyn_cast<const Expr *>(); 145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 146 } 147 148 /// Determines whether the given kind of constant expression is only ever 149 /// used for name mangling. If so, it's permitted to reference things that we 150 /// can't generate code for (in particular, dllimported functions). 151 static bool isForManglingOnly(ConstantExprKind Kind) { 152 switch (Kind) { 153 case ConstantExprKind::Normal: 154 case ConstantExprKind::ClassTemplateArgument: 155 case ConstantExprKind::ImmediateInvocation: 156 // Note that non-type template arguments of class type are emitted as 157 // template parameter objects. 158 return false; 159 160 case ConstantExprKind::NonClassTemplateArgument: 161 return true; 162 } 163 llvm_unreachable("unknown ConstantExprKind"); 164 } 165 166 static bool isTemplateArgument(ConstantExprKind Kind) { 167 switch (Kind) { 168 case ConstantExprKind::Normal: 169 case ConstantExprKind::ImmediateInvocation: 170 return false; 171 172 case ConstantExprKind::ClassTemplateArgument: 173 case ConstantExprKind::NonClassTemplateArgument: 174 return true; 175 } 176 llvm_unreachable("unknown ConstantExprKind"); 177 } 178 179 /// The bound to claim that an array of unknown bound has. 180 /// The value in MostDerivedArraySize is undefined in this case. So, set it 181 /// to an arbitrary value that's likely to loudly break things if it's used. 182 static const uint64_t AssumedSizeForUnsizedArray = 183 std::numeric_limits<uint64_t>::max() / 2; 184 185 /// Determines if an LValue with the given LValueBase will have an unsized 186 /// array in its designator. 187 /// Find the path length and type of the most-derived subobject in the given 188 /// path, and find the size of the containing array, if any. 189 static unsigned 190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 191 ArrayRef<APValue::LValuePathEntry> Path, 192 uint64_t &ArraySize, QualType &Type, bool &IsArray, 193 bool &FirstEntryIsUnsizedArray) { 194 // This only accepts LValueBases from APValues, and APValues don't support 195 // arrays that lack size info. 196 assert(!isBaseAnAllocSizeCall(Base) && 197 "Unsized arrays shouldn't appear here"); 198 unsigned MostDerivedLength = 0; 199 Type = getType(Base); 200 201 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 202 if (Type->isArrayType()) { 203 const ArrayType *AT = Ctx.getAsArrayType(Type); 204 Type = AT->getElementType(); 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 209 ArraySize = CAT->getSize().getZExtValue(); 210 } else { 211 assert(I == 0 && "unexpected unsized array designator"); 212 FirstEntryIsUnsizedArray = true; 213 ArraySize = AssumedSizeForUnsizedArray; 214 } 215 } else if (Type->isAnyComplexType()) { 216 const ComplexType *CT = Type->castAs<ComplexType>(); 217 Type = CT->getElementType(); 218 ArraySize = 2; 219 MostDerivedLength = I + 1; 220 IsArray = true; 221 } else if (const FieldDecl *FD = getAsField(Path[I])) { 222 Type = FD->getType(); 223 ArraySize = 0; 224 MostDerivedLength = I + 1; 225 IsArray = false; 226 } else { 227 // Path[I] describes a base class. 228 ArraySize = 0; 229 IsArray = false; 230 } 231 } 232 return MostDerivedLength; 233 } 234 235 /// A path from a glvalue to a subobject of that glvalue. 236 struct SubobjectDesignator { 237 /// True if the subobject was named in a manner not supported by C++11. Such 238 /// lvalues can still be folded, but they are not core constant expressions 239 /// and we cannot perform lvalue-to-rvalue conversions on them. 240 unsigned Invalid : 1; 241 242 /// Is this a pointer one past the end of an object? 243 unsigned IsOnePastTheEnd : 1; 244 245 /// Indicator of whether the first entry is an unsized array. 246 unsigned FirstEntryIsAnUnsizedArray : 1; 247 248 /// Indicator of whether the most-derived object is an array element. 249 unsigned MostDerivedIsArrayElement : 1; 250 251 /// The length of the path to the most-derived object of which this is a 252 /// subobject. 253 unsigned MostDerivedPathLength : 28; 254 255 /// The size of the array of which the most-derived object is an element. 256 /// This will always be 0 if the most-derived object is not an array 257 /// element. 0 is not an indicator of whether or not the most-derived object 258 /// is an array, however, because 0-length arrays are allowed. 259 /// 260 /// If the current array is an unsized array, the value of this is 261 /// undefined. 262 uint64_t MostDerivedArraySize; 263 264 /// The type of the most derived object referred to by this address. 265 QualType MostDerivedType; 266 267 typedef APValue::LValuePathEntry PathEntry; 268 269 /// The entries on the path from the glvalue to the designated subobject. 270 SmallVector<PathEntry, 8> Entries; 271 272 SubobjectDesignator() : Invalid(true) {} 273 274 explicit SubobjectDesignator(QualType T) 275 : Invalid(false), IsOnePastTheEnd(false), 276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 277 MostDerivedPathLength(0), MostDerivedArraySize(0), 278 MostDerivedType(T) {} 279 280 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 283 MostDerivedPathLength(0), MostDerivedArraySize(0) { 284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 285 if (!Invalid) { 286 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 287 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 289 if (V.getLValueBase()) { 290 bool IsArray = false; 291 bool FirstIsUnsizedArray = false; 292 MostDerivedPathLength = findMostDerivedSubobject( 293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 294 MostDerivedType, IsArray, FirstIsUnsizedArray); 295 MostDerivedIsArrayElement = IsArray; 296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 297 } 298 } 299 } 300 301 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 302 unsigned NewLength) { 303 if (Invalid) 304 return; 305 306 assert(Base && "cannot truncate path for null pointer"); 307 assert(NewLength <= Entries.size() && "not a truncation"); 308 309 if (NewLength == Entries.size()) 310 return; 311 Entries.resize(NewLength); 312 313 bool IsArray = false; 314 bool FirstIsUnsizedArray = false; 315 MostDerivedPathLength = findMostDerivedSubobject( 316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 317 FirstIsUnsizedArray); 318 MostDerivedIsArrayElement = IsArray; 319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 320 } 321 322 void setInvalid() { 323 Invalid = true; 324 Entries.clear(); 325 } 326 327 /// Determine whether the most derived subobject is an array without a 328 /// known bound. 329 bool isMostDerivedAnUnsizedArray() const { 330 assert(!Invalid && "Calling this makes no sense on invalid designators"); 331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 332 } 333 334 /// Determine what the most derived array's size is. Results in an assertion 335 /// failure if the most derived array lacks a size. 336 uint64_t getMostDerivedArraySize() const { 337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 338 return MostDerivedArraySize; 339 } 340 341 /// Determine whether this is a one-past-the-end pointer. 342 bool isOnePastTheEnd() const { 343 assert(!Invalid); 344 if (IsOnePastTheEnd) 345 return true; 346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 348 MostDerivedArraySize) 349 return true; 350 return false; 351 } 352 353 /// Get the range of valid index adjustments in the form 354 /// {maximum value that can be subtracted from this pointer, 355 /// maximum value that can be added to this pointer} 356 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 357 if (Invalid || isMostDerivedAnUnsizedArray()) 358 return {0, 0}; 359 360 // [expr.add]p4: For the purposes of these operators, a pointer to a 361 // nonarray object behaves the same as a pointer to the first element of 362 // an array of length one with the type of the object as its element type. 363 bool IsArray = MostDerivedPathLength == Entries.size() && 364 MostDerivedIsArrayElement; 365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 366 : (uint64_t)IsOnePastTheEnd; 367 uint64_t ArraySize = 368 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 369 return {ArrayIndex, ArraySize - ArrayIndex}; 370 } 371 372 /// Check that this refers to a valid subobject. 373 bool isValidSubobject() const { 374 if (Invalid) 375 return false; 376 return !isOnePastTheEnd(); 377 } 378 /// Check that this refers to a valid subobject, and if not, produce a 379 /// relevant diagnostic and set the designator as invalid. 380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 381 382 /// Get the type of the designated object. 383 QualType getType(ASTContext &Ctx) const { 384 assert(!Invalid && "invalid designator has no subobject type"); 385 return MostDerivedPathLength == Entries.size() 386 ? MostDerivedType 387 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 388 } 389 390 /// Update this designator to refer to the first element within this array. 391 void addArrayUnchecked(const ConstantArrayType *CAT) { 392 Entries.push_back(PathEntry::ArrayIndex(0)); 393 394 // This is a most-derived object. 395 MostDerivedType = CAT->getElementType(); 396 MostDerivedIsArrayElement = true; 397 MostDerivedArraySize = CAT->getSize().getZExtValue(); 398 MostDerivedPathLength = Entries.size(); 399 } 400 /// Update this designator to refer to the first element within the array of 401 /// elements of type T. This is an array of unknown size. 402 void addUnsizedArrayUnchecked(QualType ElemTy) { 403 Entries.push_back(PathEntry::ArrayIndex(0)); 404 405 MostDerivedType = ElemTy; 406 MostDerivedIsArrayElement = true; 407 // The value in MostDerivedArraySize is undefined in this case. So, set it 408 // to an arbitrary value that's likely to loudly break things if it's 409 // used. 410 MostDerivedArraySize = AssumedSizeForUnsizedArray; 411 MostDerivedPathLength = Entries.size(); 412 } 413 /// Update this designator to refer to the given base or member of this 414 /// object. 415 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 417 418 // If this isn't a base class, it's a new most-derived object. 419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 420 MostDerivedType = FD->getType(); 421 MostDerivedIsArrayElement = false; 422 MostDerivedArraySize = 0; 423 MostDerivedPathLength = Entries.size(); 424 } 425 } 426 /// Update this designator to refer to the given complex component. 427 void addComplexUnchecked(QualType EltTy, bool Imag) { 428 Entries.push_back(PathEntry::ArrayIndex(Imag)); 429 430 // This is technically a most-derived object, though in practice this 431 // is unlikely to matter. 432 MostDerivedType = EltTy; 433 MostDerivedIsArrayElement = true; 434 MostDerivedArraySize = 2; 435 MostDerivedPathLength = Entries.size(); 436 } 437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 439 const APSInt &N); 440 /// Add N to the address of this subobject. 441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 442 if (Invalid || !N) return; 443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 444 if (isMostDerivedAnUnsizedArray()) { 445 diagnoseUnsizedArrayPointerArithmetic(Info, E); 446 // Can't verify -- trust that the user is doing the right thing (or if 447 // not, trust that the caller will catch the bad behavior). 448 // FIXME: Should we reject if this overflows, at least? 449 Entries.back() = PathEntry::ArrayIndex( 450 Entries.back().getAsArrayIndex() + TruncatedN); 451 return; 452 } 453 454 // [expr.add]p4: For the purposes of these operators, a pointer to a 455 // nonarray object behaves the same as a pointer to the first element of 456 // an array of length one with the type of the object as its element type. 457 bool IsArray = MostDerivedPathLength == Entries.size() && 458 MostDerivedIsArrayElement; 459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 460 : (uint64_t)IsOnePastTheEnd; 461 uint64_t ArraySize = 462 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 463 464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 465 // Calculate the actual index in a wide enough type, so we can include 466 // it in the note. 467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 468 (llvm::APInt&)N += ArrayIndex; 469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 470 diagnosePointerArithmetic(Info, E, N); 471 setInvalid(); 472 return; 473 } 474 475 ArrayIndex += TruncatedN; 476 assert(ArrayIndex <= ArraySize && 477 "bounds check succeeded for out-of-bounds index"); 478 479 if (IsArray) 480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 481 else 482 IsOnePastTheEnd = (ArrayIndex != 0); 483 } 484 }; 485 486 /// A scope at the end of which an object can need to be destroyed. 487 enum class ScopeKind { 488 Block, 489 FullExpression, 490 Call 491 }; 492 493 /// A reference to a particular call and its arguments. 494 struct CallRef { 495 CallRef() : OrigCallee(), CallIndex(0), Version() {} 496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 498 499 explicit operator bool() const { return OrigCallee; } 500 501 /// Get the parameter that the caller initialized, corresponding to the 502 /// given parameter in the callee. 503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 505 : PVD; 506 } 507 508 /// The callee at the point where the arguments were evaluated. This might 509 /// be different from the actual callee (a different redeclaration, or a 510 /// virtual override), but this function's parameters are the ones that 511 /// appear in the parameter map. 512 const FunctionDecl *OrigCallee; 513 /// The call index of the frame that holds the argument values. 514 unsigned CallIndex; 515 /// The version of the parameters corresponding to this call. 516 unsigned Version; 517 }; 518 519 /// A stack frame in the constexpr call stack. 520 class CallStackFrame : public interp::Frame { 521 public: 522 EvalInfo &Info; 523 524 /// Parent - The caller of this stack frame. 525 CallStackFrame *Caller; 526 527 /// Callee - The function which was called. 528 const FunctionDecl *Callee; 529 530 /// This - The binding for the this pointer in this call, if any. 531 const LValue *This; 532 533 /// Information on how to find the arguments to this call. Our arguments 534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 535 /// key and this value as the version. 536 CallRef Arguments; 537 538 /// Source location information about the default argument or default 539 /// initializer expression we're evaluating, if any. 540 CurrentSourceLocExprScope CurSourceLocExprScope; 541 542 // Note that we intentionally use std::map here so that references to 543 // values are stable. 544 typedef std::pair<const void *, unsigned> MapKeyTy; 545 typedef std::map<MapKeyTy, APValue> MapTy; 546 /// Temporaries - Temporary lvalues materialized within this stack frame. 547 MapTy Temporaries; 548 549 /// CallLoc - The location of the call expression for this call. 550 SourceLocation CallLoc; 551 552 /// Index - The call index of this call. 553 unsigned Index; 554 555 /// The stack of integers for tracking version numbers for temporaries. 556 SmallVector<unsigned, 2> TempVersionStack = {1}; 557 unsigned CurTempVersion = TempVersionStack.back(); 558 559 unsigned getTempVersion() const { return TempVersionStack.back(); } 560 561 void pushTempVersion() { 562 TempVersionStack.push_back(++CurTempVersion); 563 } 564 565 void popTempVersion() { 566 TempVersionStack.pop_back(); 567 } 568 569 CallRef createCall(const FunctionDecl *Callee) { 570 return {Callee, Index, ++CurTempVersion}; 571 } 572 573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 574 // on the overall stack usage of deeply-recursing constexpr evaluations. 575 // (We should cache this map rather than recomputing it repeatedly.) 576 // But let's try this and see how it goes; we can look into caching the map 577 // as a later change. 578 579 /// LambdaCaptureFields - Mapping from captured variables/this to 580 /// corresponding data members in the closure class. 581 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 582 FieldDecl *LambdaThisCaptureField; 583 584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 585 const FunctionDecl *Callee, const LValue *This, 586 CallRef Arguments); 587 ~CallStackFrame(); 588 589 // Return the temporary for Key whose version number is Version. 590 APValue *getTemporary(const void *Key, unsigned Version) { 591 MapKeyTy KV(Key, Version); 592 auto LB = Temporaries.lower_bound(KV); 593 if (LB != Temporaries.end() && LB->first == KV) 594 return &LB->second; 595 // Pair (Key,Version) wasn't found in the map. Check that no elements 596 // in the map have 'Key' as their key. 597 assert((LB == Temporaries.end() || LB->first.first != Key) && 598 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 599 "Element with key 'Key' found in map"); 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) 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 665 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 666 const LValue &This, QualType ThisType); 667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 668 APValue::LValueBase LVBase, APValue &Value, 669 QualType T); 670 671 namespace { 672 /// A cleanup, and a flag indicating whether it is lifetime-extended. 673 class Cleanup { 674 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 675 APValue::LValueBase Base; 676 QualType T; 677 678 public: 679 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 680 ScopeKind Scope) 681 : Value(Val, Scope), Base(Base), T(T) {} 682 683 /// Determine whether this cleanup should be performed at the end of the 684 /// given kind of scope. 685 bool isDestroyedAtEndOf(ScopeKind K) const { 686 return (int)Value.getInt() >= (int)K; 687 } 688 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 689 if (RunDestructors) { 690 SourceLocation Loc; 691 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 692 Loc = VD->getLocation(); 693 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 694 Loc = E->getExprLoc(); 695 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 696 } 697 *Value.getPointer() = APValue(); 698 return true; 699 } 700 701 bool hasSideEffect() { 702 return T.isDestructedType(); 703 } 704 }; 705 706 /// A reference to an object whose construction we are currently evaluating. 707 struct ObjectUnderConstruction { 708 APValue::LValueBase Base; 709 ArrayRef<APValue::LValuePathEntry> Path; 710 friend bool operator==(const ObjectUnderConstruction &LHS, 711 const ObjectUnderConstruction &RHS) { 712 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 713 } 714 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 715 return llvm::hash_combine(Obj.Base, Obj.Path); 716 } 717 }; 718 enum class ConstructionPhase { 719 None, 720 Bases, 721 AfterBases, 722 AfterFields, 723 Destroying, 724 DestroyingBases 725 }; 726 } 727 728 namespace llvm { 729 template<> struct DenseMapInfo<ObjectUnderConstruction> { 730 using Base = DenseMapInfo<APValue::LValueBase>; 731 static ObjectUnderConstruction getEmptyKey() { 732 return {Base::getEmptyKey(), {}}; } 733 static ObjectUnderConstruction getTombstoneKey() { 734 return {Base::getTombstoneKey(), {}}; 735 } 736 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 737 return hash_value(Object); 738 } 739 static bool isEqual(const ObjectUnderConstruction &LHS, 740 const ObjectUnderConstruction &RHS) { 741 return LHS == RHS; 742 } 743 }; 744 } 745 746 namespace { 747 /// A dynamically-allocated heap object. 748 struct DynAlloc { 749 /// The value of this heap-allocated object. 750 APValue Value; 751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 752 /// or a CallExpr (the latter is for direct calls to operator new inside 753 /// std::allocator<T>::allocate). 754 const Expr *AllocExpr = nullptr; 755 756 enum Kind { 757 New, 758 ArrayNew, 759 StdAllocator 760 }; 761 762 /// Get the kind of the allocation. This must match between allocation 763 /// and deallocation. 764 Kind getKind() const { 765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 766 return NE->isArray() ? ArrayNew : New; 767 assert(isa<CallExpr>(AllocExpr)); 768 return StdAllocator; 769 } 770 }; 771 772 struct DynAllocOrder { 773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 774 return L.getIndex() < R.getIndex(); 775 } 776 }; 777 778 /// EvalInfo - This is a private struct used by the evaluator to capture 779 /// information about a subexpression as it is folded. It retains information 780 /// about the AST context, but also maintains information about the folded 781 /// expression. 782 /// 783 /// If an expression could be evaluated, it is still possible it is not a C 784 /// "integer constant expression" or constant expression. If not, this struct 785 /// captures information about how and why not. 786 /// 787 /// One bit of information passed *into* the request for constant folding 788 /// indicates whether the subexpression is "evaluated" or not according to C 789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 790 /// evaluate the expression regardless of what the RHS is, but C only allows 791 /// certain things in certain situations. 792 class EvalInfo : public interp::State { 793 public: 794 ASTContext &Ctx; 795 796 /// EvalStatus - Contains information about the evaluation. 797 Expr::EvalStatus &EvalStatus; 798 799 /// CurrentCall - The top of the constexpr call stack. 800 CallStackFrame *CurrentCall; 801 802 /// CallStackDepth - The number of calls in the call stack right now. 803 unsigned CallStackDepth; 804 805 /// NextCallIndex - The next call index to assign. 806 unsigned NextCallIndex; 807 808 /// StepsLeft - The remaining number of evaluation steps we're permitted 809 /// to perform. This is essentially a limit for the number of statements 810 /// we will evaluate. 811 unsigned StepsLeft; 812 813 /// Enable the experimental new constant interpreter. If an expression is 814 /// not supported by the interpreter, an error is triggered. 815 bool EnableNewConstInterp; 816 817 /// BottomFrame - The frame in which evaluation started. This must be 818 /// initialized after CurrentCall and CallStackDepth. 819 CallStackFrame BottomFrame; 820 821 /// A stack of values whose lifetimes end at the end of some surrounding 822 /// evaluation frame. 823 llvm::SmallVector<Cleanup, 16> CleanupStack; 824 825 /// EvaluatingDecl - This is the declaration whose initializer is being 826 /// evaluated, if any. 827 APValue::LValueBase EvaluatingDecl; 828 829 enum class EvaluatingDeclKind { 830 None, 831 /// We're evaluating the construction of EvaluatingDecl. 832 Ctor, 833 /// We're evaluating the destruction of EvaluatingDecl. 834 Dtor, 835 }; 836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 837 838 /// EvaluatingDeclValue - This is the value being constructed for the 839 /// declaration whose initializer is being evaluated, if any. 840 APValue *EvaluatingDeclValue; 841 842 /// Set of objects that are currently being constructed. 843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 844 ObjectsUnderConstruction; 845 846 /// Current heap allocations, along with the location where each was 847 /// allocated. We use std::map here because we need stable addresses 848 /// for the stored APValues. 849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 850 851 /// The number of heap allocations performed so far in this evaluation. 852 unsigned NumHeapAllocs = 0; 853 854 struct EvaluatingConstructorRAII { 855 EvalInfo &EI; 856 ObjectUnderConstruction Object; 857 bool DidInsert; 858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 859 bool HasBases) 860 : EI(EI), Object(Object) { 861 DidInsert = 862 EI.ObjectsUnderConstruction 863 .insert({Object, HasBases ? ConstructionPhase::Bases 864 : ConstructionPhase::AfterBases}) 865 .second; 866 } 867 void finishedConstructingBases() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 869 } 870 void finishedConstructingFields() { 871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 872 } 873 ~EvaluatingConstructorRAII() { 874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 875 } 876 }; 877 878 struct EvaluatingDestructorRAII { 879 EvalInfo &EI; 880 ObjectUnderConstruction Object; 881 bool DidInsert; 882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 883 : EI(EI), Object(Object) { 884 DidInsert = EI.ObjectsUnderConstruction 885 .insert({Object, ConstructionPhase::Destroying}) 886 .second; 887 } 888 void startedDestroyingBases() { 889 EI.ObjectsUnderConstruction[Object] = 890 ConstructionPhase::DestroyingBases; 891 } 892 ~EvaluatingDestructorRAII() { 893 if (DidInsert) 894 EI.ObjectsUnderConstruction.erase(Object); 895 } 896 }; 897 898 ConstructionPhase 899 isEvaluatingCtorDtor(APValue::LValueBase Base, 900 ArrayRef<APValue::LValuePathEntry> Path) { 901 return ObjectsUnderConstruction.lookup({Base, Path}); 902 } 903 904 /// If we're currently speculatively evaluating, the outermost call stack 905 /// depth at which we can mutate state, otherwise 0. 906 unsigned SpeculativeEvaluationDepth = 0; 907 908 /// The current array initialization index, if we're performing array 909 /// initialization. 910 uint64_t ArrayInitIndex = -1; 911 912 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 913 /// notes attached to it will also be stored, otherwise they will not be. 914 bool HasActiveDiagnostic; 915 916 /// Have we emitted a diagnostic explaining why we couldn't constant 917 /// fold (not just why it's not strictly a constant expression)? 918 bool HasFoldFailureDiagnostic; 919 920 /// Whether or not we're in a context where the front end requires a 921 /// constant value. 922 bool InConstantContext; 923 924 /// Whether we're checking that an expression is a potential constant 925 /// expression. If so, do not fail on constructs that could become constant 926 /// later on (such as a use of an undefined global). 927 bool CheckingPotentialConstantExpression = false; 928 929 /// Whether we're checking for an expression that has undefined behavior. 930 /// If so, we will produce warnings if we encounter an operation that is 931 /// always undefined. 932 /// 933 /// Note that we still need to evaluate the expression normally when this 934 /// is set; this is used when evaluating ICEs in C. 935 bool CheckingForUndefinedBehavior = false; 936 937 enum EvaluationMode { 938 /// Evaluate as a constant expression. Stop if we find that the expression 939 /// is not a constant expression. 940 EM_ConstantExpression, 941 942 /// Evaluate as a constant expression. Stop if we find that the expression 943 /// is not a constant expression. Some expressions can be retried in the 944 /// optimizer if we don't constant fold them here, but in an unevaluated 945 /// context we try to fold them immediately since the optimizer never 946 /// gets a chance to look at it. 947 EM_ConstantExpressionUnevaluated, 948 949 /// Fold the expression to a constant. Stop if we hit a side-effect that 950 /// we can't model. 951 EM_ConstantFold, 952 953 /// Evaluate in any way we know how. Don't worry about side-effects that 954 /// can't be modeled. 955 EM_IgnoreSideEffects, 956 } EvalMode; 957 958 /// Are we checking whether the expression is a potential constant 959 /// expression? 960 bool checkingPotentialConstantExpression() const override { 961 return CheckingPotentialConstantExpression; 962 } 963 964 /// Are we checking an expression for overflow? 965 // FIXME: We should check for any kind of undefined or suspicious behavior 966 // in such constructs, not just overflow. 967 bool checkingForUndefinedBehavior() const override { 968 return CheckingForUndefinedBehavior; 969 } 970 971 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 972 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 973 CallStackDepth(0), NextCallIndex(1), 974 StepsLeft(C.getLangOpts().ConstexprStepLimit), 975 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 976 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 977 EvaluatingDecl((const ValueDecl *)nullptr), 978 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 979 HasFoldFailureDiagnostic(false), InConstantContext(false), 980 EvalMode(Mode) {} 981 982 ~EvalInfo() { 983 discardCleanups(); 984 } 985 986 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 987 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 988 EvaluatingDecl = Base; 989 IsEvaluatingDecl = EDK; 990 EvaluatingDeclValue = &Value; 991 } 992 993 bool CheckCallLimit(SourceLocation Loc) { 994 // Don't perform any constexpr calls (other than the call we're checking) 995 // when checking a potential constant expression. 996 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 997 return false; 998 if (NextCallIndex == 0) { 999 // NextCallIndex has wrapped around. 1000 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1001 return false; 1002 } 1003 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1004 return true; 1005 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1006 << getLangOpts().ConstexprCallDepth; 1007 return false; 1008 } 1009 1010 std::pair<CallStackFrame *, unsigned> 1011 getCallFrameAndDepth(unsigned CallIndex) { 1012 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1013 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1014 // be null in this loop. 1015 unsigned Depth = CallStackDepth; 1016 CallStackFrame *Frame = CurrentCall; 1017 while (Frame->Index > CallIndex) { 1018 Frame = Frame->Caller; 1019 --Depth; 1020 } 1021 if (Frame->Index == CallIndex) 1022 return {Frame, Depth}; 1023 return {nullptr, 0}; 1024 } 1025 1026 bool nextStep(const Stmt *S) { 1027 if (!StepsLeft) { 1028 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1029 return false; 1030 } 1031 --StepsLeft; 1032 return true; 1033 } 1034 1035 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1036 1037 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1038 Optional<DynAlloc*> Result; 1039 auto It = HeapAllocs.find(DA); 1040 if (It != HeapAllocs.end()) 1041 Result = &It->second; 1042 return Result; 1043 } 1044 1045 /// Get the allocated storage for the given parameter of the given call. 1046 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1047 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1048 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1049 : nullptr; 1050 } 1051 1052 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1053 struct StdAllocatorCaller { 1054 unsigned FrameIndex; 1055 QualType ElemType; 1056 explicit operator bool() const { return FrameIndex != 0; }; 1057 }; 1058 1059 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1060 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1061 Call = Call->Caller) { 1062 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1063 if (!MD) 1064 continue; 1065 const IdentifierInfo *FnII = MD->getIdentifier(); 1066 if (!FnII || !FnII->isStr(FnName)) 1067 continue; 1068 1069 const auto *CTSD = 1070 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1071 if (!CTSD) 1072 continue; 1073 1074 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1075 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1076 if (CTSD->isInStdNamespace() && ClassII && 1077 ClassII->isStr("allocator") && TAL.size() >= 1 && 1078 TAL[0].getKind() == TemplateArgument::Type) 1079 return {Call->Index, TAL[0].getAsType()}; 1080 } 1081 1082 return {}; 1083 } 1084 1085 void performLifetimeExtension() { 1086 // Disable the cleanups for lifetime-extended temporaries. 1087 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1088 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1089 }); 1090 } 1091 1092 /// Throw away any remaining cleanups at the end of evaluation. If any 1093 /// cleanups would have had a side-effect, note that as an unmodeled 1094 /// side-effect and return false. Otherwise, return true. 1095 bool discardCleanups() { 1096 for (Cleanup &C : CleanupStack) { 1097 if (C.hasSideEffect() && !noteSideEffect()) { 1098 CleanupStack.clear(); 1099 return false; 1100 } 1101 } 1102 CleanupStack.clear(); 1103 return true; 1104 } 1105 1106 private: 1107 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1108 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1109 1110 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1111 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1112 1113 void setFoldFailureDiagnostic(bool Flag) override { 1114 HasFoldFailureDiagnostic = Flag; 1115 } 1116 1117 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1118 1119 ASTContext &getCtx() const override { return Ctx; } 1120 1121 // If we have a prior diagnostic, it will be noting that the expression 1122 // isn't a constant expression. This diagnostic is more important, 1123 // unless we require this evaluation to produce a constant expression. 1124 // 1125 // FIXME: We might want to show both diagnostics to the user in 1126 // EM_ConstantFold mode. 1127 bool hasPriorDiagnostic() override { 1128 if (!EvalStatus.Diag->empty()) { 1129 switch (EvalMode) { 1130 case EM_ConstantFold: 1131 case EM_IgnoreSideEffects: 1132 if (!HasFoldFailureDiagnostic) 1133 break; 1134 // We've already failed to fold something. Keep that diagnostic. 1135 LLVM_FALLTHROUGH; 1136 case EM_ConstantExpression: 1137 case EM_ConstantExpressionUnevaluated: 1138 setActiveDiagnostic(false); 1139 return true; 1140 } 1141 } 1142 return false; 1143 } 1144 1145 unsigned getCallStackDepth() override { return CallStackDepth; } 1146 1147 public: 1148 /// Should we continue evaluation after encountering a side-effect that we 1149 /// couldn't model? 1150 bool keepEvaluatingAfterSideEffect() { 1151 switch (EvalMode) { 1152 case EM_IgnoreSideEffects: 1153 return true; 1154 1155 case EM_ConstantExpression: 1156 case EM_ConstantExpressionUnevaluated: 1157 case EM_ConstantFold: 1158 // By default, assume any side effect might be valid in some other 1159 // evaluation of this expression from a different context. 1160 return checkingPotentialConstantExpression() || 1161 checkingForUndefinedBehavior(); 1162 } 1163 llvm_unreachable("Missed EvalMode case"); 1164 } 1165 1166 /// Note that we have had a side-effect, and determine whether we should 1167 /// keep evaluating. 1168 bool noteSideEffect() { 1169 EvalStatus.HasSideEffects = true; 1170 return keepEvaluatingAfterSideEffect(); 1171 } 1172 1173 /// Should we continue evaluation after encountering undefined behavior? 1174 bool keepEvaluatingAfterUndefinedBehavior() { 1175 switch (EvalMode) { 1176 case EM_IgnoreSideEffects: 1177 case EM_ConstantFold: 1178 return true; 1179 1180 case EM_ConstantExpression: 1181 case EM_ConstantExpressionUnevaluated: 1182 return checkingForUndefinedBehavior(); 1183 } 1184 llvm_unreachable("Missed EvalMode case"); 1185 } 1186 1187 /// Note that we hit something that was technically undefined behavior, but 1188 /// that we can evaluate past it (such as signed overflow or floating-point 1189 /// division by zero.) 1190 bool noteUndefinedBehavior() override { 1191 EvalStatus.HasUndefinedBehavior = true; 1192 return keepEvaluatingAfterUndefinedBehavior(); 1193 } 1194 1195 /// Should we continue evaluation as much as possible after encountering a 1196 /// construct which can't be reduced to a value? 1197 bool keepEvaluatingAfterFailure() const override { 1198 if (!StepsLeft) 1199 return false; 1200 1201 switch (EvalMode) { 1202 case EM_ConstantExpression: 1203 case EM_ConstantExpressionUnevaluated: 1204 case EM_ConstantFold: 1205 case EM_IgnoreSideEffects: 1206 return checkingPotentialConstantExpression() || 1207 checkingForUndefinedBehavior(); 1208 } 1209 llvm_unreachable("Missed EvalMode case"); 1210 } 1211 1212 /// Notes that we failed to evaluate an expression that other expressions 1213 /// directly depend on, and determine if we should keep evaluating. This 1214 /// should only be called if we actually intend to keep evaluating. 1215 /// 1216 /// Call noteSideEffect() instead if we may be able to ignore the value that 1217 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1218 /// 1219 /// (Foo(), 1) // use noteSideEffect 1220 /// (Foo() || true) // use noteSideEffect 1221 /// Foo() + 1 // use noteFailure 1222 LLVM_NODISCARD bool noteFailure() { 1223 // Failure when evaluating some expression often means there is some 1224 // subexpression whose evaluation was skipped. Therefore, (because we 1225 // don't track whether we skipped an expression when unwinding after an 1226 // evaluation failure) every evaluation failure that bubbles up from a 1227 // subexpression implies that a side-effect has potentially happened. We 1228 // skip setting the HasSideEffects flag to true until we decide to 1229 // continue evaluating after that point, which happens here. 1230 bool KeepGoing = keepEvaluatingAfterFailure(); 1231 EvalStatus.HasSideEffects |= KeepGoing; 1232 return KeepGoing; 1233 } 1234 1235 class ArrayInitLoopIndex { 1236 EvalInfo &Info; 1237 uint64_t OuterIndex; 1238 1239 public: 1240 ArrayInitLoopIndex(EvalInfo &Info) 1241 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1242 Info.ArrayInitIndex = 0; 1243 } 1244 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1245 1246 operator uint64_t&() { return Info.ArrayInitIndex; } 1247 }; 1248 }; 1249 1250 /// Object used to treat all foldable expressions as constant expressions. 1251 struct FoldConstant { 1252 EvalInfo &Info; 1253 bool Enabled; 1254 bool HadNoPriorDiags; 1255 EvalInfo::EvaluationMode OldMode; 1256 1257 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1258 : Info(Info), 1259 Enabled(Enabled), 1260 HadNoPriorDiags(Info.EvalStatus.Diag && 1261 Info.EvalStatus.Diag->empty() && 1262 !Info.EvalStatus.HasSideEffects), 1263 OldMode(Info.EvalMode) { 1264 if (Enabled) 1265 Info.EvalMode = EvalInfo::EM_ConstantFold; 1266 } 1267 void keepDiagnostics() { Enabled = false; } 1268 ~FoldConstant() { 1269 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1270 !Info.EvalStatus.HasSideEffects) 1271 Info.EvalStatus.Diag->clear(); 1272 Info.EvalMode = OldMode; 1273 } 1274 }; 1275 1276 /// RAII object used to set the current evaluation mode to ignore 1277 /// side-effects. 1278 struct IgnoreSideEffectsRAII { 1279 EvalInfo &Info; 1280 EvalInfo::EvaluationMode OldMode; 1281 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1282 : Info(Info), OldMode(Info.EvalMode) { 1283 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1284 } 1285 1286 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1287 }; 1288 1289 /// RAII object used to optionally suppress diagnostics and side-effects from 1290 /// a speculative evaluation. 1291 class SpeculativeEvaluationRAII { 1292 EvalInfo *Info = nullptr; 1293 Expr::EvalStatus OldStatus; 1294 unsigned OldSpeculativeEvaluationDepth; 1295 1296 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1297 Info = Other.Info; 1298 OldStatus = Other.OldStatus; 1299 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1300 Other.Info = nullptr; 1301 } 1302 1303 void maybeRestoreState() { 1304 if (!Info) 1305 return; 1306 1307 Info->EvalStatus = OldStatus; 1308 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1309 } 1310 1311 public: 1312 SpeculativeEvaluationRAII() = default; 1313 1314 SpeculativeEvaluationRAII( 1315 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1316 : Info(&Info), OldStatus(Info.EvalStatus), 1317 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1318 Info.EvalStatus.Diag = NewDiag; 1319 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1320 } 1321 1322 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1323 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1324 moveFromAndCancel(std::move(Other)); 1325 } 1326 1327 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1328 maybeRestoreState(); 1329 moveFromAndCancel(std::move(Other)); 1330 return *this; 1331 } 1332 1333 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1334 }; 1335 1336 /// RAII object wrapping a full-expression or block scope, and handling 1337 /// the ending of the lifetime of temporaries created within it. 1338 template<ScopeKind Kind> 1339 class ScopeRAII { 1340 EvalInfo &Info; 1341 unsigned OldStackSize; 1342 public: 1343 ScopeRAII(EvalInfo &Info) 1344 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1345 // Push a new temporary version. This is needed to distinguish between 1346 // temporaries created in different iterations of a loop. 1347 Info.CurrentCall->pushTempVersion(); 1348 } 1349 bool destroy(bool RunDestructors = true) { 1350 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1351 OldStackSize = -1U; 1352 return OK; 1353 } 1354 ~ScopeRAII() { 1355 if (OldStackSize != -1U) 1356 destroy(false); 1357 // Body moved to a static method to encourage the compiler to inline away 1358 // instances of this class. 1359 Info.CurrentCall->popTempVersion(); 1360 } 1361 private: 1362 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1363 unsigned OldStackSize) { 1364 assert(OldStackSize <= Info.CleanupStack.size() && 1365 "running cleanups out of order?"); 1366 1367 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1368 // for a full-expression scope. 1369 bool Success = true; 1370 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1371 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1372 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1373 Success = false; 1374 break; 1375 } 1376 } 1377 } 1378 1379 // Compact any retained cleanups. 1380 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1381 if (Kind != ScopeKind::Block) 1382 NewEnd = 1383 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1384 return C.isDestroyedAtEndOf(Kind); 1385 }); 1386 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1387 return Success; 1388 } 1389 }; 1390 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1391 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1392 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1393 } 1394 1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1396 CheckSubobjectKind CSK) { 1397 if (Invalid) 1398 return false; 1399 if (isOnePastTheEnd()) { 1400 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1401 << CSK; 1402 setInvalid(); 1403 return false; 1404 } 1405 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1406 // must actually be at least one array element; even a VLA cannot have a 1407 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1408 return true; 1409 } 1410 1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1412 const Expr *E) { 1413 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1414 // Do not set the designator as invalid: we can represent this situation, 1415 // and correct handling of __builtin_object_size requires us to do so. 1416 } 1417 1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1419 const Expr *E, 1420 const APSInt &N) { 1421 // If we're complaining, we must be able to statically determine the size of 1422 // the most derived array. 1423 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1424 Info.CCEDiag(E, diag::note_constexpr_array_index) 1425 << N << /*array*/ 0 1426 << static_cast<unsigned>(getMostDerivedArraySize()); 1427 else 1428 Info.CCEDiag(E, diag::note_constexpr_array_index) 1429 << N << /*non-array*/ 1; 1430 setInvalid(); 1431 } 1432 1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1434 const FunctionDecl *Callee, const LValue *This, 1435 CallRef Call) 1436 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1437 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1438 Info.CurrentCall = this; 1439 ++Info.CallStackDepth; 1440 } 1441 1442 CallStackFrame::~CallStackFrame() { 1443 assert(Info.CurrentCall == this && "calls retired out of order"); 1444 --Info.CallStackDepth; 1445 Info.CurrentCall = Caller; 1446 } 1447 1448 static bool isRead(AccessKinds AK) { 1449 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1450 } 1451 1452 static bool isModification(AccessKinds AK) { 1453 switch (AK) { 1454 case AK_Read: 1455 case AK_ReadObjectRepresentation: 1456 case AK_MemberCall: 1457 case AK_DynamicCast: 1458 case AK_TypeId: 1459 return false; 1460 case AK_Assign: 1461 case AK_Increment: 1462 case AK_Decrement: 1463 case AK_Construct: 1464 case AK_Destroy: 1465 return true; 1466 } 1467 llvm_unreachable("unknown access kind"); 1468 } 1469 1470 static bool isAnyAccess(AccessKinds AK) { 1471 return isRead(AK) || isModification(AK); 1472 } 1473 1474 /// Is this an access per the C++ definition? 1475 static bool isFormalAccess(AccessKinds AK) { 1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1477 } 1478 1479 /// Is this kind of axcess valid on an indeterminate object value? 1480 static bool isValidIndeterminateAccess(AccessKinds AK) { 1481 switch (AK) { 1482 case AK_Read: 1483 case AK_Increment: 1484 case AK_Decrement: 1485 // These need the object's value. 1486 return false; 1487 1488 case AK_ReadObjectRepresentation: 1489 case AK_Assign: 1490 case AK_Construct: 1491 case AK_Destroy: 1492 // Construction and destruction don't need the value. 1493 return true; 1494 1495 case AK_MemberCall: 1496 case AK_DynamicCast: 1497 case AK_TypeId: 1498 // These aren't really meaningful on scalars. 1499 return true; 1500 } 1501 llvm_unreachable("unknown access kind"); 1502 } 1503 1504 namespace { 1505 struct ComplexValue { 1506 private: 1507 bool IsInt; 1508 1509 public: 1510 APSInt IntReal, IntImag; 1511 APFloat FloatReal, FloatImag; 1512 1513 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1514 1515 void makeComplexFloat() { IsInt = false; } 1516 bool isComplexFloat() const { return !IsInt; } 1517 APFloat &getComplexFloatReal() { return FloatReal; } 1518 APFloat &getComplexFloatImag() { return FloatImag; } 1519 1520 void makeComplexInt() { IsInt = true; } 1521 bool isComplexInt() const { return IsInt; } 1522 APSInt &getComplexIntReal() { return IntReal; } 1523 APSInt &getComplexIntImag() { return IntImag; } 1524 1525 void moveInto(APValue &v) const { 1526 if (isComplexFloat()) 1527 v = APValue(FloatReal, FloatImag); 1528 else 1529 v = APValue(IntReal, IntImag); 1530 } 1531 void setFrom(const APValue &v) { 1532 assert(v.isComplexFloat() || v.isComplexInt()); 1533 if (v.isComplexFloat()) { 1534 makeComplexFloat(); 1535 FloatReal = v.getComplexFloatReal(); 1536 FloatImag = v.getComplexFloatImag(); 1537 } else { 1538 makeComplexInt(); 1539 IntReal = v.getComplexIntReal(); 1540 IntImag = v.getComplexIntImag(); 1541 } 1542 } 1543 }; 1544 1545 struct LValue { 1546 APValue::LValueBase Base; 1547 CharUnits Offset; 1548 SubobjectDesignator Designator; 1549 bool IsNullPtr : 1; 1550 bool InvalidBase : 1; 1551 1552 const APValue::LValueBase getLValueBase() const { return Base; } 1553 CharUnits &getLValueOffset() { return Offset; } 1554 const CharUnits &getLValueOffset() const { return Offset; } 1555 SubobjectDesignator &getLValueDesignator() { return Designator; } 1556 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1557 bool isNullPointer() const { return IsNullPtr;} 1558 1559 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1560 unsigned getLValueVersion() const { return Base.getVersion(); } 1561 1562 void moveInto(APValue &V) const { 1563 if (Designator.Invalid) 1564 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1565 else { 1566 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1567 V = APValue(Base, Offset, Designator.Entries, 1568 Designator.IsOnePastTheEnd, IsNullPtr); 1569 } 1570 } 1571 void setFrom(ASTContext &Ctx, const APValue &V) { 1572 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1573 Base = V.getLValueBase(); 1574 Offset = V.getLValueOffset(); 1575 InvalidBase = false; 1576 Designator = SubobjectDesignator(Ctx, V); 1577 IsNullPtr = V.isNullPointer(); 1578 } 1579 1580 void set(APValue::LValueBase B, bool BInvalid = false) { 1581 #ifndef NDEBUG 1582 // We only allow a few types of invalid bases. Enforce that here. 1583 if (BInvalid) { 1584 const auto *E = B.get<const Expr *>(); 1585 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1586 "Unexpected type of invalid base"); 1587 } 1588 #endif 1589 1590 Base = B; 1591 Offset = CharUnits::fromQuantity(0); 1592 InvalidBase = BInvalid; 1593 Designator = SubobjectDesignator(getType(B)); 1594 IsNullPtr = false; 1595 } 1596 1597 void setNull(ASTContext &Ctx, QualType PointerTy) { 1598 Base = (const ValueDecl *)nullptr; 1599 Offset = 1600 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1601 InvalidBase = false; 1602 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1603 IsNullPtr = true; 1604 } 1605 1606 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1607 set(B, true); 1608 } 1609 1610 std::string toString(ASTContext &Ctx, QualType T) const { 1611 APValue Printable; 1612 moveInto(Printable); 1613 return Printable.getAsString(Ctx, T); 1614 } 1615 1616 private: 1617 // Check that this LValue is not based on a null pointer. If it is, produce 1618 // a diagnostic and mark the designator as invalid. 1619 template <typename GenDiagType> 1620 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1621 if (Designator.Invalid) 1622 return false; 1623 if (IsNullPtr) { 1624 GenDiag(); 1625 Designator.setInvalid(); 1626 return false; 1627 } 1628 return true; 1629 } 1630 1631 public: 1632 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1633 CheckSubobjectKind CSK) { 1634 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1635 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1636 }); 1637 } 1638 1639 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1640 AccessKinds AK) { 1641 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1642 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1643 }); 1644 } 1645 1646 // Check this LValue refers to an object. If not, set the designator to be 1647 // invalid and emit a diagnostic. 1648 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1649 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1650 Designator.checkSubobject(Info, E, CSK); 1651 } 1652 1653 void addDecl(EvalInfo &Info, const Expr *E, 1654 const Decl *D, bool Virtual = false) { 1655 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1656 Designator.addDeclUnchecked(D, Virtual); 1657 } 1658 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1659 if (!Designator.Entries.empty()) { 1660 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1661 Designator.setInvalid(); 1662 return; 1663 } 1664 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1665 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1666 Designator.FirstEntryIsAnUnsizedArray = true; 1667 Designator.addUnsizedArrayUnchecked(ElemTy); 1668 } 1669 } 1670 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1671 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1672 Designator.addArrayUnchecked(CAT); 1673 } 1674 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1675 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1676 Designator.addComplexUnchecked(EltTy, Imag); 1677 } 1678 void clearIsNullPointer() { 1679 IsNullPtr = false; 1680 } 1681 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1682 const APSInt &Index, CharUnits ElementSize) { 1683 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1684 // but we're not required to diagnose it and it's valid in C++.) 1685 if (!Index) 1686 return; 1687 1688 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1689 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1690 // offsets. 1691 uint64_t Offset64 = Offset.getQuantity(); 1692 uint64_t ElemSize64 = ElementSize.getQuantity(); 1693 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1694 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1695 1696 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1697 Designator.adjustIndex(Info, E, Index); 1698 clearIsNullPointer(); 1699 } 1700 void adjustOffset(CharUnits N) { 1701 Offset += N; 1702 if (N.getQuantity()) 1703 clearIsNullPointer(); 1704 } 1705 }; 1706 1707 struct MemberPtr { 1708 MemberPtr() {} 1709 explicit MemberPtr(const ValueDecl *Decl) : 1710 DeclAndIsDerivedMember(Decl, false), Path() {} 1711 1712 /// The member or (direct or indirect) field referred to by this member 1713 /// pointer, or 0 if this is a null member pointer. 1714 const ValueDecl *getDecl() const { 1715 return DeclAndIsDerivedMember.getPointer(); 1716 } 1717 /// Is this actually a member of some type derived from the relevant class? 1718 bool isDerivedMember() const { 1719 return DeclAndIsDerivedMember.getInt(); 1720 } 1721 /// Get the class which the declaration actually lives in. 1722 const CXXRecordDecl *getContainingRecord() const { 1723 return cast<CXXRecordDecl>( 1724 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1725 } 1726 1727 void moveInto(APValue &V) const { 1728 V = APValue(getDecl(), isDerivedMember(), Path); 1729 } 1730 void setFrom(const APValue &V) { 1731 assert(V.isMemberPointer()); 1732 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1733 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1734 Path.clear(); 1735 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1736 Path.insert(Path.end(), P.begin(), P.end()); 1737 } 1738 1739 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1740 /// whether the member is a member of some class derived from the class type 1741 /// of the member pointer. 1742 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1743 /// Path - The path of base/derived classes from the member declaration's 1744 /// class (exclusive) to the class type of the member pointer (inclusive). 1745 SmallVector<const CXXRecordDecl*, 4> Path; 1746 1747 /// Perform a cast towards the class of the Decl (either up or down the 1748 /// hierarchy). 1749 bool castBack(const CXXRecordDecl *Class) { 1750 assert(!Path.empty()); 1751 const CXXRecordDecl *Expected; 1752 if (Path.size() >= 2) 1753 Expected = Path[Path.size() - 2]; 1754 else 1755 Expected = getContainingRecord(); 1756 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1757 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1758 // if B does not contain the original member and is not a base or 1759 // derived class of the class containing the original member, the result 1760 // of the cast is undefined. 1761 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1762 // (D::*). We consider that to be a language defect. 1763 return false; 1764 } 1765 Path.pop_back(); 1766 return true; 1767 } 1768 /// Perform a base-to-derived member pointer cast. 1769 bool castToDerived(const CXXRecordDecl *Derived) { 1770 if (!getDecl()) 1771 return true; 1772 if (!isDerivedMember()) { 1773 Path.push_back(Derived); 1774 return true; 1775 } 1776 if (!castBack(Derived)) 1777 return false; 1778 if (Path.empty()) 1779 DeclAndIsDerivedMember.setInt(false); 1780 return true; 1781 } 1782 /// Perform a derived-to-base member pointer cast. 1783 bool castToBase(const CXXRecordDecl *Base) { 1784 if (!getDecl()) 1785 return true; 1786 if (Path.empty()) 1787 DeclAndIsDerivedMember.setInt(true); 1788 if (isDerivedMember()) { 1789 Path.push_back(Base); 1790 return true; 1791 } 1792 return castBack(Base); 1793 } 1794 }; 1795 1796 /// Compare two member pointers, which are assumed to be of the same type. 1797 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1798 if (!LHS.getDecl() || !RHS.getDecl()) 1799 return !LHS.getDecl() && !RHS.getDecl(); 1800 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1801 return false; 1802 return LHS.Path == RHS.Path; 1803 } 1804 } 1805 1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1808 const LValue &This, const Expr *E, 1809 bool AllowNonLiteralTypes = false); 1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1811 bool InvalidBaseOK = false); 1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1813 bool InvalidBaseOK = false); 1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1815 EvalInfo &Info); 1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1819 EvalInfo &Info); 1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1826 EvalInfo &Info); 1827 1828 /// Evaluate an integer or fixed point expression into an APResult. 1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1830 EvalInfo &Info); 1831 1832 /// Evaluate only a fixed point expression into an APResult. 1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1834 EvalInfo &Info); 1835 1836 //===----------------------------------------------------------------------===// 1837 // Misc utilities 1838 //===----------------------------------------------------------------------===// 1839 1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1841 /// preserving its value (by extending by up to one bit as needed). 1842 static void negateAsSigned(APSInt &Int) { 1843 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1844 Int = Int.extend(Int.getBitWidth() + 1); 1845 Int.setIsSigned(true); 1846 } 1847 Int = -Int; 1848 } 1849 1850 template<typename KeyT> 1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1852 ScopeKind Scope, LValue &LV) { 1853 unsigned Version = getTempVersion(); 1854 APValue::LValueBase Base(Key, Index, Version); 1855 LV.set(Base); 1856 return createLocal(Base, Key, T, Scope); 1857 } 1858 1859 /// Allocate storage for a parameter of a function call made in this frame. 1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1861 LValue &LV) { 1862 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1863 APValue::LValueBase Base(PVD, Index, Args.Version); 1864 LV.set(Base); 1865 // We always destroy parameters at the end of the call, even if we'd allow 1866 // them to live to the end of the full-expression at runtime, in order to 1867 // give portable results and match other compilers. 1868 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1869 } 1870 1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1872 QualType T, ScopeKind Scope) { 1873 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1874 unsigned Version = Base.getVersion(); 1875 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1876 assert(Result.isAbsent() && "local created multiple times"); 1877 1878 // If we're creating a local immediately in the operand of a speculative 1879 // evaluation, don't register a cleanup to be run outside the speculative 1880 // evaluation context, since we won't actually be able to initialize this 1881 // object. 1882 if (Index <= Info.SpeculativeEvaluationDepth) { 1883 if (T.isDestructedType()) 1884 Info.noteSideEffect(); 1885 } else { 1886 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1887 } 1888 return Result; 1889 } 1890 1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1892 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1893 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1894 return nullptr; 1895 } 1896 1897 DynamicAllocLValue DA(NumHeapAllocs++); 1898 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1899 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1900 std::forward_as_tuple(DA), std::tuple<>()); 1901 assert(Result.second && "reused a heap alloc index?"); 1902 Result.first->second.AllocExpr = E; 1903 return &Result.first->second.Value; 1904 } 1905 1906 /// Produce a string describing the given constexpr call. 1907 void CallStackFrame::describe(raw_ostream &Out) { 1908 unsigned ArgIndex = 0; 1909 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1910 !isa<CXXConstructorDecl>(Callee) && 1911 cast<CXXMethodDecl>(Callee)->isInstance(); 1912 1913 if (!IsMemberCall) 1914 Out << *Callee << '('; 1915 1916 if (This && IsMemberCall) { 1917 APValue Val; 1918 This->moveInto(Val); 1919 Val.printPretty(Out, Info.Ctx, 1920 This->Designator.MostDerivedType); 1921 // FIXME: Add parens around Val if needed. 1922 Out << "->" << *Callee << '('; 1923 IsMemberCall = false; 1924 } 1925 1926 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1927 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1928 if (ArgIndex > (unsigned)IsMemberCall) 1929 Out << ", "; 1930 1931 const ParmVarDecl *Param = *I; 1932 APValue *V = Info.getParamSlot(Arguments, Param); 1933 if (V) 1934 V->printPretty(Out, Info.Ctx, Param->getType()); 1935 else 1936 Out << "<...>"; 1937 1938 if (ArgIndex == 0 && IsMemberCall) 1939 Out << "->" << *Callee << '('; 1940 } 1941 1942 Out << ')'; 1943 } 1944 1945 /// Evaluate an expression to see if it had side-effects, and discard its 1946 /// result. 1947 /// \return \c true if the caller should keep evaluating. 1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1949 assert(!E->isValueDependent()); 1950 APValue Scratch; 1951 if (!Evaluate(Scratch, Info, E)) 1952 // We don't need the value, but we might have skipped a side effect here. 1953 return Info.noteSideEffect(); 1954 return true; 1955 } 1956 1957 /// Should this call expression be treated as a string literal? 1958 static bool IsStringLiteralCall(const CallExpr *E) { 1959 unsigned Builtin = E->getBuiltinCallee(); 1960 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1961 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1962 } 1963 1964 static bool IsGlobalLValue(APValue::LValueBase B) { 1965 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1966 // constant expression of pointer type that evaluates to... 1967 1968 // ... a null pointer value, or a prvalue core constant expression of type 1969 // std::nullptr_t. 1970 if (!B) return true; 1971 1972 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1973 // ... the address of an object with static storage duration, 1974 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1975 return VD->hasGlobalStorage(); 1976 if (isa<TemplateParamObjectDecl>(D)) 1977 return true; 1978 // ... the address of a function, 1979 // ... the address of a GUID [MS extension], 1980 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1981 } 1982 1983 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1984 return true; 1985 1986 const Expr *E = B.get<const Expr*>(); 1987 switch (E->getStmtClass()) { 1988 default: 1989 return false; 1990 case Expr::CompoundLiteralExprClass: { 1991 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1992 return CLE->isFileScope() && CLE->isLValue(); 1993 } 1994 case Expr::MaterializeTemporaryExprClass: 1995 // A materialized temporary might have been lifetime-extended to static 1996 // storage duration. 1997 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1998 // A string literal has static storage duration. 1999 case Expr::StringLiteralClass: 2000 case Expr::PredefinedExprClass: 2001 case Expr::ObjCStringLiteralClass: 2002 case Expr::ObjCEncodeExprClass: 2003 return true; 2004 case Expr::ObjCBoxedExprClass: 2005 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2006 case Expr::CallExprClass: 2007 return IsStringLiteralCall(cast<CallExpr>(E)); 2008 // For GCC compatibility, &&label has static storage duration. 2009 case Expr::AddrLabelExprClass: 2010 return true; 2011 // A Block literal expression may be used as the initialization value for 2012 // Block variables at global or local static scope. 2013 case Expr::BlockExprClass: 2014 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2015 case Expr::ImplicitValueInitExprClass: 2016 // FIXME: 2017 // We can never form an lvalue with an implicit value initialization as its 2018 // base through expression evaluation, so these only appear in one case: the 2019 // implicit variable declaration we invent when checking whether a constexpr 2020 // constructor can produce a constant expression. We must assume that such 2021 // an expression might be a global lvalue. 2022 return true; 2023 } 2024 } 2025 2026 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2027 return LVal.Base.dyn_cast<const ValueDecl*>(); 2028 } 2029 2030 static bool IsLiteralLValue(const LValue &Value) { 2031 if (Value.getLValueCallIndex()) 2032 return false; 2033 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2034 return E && !isa<MaterializeTemporaryExpr>(E); 2035 } 2036 2037 static bool IsWeakLValue(const LValue &Value) { 2038 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2039 return Decl && Decl->isWeak(); 2040 } 2041 2042 static bool isZeroSized(const LValue &Value) { 2043 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2044 if (Decl && isa<VarDecl>(Decl)) { 2045 QualType Ty = Decl->getType(); 2046 if (Ty->isArrayType()) 2047 return Ty->isIncompleteType() || 2048 Decl->getASTContext().getTypeSize(Ty) == 0; 2049 } 2050 return false; 2051 } 2052 2053 static bool HasSameBase(const LValue &A, const LValue &B) { 2054 if (!A.getLValueBase()) 2055 return !B.getLValueBase(); 2056 if (!B.getLValueBase()) 2057 return false; 2058 2059 if (A.getLValueBase().getOpaqueValue() != 2060 B.getLValueBase().getOpaqueValue()) 2061 return false; 2062 2063 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2064 A.getLValueVersion() == B.getLValueVersion(); 2065 } 2066 2067 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2068 assert(Base && "no location for a null lvalue"); 2069 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2070 2071 // For a parameter, find the corresponding call stack frame (if it still 2072 // exists), and point at the parameter of the function definition we actually 2073 // invoked. 2074 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2075 unsigned Idx = PVD->getFunctionScopeIndex(); 2076 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2077 if (F->Arguments.CallIndex == Base.getCallIndex() && 2078 F->Arguments.Version == Base.getVersion() && F->Callee && 2079 Idx < F->Callee->getNumParams()) { 2080 VD = F->Callee->getParamDecl(Idx); 2081 break; 2082 } 2083 } 2084 } 2085 2086 if (VD) 2087 Info.Note(VD->getLocation(), diag::note_declared_at); 2088 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2089 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2090 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2091 // FIXME: Produce a note for dangling pointers too. 2092 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2093 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2094 diag::note_constexpr_dynamic_alloc_here); 2095 } 2096 // We have no information to show for a typeid(T) object. 2097 } 2098 2099 enum class CheckEvaluationResultKind { 2100 ConstantExpression, 2101 FullyInitialized, 2102 }; 2103 2104 /// Materialized temporaries that we've already checked to determine if they're 2105 /// initializsed by a constant expression. 2106 using CheckedTemporaries = 2107 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2108 2109 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2110 EvalInfo &Info, SourceLocation DiagLoc, 2111 QualType Type, const APValue &Value, 2112 ConstantExprKind Kind, 2113 SourceLocation SubobjectLoc, 2114 CheckedTemporaries &CheckedTemps); 2115 2116 /// Check that this reference or pointer core constant expression is a valid 2117 /// value for an address or reference constant expression. Return true if we 2118 /// can fold this expression, whether or not it's a constant expression. 2119 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2120 QualType Type, const LValue &LVal, 2121 ConstantExprKind Kind, 2122 CheckedTemporaries &CheckedTemps) { 2123 bool IsReferenceType = Type->isReferenceType(); 2124 2125 APValue::LValueBase Base = LVal.getLValueBase(); 2126 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2127 2128 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2129 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2130 2131 // Additional restrictions apply in a template argument. We only enforce the 2132 // C++20 restrictions here; additional syntactic and semantic restrictions 2133 // are applied elsewhere. 2134 if (isTemplateArgument(Kind)) { 2135 int InvalidBaseKind = -1; 2136 StringRef Ident; 2137 if (Base.is<TypeInfoLValue>()) 2138 InvalidBaseKind = 0; 2139 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2140 InvalidBaseKind = 1; 2141 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2142 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2143 InvalidBaseKind = 2; 2144 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2145 InvalidBaseKind = 3; 2146 Ident = PE->getIdentKindName(); 2147 } 2148 2149 if (InvalidBaseKind != -1) { 2150 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2151 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2152 << Ident; 2153 return false; 2154 } 2155 } 2156 2157 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2158 if (FD->isConsteval()) { 2159 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2160 << !Type->isAnyPointerType(); 2161 Info.Note(FD->getLocation(), diag::note_declared_at); 2162 return false; 2163 } 2164 } 2165 2166 // Check that the object is a global. Note that the fake 'this' object we 2167 // manufacture when checking potential constant expressions is conservatively 2168 // assumed to be global here. 2169 if (!IsGlobalLValue(Base)) { 2170 if (Info.getLangOpts().CPlusPlus11) { 2171 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2172 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2173 << IsReferenceType << !Designator.Entries.empty() 2174 << !!VD << VD; 2175 2176 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2177 if (VarD && VarD->isConstexpr()) { 2178 // Non-static local constexpr variables have unintuitive semantics: 2179 // constexpr int a = 1; 2180 // constexpr const int *p = &a; 2181 // ... is invalid because the address of 'a' is not constant. Suggest 2182 // adding a 'static' in this case. 2183 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2184 << VarD 2185 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2186 } else { 2187 NoteLValueLocation(Info, Base); 2188 } 2189 } else { 2190 Info.FFDiag(Loc); 2191 } 2192 // Don't allow references to temporaries to escape. 2193 return false; 2194 } 2195 assert((Info.checkingPotentialConstantExpression() || 2196 LVal.getLValueCallIndex() == 0) && 2197 "have call index for global lvalue"); 2198 2199 if (Base.is<DynamicAllocLValue>()) { 2200 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2201 << IsReferenceType << !Designator.Entries.empty(); 2202 NoteLValueLocation(Info, Base); 2203 return false; 2204 } 2205 2206 if (BaseVD) { 2207 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2208 // Check if this is a thread-local variable. 2209 if (Var->getTLSKind()) 2210 // FIXME: Diagnostic! 2211 return false; 2212 2213 // A dllimport variable never acts like a constant, unless we're 2214 // evaluating a value for use only in name mangling. 2215 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2216 // FIXME: Diagnostic! 2217 return false; 2218 } 2219 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2220 // __declspec(dllimport) must be handled very carefully: 2221 // We must never initialize an expression with the thunk in C++. 2222 // Doing otherwise would allow the same id-expression to yield 2223 // different addresses for the same function in different translation 2224 // units. However, this means that we must dynamically initialize the 2225 // expression with the contents of the import address table at runtime. 2226 // 2227 // The C language has no notion of ODR; furthermore, it has no notion of 2228 // dynamic initialization. This means that we are permitted to 2229 // perform initialization with the address of the thunk. 2230 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2231 FD->hasAttr<DLLImportAttr>()) 2232 // FIXME: Diagnostic! 2233 return false; 2234 } 2235 } else if (const auto *MTE = 2236 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2237 if (CheckedTemps.insert(MTE).second) { 2238 QualType TempType = getType(Base); 2239 if (TempType.isDestructedType()) { 2240 Info.FFDiag(MTE->getExprLoc(), 2241 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2242 << TempType; 2243 return false; 2244 } 2245 2246 APValue *V = MTE->getOrCreateValue(false); 2247 assert(V && "evasluation result refers to uninitialised temporary"); 2248 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2249 Info, MTE->getExprLoc(), TempType, *V, 2250 Kind, SourceLocation(), CheckedTemps)) 2251 return false; 2252 } 2253 } 2254 2255 // Allow address constant expressions to be past-the-end pointers. This is 2256 // an extension: the standard requires them to point to an object. 2257 if (!IsReferenceType) 2258 return true; 2259 2260 // A reference constant expression must refer to an object. 2261 if (!Base) { 2262 // FIXME: diagnostic 2263 Info.CCEDiag(Loc); 2264 return true; 2265 } 2266 2267 // Does this refer one past the end of some object? 2268 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2269 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2270 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2271 NoteLValueLocation(Info, Base); 2272 } 2273 2274 return true; 2275 } 2276 2277 /// Member pointers are constant expressions unless they point to a 2278 /// non-virtual dllimport member function. 2279 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2280 SourceLocation Loc, 2281 QualType Type, 2282 const APValue &Value, 2283 ConstantExprKind Kind) { 2284 const ValueDecl *Member = Value.getMemberPointerDecl(); 2285 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2286 if (!FD) 2287 return true; 2288 if (FD->isConsteval()) { 2289 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2290 Info.Note(FD->getLocation(), diag::note_declared_at); 2291 return false; 2292 } 2293 return isForManglingOnly(Kind) || FD->isVirtual() || 2294 !FD->hasAttr<DLLImportAttr>(); 2295 } 2296 2297 /// Check that this core constant expression is of literal type, and if not, 2298 /// produce an appropriate diagnostic. 2299 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2300 const LValue *This = nullptr) { 2301 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2302 return true; 2303 2304 // C++1y: A constant initializer for an object o [...] may also invoke 2305 // constexpr constructors for o and its subobjects even if those objects 2306 // are of non-literal class types. 2307 // 2308 // C++11 missed this detail for aggregates, so classes like this: 2309 // struct foo_t { union { int i; volatile int j; } u; }; 2310 // are not (obviously) initializable like so: 2311 // __attribute__((__require_constant_initialization__)) 2312 // static const foo_t x = {{0}}; 2313 // because "i" is a subobject with non-literal initialization (due to the 2314 // volatile member of the union). See: 2315 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2316 // Therefore, we use the C++1y behavior. 2317 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2318 return true; 2319 2320 // Prvalue constant expressions must be of literal types. 2321 if (Info.getLangOpts().CPlusPlus11) 2322 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2323 << E->getType(); 2324 else 2325 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2326 return false; 2327 } 2328 2329 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2330 EvalInfo &Info, SourceLocation DiagLoc, 2331 QualType Type, const APValue &Value, 2332 ConstantExprKind Kind, 2333 SourceLocation SubobjectLoc, 2334 CheckedTemporaries &CheckedTemps) { 2335 if (!Value.hasValue()) { 2336 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2337 << true << Type; 2338 if (SubobjectLoc.isValid()) 2339 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2340 return false; 2341 } 2342 2343 // We allow _Atomic(T) to be initialized from anything that T can be 2344 // initialized from. 2345 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2346 Type = AT->getValueType(); 2347 2348 // Core issue 1454: For a literal constant expression of array or class type, 2349 // each subobject of its value shall have been initialized by a constant 2350 // expression. 2351 if (Value.isArray()) { 2352 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2353 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2354 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2355 Value.getArrayInitializedElt(I), Kind, 2356 SubobjectLoc, CheckedTemps)) 2357 return false; 2358 } 2359 if (!Value.hasArrayFiller()) 2360 return true; 2361 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2362 Value.getArrayFiller(), Kind, SubobjectLoc, 2363 CheckedTemps); 2364 } 2365 if (Value.isUnion() && Value.getUnionField()) { 2366 return CheckEvaluationResult( 2367 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2368 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2369 CheckedTemps); 2370 } 2371 if (Value.isStruct()) { 2372 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2373 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2374 unsigned BaseIndex = 0; 2375 for (const CXXBaseSpecifier &BS : CD->bases()) { 2376 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2377 Value.getStructBase(BaseIndex), Kind, 2378 BS.getBeginLoc(), CheckedTemps)) 2379 return false; 2380 ++BaseIndex; 2381 } 2382 } 2383 for (const auto *I : RD->fields()) { 2384 if (I->isUnnamedBitfield()) 2385 continue; 2386 2387 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2388 Value.getStructField(I->getFieldIndex()), 2389 Kind, I->getLocation(), CheckedTemps)) 2390 return false; 2391 } 2392 } 2393 2394 if (Value.isLValue() && 2395 CERK == CheckEvaluationResultKind::ConstantExpression) { 2396 LValue LVal; 2397 LVal.setFrom(Info.Ctx, Value); 2398 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2399 CheckedTemps); 2400 } 2401 2402 if (Value.isMemberPointer() && 2403 CERK == CheckEvaluationResultKind::ConstantExpression) 2404 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2405 2406 // Everything else is fine. 2407 return true; 2408 } 2409 2410 /// Check that this core constant expression value is a valid value for a 2411 /// constant expression. If not, report an appropriate diagnostic. Does not 2412 /// check that the expression is of literal type. 2413 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2414 QualType Type, const APValue &Value, 2415 ConstantExprKind Kind) { 2416 // Nothing to check for a constant expression of type 'cv void'. 2417 if (Type->isVoidType()) 2418 return true; 2419 2420 CheckedTemporaries CheckedTemps; 2421 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2422 Info, DiagLoc, Type, Value, Kind, 2423 SourceLocation(), CheckedTemps); 2424 } 2425 2426 /// Check that this evaluated value is fully-initialized and can be loaded by 2427 /// an lvalue-to-rvalue conversion. 2428 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2429 QualType Type, const APValue &Value) { 2430 CheckedTemporaries CheckedTemps; 2431 return CheckEvaluationResult( 2432 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2433 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2434 } 2435 2436 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2437 /// "the allocated storage is deallocated within the evaluation". 2438 static bool CheckMemoryLeaks(EvalInfo &Info) { 2439 if (!Info.HeapAllocs.empty()) { 2440 // We can still fold to a constant despite a compile-time memory leak, 2441 // so long as the heap allocation isn't referenced in the result (we check 2442 // that in CheckConstantExpression). 2443 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2444 diag::note_constexpr_memory_leak) 2445 << unsigned(Info.HeapAllocs.size() - 1); 2446 } 2447 return true; 2448 } 2449 2450 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2451 // A null base expression indicates a null pointer. These are always 2452 // evaluatable, and they are false unless the offset is zero. 2453 if (!Value.getLValueBase()) { 2454 Result = !Value.getLValueOffset().isZero(); 2455 return true; 2456 } 2457 2458 // We have a non-null base. These are generally known to be true, but if it's 2459 // a weak declaration it can be null at runtime. 2460 Result = true; 2461 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2462 return !Decl || !Decl->isWeak(); 2463 } 2464 2465 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2466 switch (Val.getKind()) { 2467 case APValue::None: 2468 case APValue::Indeterminate: 2469 return false; 2470 case APValue::Int: 2471 Result = Val.getInt().getBoolValue(); 2472 return true; 2473 case APValue::FixedPoint: 2474 Result = Val.getFixedPoint().getBoolValue(); 2475 return true; 2476 case APValue::Float: 2477 Result = !Val.getFloat().isZero(); 2478 return true; 2479 case APValue::ComplexInt: 2480 Result = Val.getComplexIntReal().getBoolValue() || 2481 Val.getComplexIntImag().getBoolValue(); 2482 return true; 2483 case APValue::ComplexFloat: 2484 Result = !Val.getComplexFloatReal().isZero() || 2485 !Val.getComplexFloatImag().isZero(); 2486 return true; 2487 case APValue::LValue: 2488 return EvalPointerValueAsBool(Val, Result); 2489 case APValue::MemberPointer: 2490 Result = Val.getMemberPointerDecl(); 2491 return true; 2492 case APValue::Vector: 2493 case APValue::Array: 2494 case APValue::Struct: 2495 case APValue::Union: 2496 case APValue::AddrLabelDiff: 2497 return false; 2498 } 2499 2500 llvm_unreachable("unknown APValue kind"); 2501 } 2502 2503 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2504 EvalInfo &Info) { 2505 assert(!E->isValueDependent()); 2506 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2507 APValue Val; 2508 if (!Evaluate(Val, Info, E)) 2509 return false; 2510 return HandleConversionToBool(Val, Result); 2511 } 2512 2513 template<typename T> 2514 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2515 const T &SrcValue, QualType DestType) { 2516 Info.CCEDiag(E, diag::note_constexpr_overflow) 2517 << SrcValue << DestType; 2518 return Info.noteUndefinedBehavior(); 2519 } 2520 2521 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2522 QualType SrcType, const APFloat &Value, 2523 QualType DestType, APSInt &Result) { 2524 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2525 // Determine whether we are converting to unsigned or signed. 2526 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2527 2528 Result = APSInt(DestWidth, !DestSigned); 2529 bool ignored; 2530 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2531 & APFloat::opInvalidOp) 2532 return HandleOverflow(Info, E, Value, DestType); 2533 return true; 2534 } 2535 2536 /// Get rounding mode used for evaluation of the specified expression. 2537 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2538 /// dynamic. 2539 /// If rounding mode is unknown at compile time, still try to evaluate the 2540 /// expression. If the result is exact, it does not depend on rounding mode. 2541 /// So return "tonearest" mode instead of "dynamic". 2542 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2543 bool &DynamicRM) { 2544 llvm::RoundingMode RM = 2545 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2546 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2547 if (DynamicRM) 2548 RM = llvm::RoundingMode::NearestTiesToEven; 2549 return RM; 2550 } 2551 2552 /// Check if the given evaluation result is allowed for constant evaluation. 2553 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2554 APFloat::opStatus St) { 2555 // In a constant context, assume that any dynamic rounding mode or FP 2556 // exception state matches the default floating-point environment. 2557 if (Info.InConstantContext) 2558 return true; 2559 2560 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2561 if ((St & APFloat::opInexact) && 2562 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2563 // Inexact result means that it depends on rounding mode. If the requested 2564 // mode is dynamic, the evaluation cannot be made in compile time. 2565 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2566 return false; 2567 } 2568 2569 if ((St != APFloat::opOK) && 2570 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2571 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2572 FPO.getAllowFEnvAccess())) { 2573 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2574 return false; 2575 } 2576 2577 if ((St & APFloat::opStatus::opInvalidOp) && 2578 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2579 // There is no usefully definable result. 2580 Info.FFDiag(E); 2581 return false; 2582 } 2583 2584 // FIXME: if: 2585 // - evaluation triggered other FP exception, and 2586 // - exception mode is not "ignore", and 2587 // - the expression being evaluated is not a part of global variable 2588 // initializer, 2589 // the evaluation probably need to be rejected. 2590 return true; 2591 } 2592 2593 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2594 QualType SrcType, QualType DestType, 2595 APFloat &Result) { 2596 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2597 bool DynamicRM; 2598 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2599 APFloat::opStatus St; 2600 APFloat Value = Result; 2601 bool ignored; 2602 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2603 return checkFloatingPointResult(Info, E, St); 2604 } 2605 2606 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2607 QualType DestType, QualType SrcType, 2608 const APSInt &Value) { 2609 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2610 // Figure out if this is a truncate, extend or noop cast. 2611 // If the input is signed, do a sign extend, noop, or truncate. 2612 APSInt Result = Value.extOrTrunc(DestWidth); 2613 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2614 if (DestType->isBooleanType()) 2615 Result = Value.getBoolValue(); 2616 return Result; 2617 } 2618 2619 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2620 const FPOptions FPO, 2621 QualType SrcType, const APSInt &Value, 2622 QualType DestType, APFloat &Result) { 2623 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2624 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2625 APFloat::rmNearestTiesToEven); 2626 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2627 FPO.isFPConstrained()) { 2628 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2629 return false; 2630 } 2631 return true; 2632 } 2633 2634 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2635 APValue &Value, const FieldDecl *FD) { 2636 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2637 2638 if (!Value.isInt()) { 2639 // Trying to store a pointer-cast-to-integer into a bitfield. 2640 // FIXME: In this case, we should provide the diagnostic for casting 2641 // a pointer to an integer. 2642 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2643 Info.FFDiag(E); 2644 return false; 2645 } 2646 2647 APSInt &Int = Value.getInt(); 2648 unsigned OldBitWidth = Int.getBitWidth(); 2649 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2650 if (NewBitWidth < OldBitWidth) 2651 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2652 return true; 2653 } 2654 2655 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2656 llvm::APInt &Res) { 2657 APValue SVal; 2658 if (!Evaluate(SVal, Info, E)) 2659 return false; 2660 if (SVal.isInt()) { 2661 Res = SVal.getInt(); 2662 return true; 2663 } 2664 if (SVal.isFloat()) { 2665 Res = SVal.getFloat().bitcastToAPInt(); 2666 return true; 2667 } 2668 if (SVal.isVector()) { 2669 QualType VecTy = E->getType(); 2670 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2671 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2672 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2673 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2674 Res = llvm::APInt::getZero(VecSize); 2675 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2676 APValue &Elt = SVal.getVectorElt(i); 2677 llvm::APInt EltAsInt; 2678 if (Elt.isInt()) { 2679 EltAsInt = Elt.getInt(); 2680 } else if (Elt.isFloat()) { 2681 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2682 } else { 2683 // Don't try to handle vectors of anything other than int or float 2684 // (not sure if it's possible to hit this case). 2685 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2686 return false; 2687 } 2688 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2689 if (BigEndian) 2690 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2691 else 2692 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2693 } 2694 return true; 2695 } 2696 // Give up if the input isn't an int, float, or vector. For example, we 2697 // reject "(v4i16)(intptr_t)&a". 2698 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2699 return false; 2700 } 2701 2702 /// Perform the given integer operation, which is known to need at most BitWidth 2703 /// bits, and check for overflow in the original type (if that type was not an 2704 /// unsigned type). 2705 template<typename Operation> 2706 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2707 const APSInt &LHS, const APSInt &RHS, 2708 unsigned BitWidth, Operation Op, 2709 APSInt &Result) { 2710 if (LHS.isUnsigned()) { 2711 Result = Op(LHS, RHS); 2712 return true; 2713 } 2714 2715 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2716 Result = Value.trunc(LHS.getBitWidth()); 2717 if (Result.extend(BitWidth) != Value) { 2718 if (Info.checkingForUndefinedBehavior()) 2719 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2720 diag::warn_integer_constant_overflow) 2721 << toString(Result, 10) << E->getType(); 2722 return HandleOverflow(Info, E, Value, E->getType()); 2723 } 2724 return true; 2725 } 2726 2727 /// Perform the given binary integer operation. 2728 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2729 BinaryOperatorKind Opcode, APSInt RHS, 2730 APSInt &Result) { 2731 switch (Opcode) { 2732 default: 2733 Info.FFDiag(E); 2734 return false; 2735 case BO_Mul: 2736 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2737 std::multiplies<APSInt>(), Result); 2738 case BO_Add: 2739 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2740 std::plus<APSInt>(), Result); 2741 case BO_Sub: 2742 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2743 std::minus<APSInt>(), Result); 2744 case BO_And: Result = LHS & RHS; return true; 2745 case BO_Xor: Result = LHS ^ RHS; return true; 2746 case BO_Or: Result = LHS | RHS; return true; 2747 case BO_Div: 2748 case BO_Rem: 2749 if (RHS == 0) { 2750 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2751 return false; 2752 } 2753 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2754 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2755 // this operation and gives the two's complement result. 2756 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2757 LHS.isMinSignedValue()) 2758 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2759 E->getType()); 2760 return true; 2761 case BO_Shl: { 2762 if (Info.getLangOpts().OpenCL) 2763 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2764 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2765 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2766 RHS.isUnsigned()); 2767 else if (RHS.isSigned() && RHS.isNegative()) { 2768 // During constant-folding, a negative shift is an opposite shift. Such 2769 // a shift is not a constant expression. 2770 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2771 RHS = -RHS; 2772 goto shift_right; 2773 } 2774 shift_left: 2775 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2776 // the shifted type. 2777 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2778 if (SA != RHS) { 2779 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2780 << RHS << E->getType() << LHS.getBitWidth(); 2781 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2782 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2783 // operand, and must not overflow the corresponding unsigned type. 2784 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2785 // E1 x 2^E2 module 2^N. 2786 if (LHS.isNegative()) 2787 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2788 else if (LHS.countLeadingZeros() < SA) 2789 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2790 } 2791 Result = LHS << SA; 2792 return true; 2793 } 2794 case BO_Shr: { 2795 if (Info.getLangOpts().OpenCL) 2796 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2797 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2798 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2799 RHS.isUnsigned()); 2800 else if (RHS.isSigned() && RHS.isNegative()) { 2801 // During constant-folding, a negative shift is an opposite shift. Such a 2802 // shift is not a constant expression. 2803 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2804 RHS = -RHS; 2805 goto shift_left; 2806 } 2807 shift_right: 2808 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2809 // shifted type. 2810 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2811 if (SA != RHS) 2812 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2813 << RHS << E->getType() << LHS.getBitWidth(); 2814 Result = LHS >> SA; 2815 return true; 2816 } 2817 2818 case BO_LT: Result = LHS < RHS; return true; 2819 case BO_GT: Result = LHS > RHS; return true; 2820 case BO_LE: Result = LHS <= RHS; return true; 2821 case BO_GE: Result = LHS >= RHS; return true; 2822 case BO_EQ: Result = LHS == RHS; return true; 2823 case BO_NE: Result = LHS != RHS; return true; 2824 case BO_Cmp: 2825 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2826 } 2827 } 2828 2829 /// Perform the given binary floating-point operation, in-place, on LHS. 2830 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2831 APFloat &LHS, BinaryOperatorKind Opcode, 2832 const APFloat &RHS) { 2833 bool DynamicRM; 2834 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2835 APFloat::opStatus St; 2836 switch (Opcode) { 2837 default: 2838 Info.FFDiag(E); 2839 return false; 2840 case BO_Mul: 2841 St = LHS.multiply(RHS, RM); 2842 break; 2843 case BO_Add: 2844 St = LHS.add(RHS, RM); 2845 break; 2846 case BO_Sub: 2847 St = LHS.subtract(RHS, RM); 2848 break; 2849 case BO_Div: 2850 // [expr.mul]p4: 2851 // If the second operand of / or % is zero the behavior is undefined. 2852 if (RHS.isZero()) 2853 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2854 St = LHS.divide(RHS, RM); 2855 break; 2856 } 2857 2858 // [expr.pre]p4: 2859 // If during the evaluation of an expression, the result is not 2860 // mathematically defined [...], the behavior is undefined. 2861 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2862 if (LHS.isNaN()) { 2863 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2864 return Info.noteUndefinedBehavior(); 2865 } 2866 2867 return checkFloatingPointResult(Info, E, St); 2868 } 2869 2870 static bool handleLogicalOpForVector(const APInt &LHSValue, 2871 BinaryOperatorKind Opcode, 2872 const APInt &RHSValue, APInt &Result) { 2873 bool LHS = (LHSValue != 0); 2874 bool RHS = (RHSValue != 0); 2875 2876 if (Opcode == BO_LAnd) 2877 Result = LHS && RHS; 2878 else 2879 Result = LHS || RHS; 2880 return true; 2881 } 2882 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2883 BinaryOperatorKind Opcode, 2884 const APFloat &RHSValue, APInt &Result) { 2885 bool LHS = !LHSValue.isZero(); 2886 bool RHS = !RHSValue.isZero(); 2887 2888 if (Opcode == BO_LAnd) 2889 Result = LHS && RHS; 2890 else 2891 Result = LHS || RHS; 2892 return true; 2893 } 2894 2895 static bool handleLogicalOpForVector(const APValue &LHSValue, 2896 BinaryOperatorKind Opcode, 2897 const APValue &RHSValue, APInt &Result) { 2898 // The result is always an int type, however operands match the first. 2899 if (LHSValue.getKind() == APValue::Int) 2900 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2901 RHSValue.getInt(), Result); 2902 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2903 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2904 RHSValue.getFloat(), Result); 2905 } 2906 2907 template <typename APTy> 2908 static bool 2909 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2910 const APTy &RHSValue, APInt &Result) { 2911 switch (Opcode) { 2912 default: 2913 llvm_unreachable("unsupported binary operator"); 2914 case BO_EQ: 2915 Result = (LHSValue == RHSValue); 2916 break; 2917 case BO_NE: 2918 Result = (LHSValue != RHSValue); 2919 break; 2920 case BO_LT: 2921 Result = (LHSValue < RHSValue); 2922 break; 2923 case BO_GT: 2924 Result = (LHSValue > RHSValue); 2925 break; 2926 case BO_LE: 2927 Result = (LHSValue <= RHSValue); 2928 break; 2929 case BO_GE: 2930 Result = (LHSValue >= RHSValue); 2931 break; 2932 } 2933 2934 return true; 2935 } 2936 2937 static bool handleCompareOpForVector(const APValue &LHSValue, 2938 BinaryOperatorKind Opcode, 2939 const APValue &RHSValue, APInt &Result) { 2940 // The result is always an int type, however operands match the first. 2941 if (LHSValue.getKind() == APValue::Int) 2942 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2943 RHSValue.getInt(), Result); 2944 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2945 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2946 RHSValue.getFloat(), Result); 2947 } 2948 2949 // Perform binary operations for vector types, in place on the LHS. 2950 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2951 BinaryOperatorKind Opcode, 2952 APValue &LHSValue, 2953 const APValue &RHSValue) { 2954 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2955 "Operation not supported on vector types"); 2956 2957 const auto *VT = E->getType()->castAs<VectorType>(); 2958 unsigned NumElements = VT->getNumElements(); 2959 QualType EltTy = VT->getElementType(); 2960 2961 // In the cases (typically C as I've observed) where we aren't evaluating 2962 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2963 // just give up. 2964 if (!LHSValue.isVector()) { 2965 assert(LHSValue.isLValue() && 2966 "A vector result that isn't a vector OR uncalculated LValue"); 2967 Info.FFDiag(E); 2968 return false; 2969 } 2970 2971 assert(LHSValue.getVectorLength() == NumElements && 2972 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2973 2974 SmallVector<APValue, 4> ResultElements; 2975 2976 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2977 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2978 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2979 2980 if (EltTy->isIntegerType()) { 2981 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2982 EltTy->isUnsignedIntegerType()}; 2983 bool Success = true; 2984 2985 if (BinaryOperator::isLogicalOp(Opcode)) 2986 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2987 else if (BinaryOperator::isComparisonOp(Opcode)) 2988 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2989 else 2990 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2991 RHSElt.getInt(), EltResult); 2992 2993 if (!Success) { 2994 Info.FFDiag(E); 2995 return false; 2996 } 2997 ResultElements.emplace_back(EltResult); 2998 2999 } else if (EltTy->isFloatingType()) { 3000 assert(LHSElt.getKind() == APValue::Float && 3001 RHSElt.getKind() == APValue::Float && 3002 "Mismatched LHS/RHS/Result Type"); 3003 APFloat LHSFloat = LHSElt.getFloat(); 3004 3005 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3006 RHSElt.getFloat())) { 3007 Info.FFDiag(E); 3008 return false; 3009 } 3010 3011 ResultElements.emplace_back(LHSFloat); 3012 } 3013 } 3014 3015 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3016 return true; 3017 } 3018 3019 /// Cast an lvalue referring to a base subobject to a derived class, by 3020 /// truncating the lvalue's path to the given length. 3021 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3022 const RecordDecl *TruncatedType, 3023 unsigned TruncatedElements) { 3024 SubobjectDesignator &D = Result.Designator; 3025 3026 // Check we actually point to a derived class object. 3027 if (TruncatedElements == D.Entries.size()) 3028 return true; 3029 assert(TruncatedElements >= D.MostDerivedPathLength && 3030 "not casting to a derived class"); 3031 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3032 return false; 3033 3034 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3035 const RecordDecl *RD = TruncatedType; 3036 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3037 if (RD->isInvalidDecl()) return false; 3038 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3039 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3040 if (isVirtualBaseClass(D.Entries[I])) 3041 Result.Offset -= Layout.getVBaseClassOffset(Base); 3042 else 3043 Result.Offset -= Layout.getBaseClassOffset(Base); 3044 RD = Base; 3045 } 3046 D.Entries.resize(TruncatedElements); 3047 return true; 3048 } 3049 3050 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3051 const CXXRecordDecl *Derived, 3052 const CXXRecordDecl *Base, 3053 const ASTRecordLayout *RL = nullptr) { 3054 if (!RL) { 3055 if (Derived->isInvalidDecl()) return false; 3056 RL = &Info.Ctx.getASTRecordLayout(Derived); 3057 } 3058 3059 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3060 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3061 return true; 3062 } 3063 3064 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3065 const CXXRecordDecl *DerivedDecl, 3066 const CXXBaseSpecifier *Base) { 3067 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3068 3069 if (!Base->isVirtual()) 3070 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3071 3072 SubobjectDesignator &D = Obj.Designator; 3073 if (D.Invalid) 3074 return false; 3075 3076 // Extract most-derived object and corresponding type. 3077 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3078 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3079 return false; 3080 3081 // Find the virtual base class. 3082 if (DerivedDecl->isInvalidDecl()) return false; 3083 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3084 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3085 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3086 return true; 3087 } 3088 3089 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3090 QualType Type, LValue &Result) { 3091 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3092 PathE = E->path_end(); 3093 PathI != PathE; ++PathI) { 3094 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3095 *PathI)) 3096 return false; 3097 Type = (*PathI)->getType(); 3098 } 3099 return true; 3100 } 3101 3102 /// Cast an lvalue referring to a derived class to a known base subobject. 3103 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3104 const CXXRecordDecl *DerivedRD, 3105 const CXXRecordDecl *BaseRD) { 3106 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3107 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3108 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3109 llvm_unreachable("Class must be derived from the passed in base class!"); 3110 3111 for (CXXBasePathElement &Elem : Paths.front()) 3112 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3113 return false; 3114 return true; 3115 } 3116 3117 /// Update LVal to refer to the given field, which must be a member of the type 3118 /// currently described by LVal. 3119 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3120 const FieldDecl *FD, 3121 const ASTRecordLayout *RL = nullptr) { 3122 if (!RL) { 3123 if (FD->getParent()->isInvalidDecl()) return false; 3124 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3125 } 3126 3127 unsigned I = FD->getFieldIndex(); 3128 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3129 LVal.addDecl(Info, E, FD); 3130 return true; 3131 } 3132 3133 /// Update LVal to refer to the given indirect field. 3134 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3135 LValue &LVal, 3136 const IndirectFieldDecl *IFD) { 3137 for (const auto *C : IFD->chain()) 3138 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3139 return false; 3140 return true; 3141 } 3142 3143 /// Get the size of the given type in char units. 3144 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3145 QualType Type, CharUnits &Size) { 3146 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3147 // extension. 3148 if (Type->isVoidType() || Type->isFunctionType()) { 3149 Size = CharUnits::One(); 3150 return true; 3151 } 3152 3153 if (Type->isDependentType()) { 3154 Info.FFDiag(Loc); 3155 return false; 3156 } 3157 3158 if (!Type->isConstantSizeType()) { 3159 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3160 // FIXME: Better diagnostic. 3161 Info.FFDiag(Loc); 3162 return false; 3163 } 3164 3165 Size = Info.Ctx.getTypeSizeInChars(Type); 3166 return true; 3167 } 3168 3169 /// Update a pointer value to model pointer arithmetic. 3170 /// \param Info - Information about the ongoing evaluation. 3171 /// \param E - The expression being evaluated, for diagnostic purposes. 3172 /// \param LVal - The pointer value to be updated. 3173 /// \param EltTy - The pointee type represented by LVal. 3174 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3175 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3176 LValue &LVal, QualType EltTy, 3177 APSInt Adjustment) { 3178 CharUnits SizeOfPointee; 3179 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3180 return false; 3181 3182 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3183 return true; 3184 } 3185 3186 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3187 LValue &LVal, QualType EltTy, 3188 int64_t Adjustment) { 3189 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3190 APSInt::get(Adjustment)); 3191 } 3192 3193 /// Update an lvalue to refer to a component of a complex number. 3194 /// \param Info - Information about the ongoing evaluation. 3195 /// \param LVal - The lvalue to be updated. 3196 /// \param EltTy - The complex number's component type. 3197 /// \param Imag - False for the real component, true for the imaginary. 3198 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3199 LValue &LVal, QualType EltTy, 3200 bool Imag) { 3201 if (Imag) { 3202 CharUnits SizeOfComponent; 3203 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3204 return false; 3205 LVal.Offset += SizeOfComponent; 3206 } 3207 LVal.addComplex(Info, E, EltTy, Imag); 3208 return true; 3209 } 3210 3211 /// Try to evaluate the initializer for a variable declaration. 3212 /// 3213 /// \param Info Information about the ongoing evaluation. 3214 /// \param E An expression to be used when printing diagnostics. 3215 /// \param VD The variable whose initializer should be obtained. 3216 /// \param Version The version of the variable within the frame. 3217 /// \param Frame The frame in which the variable was created. Must be null 3218 /// if this variable is not local to the evaluation. 3219 /// \param Result Filled in with a pointer to the value of the variable. 3220 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3221 const VarDecl *VD, CallStackFrame *Frame, 3222 unsigned Version, APValue *&Result) { 3223 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3224 3225 // If this is a local variable, dig out its value. 3226 if (Frame) { 3227 Result = Frame->getTemporary(VD, Version); 3228 if (Result) 3229 return true; 3230 3231 if (!isa<ParmVarDecl>(VD)) { 3232 // Assume variables referenced within a lambda's call operator that were 3233 // not declared within the call operator are captures and during checking 3234 // of a potential constant expression, assume they are unknown constant 3235 // expressions. 3236 assert(isLambdaCallOperator(Frame->Callee) && 3237 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3238 "missing value for local variable"); 3239 if (Info.checkingPotentialConstantExpression()) 3240 return false; 3241 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3242 // still reachable at all? 3243 Info.FFDiag(E->getBeginLoc(), 3244 diag::note_unimplemented_constexpr_lambda_feature_ast) 3245 << "captures not currently allowed"; 3246 return false; 3247 } 3248 } 3249 3250 // If we're currently evaluating the initializer of this declaration, use that 3251 // in-flight value. 3252 if (Info.EvaluatingDecl == Base) { 3253 Result = Info.EvaluatingDeclValue; 3254 return true; 3255 } 3256 3257 if (isa<ParmVarDecl>(VD)) { 3258 // Assume parameters of a potential constant expression are usable in 3259 // constant expressions. 3260 if (!Info.checkingPotentialConstantExpression() || 3261 !Info.CurrentCall->Callee || 3262 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3263 if (Info.getLangOpts().CPlusPlus11) { 3264 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3265 << VD; 3266 NoteLValueLocation(Info, Base); 3267 } else { 3268 Info.FFDiag(E); 3269 } 3270 } 3271 return false; 3272 } 3273 3274 // Dig out the initializer, and use the declaration which it's attached to. 3275 // FIXME: We should eventually check whether the variable has a reachable 3276 // initializing declaration. 3277 const Expr *Init = VD->getAnyInitializer(VD); 3278 if (!Init) { 3279 // Don't diagnose during potential constant expression checking; an 3280 // initializer might be added later. 3281 if (!Info.checkingPotentialConstantExpression()) { 3282 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3283 << VD; 3284 NoteLValueLocation(Info, Base); 3285 } 3286 return false; 3287 } 3288 3289 if (Init->isValueDependent()) { 3290 // The DeclRefExpr is not value-dependent, but the variable it refers to 3291 // has a value-dependent initializer. This should only happen in 3292 // constant-folding cases, where the variable is not actually of a suitable 3293 // type for use in a constant expression (otherwise the DeclRefExpr would 3294 // have been value-dependent too), so diagnose that. 3295 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3296 if (!Info.checkingPotentialConstantExpression()) { 3297 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3298 ? diag::note_constexpr_ltor_non_constexpr 3299 : diag::note_constexpr_ltor_non_integral, 1) 3300 << VD << VD->getType(); 3301 NoteLValueLocation(Info, Base); 3302 } 3303 return false; 3304 } 3305 3306 // Check that we can fold the initializer. In C++, we will have already done 3307 // this in the cases where it matters for conformance. 3308 if (!VD->evaluateValue()) { 3309 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3310 NoteLValueLocation(Info, Base); 3311 return false; 3312 } 3313 3314 // Check that the variable is actually usable in constant expressions. For a 3315 // const integral variable or a reference, we might have a non-constant 3316 // initializer that we can nonetheless evaluate the initializer for. Such 3317 // variables are not usable in constant expressions. In C++98, the 3318 // initializer also syntactically needs to be an ICE. 3319 // 3320 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3321 // expressions here; doing so would regress diagnostics for things like 3322 // reading from a volatile constexpr variable. 3323 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3324 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3325 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3326 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3327 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3328 NoteLValueLocation(Info, Base); 3329 } 3330 3331 // Never use the initializer of a weak variable, not even for constant 3332 // folding. We can't be sure that this is the definition that will be used. 3333 if (VD->isWeak()) { 3334 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3335 NoteLValueLocation(Info, Base); 3336 return false; 3337 } 3338 3339 Result = VD->getEvaluatedValue(); 3340 return true; 3341 } 3342 3343 /// Get the base index of the given base class within an APValue representing 3344 /// the given derived class. 3345 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3346 const CXXRecordDecl *Base) { 3347 Base = Base->getCanonicalDecl(); 3348 unsigned Index = 0; 3349 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3350 E = Derived->bases_end(); I != E; ++I, ++Index) { 3351 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3352 return Index; 3353 } 3354 3355 llvm_unreachable("base class missing from derived class's bases list"); 3356 } 3357 3358 /// Extract the value of a character from a string literal. 3359 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3360 uint64_t Index) { 3361 assert(!isa<SourceLocExpr>(Lit) && 3362 "SourceLocExpr should have already been converted to a StringLiteral"); 3363 3364 // FIXME: Support MakeStringConstant 3365 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3366 std::string Str; 3367 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3368 assert(Index <= Str.size() && "Index too large"); 3369 return APSInt::getUnsigned(Str.c_str()[Index]); 3370 } 3371 3372 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3373 Lit = PE->getFunctionName(); 3374 const StringLiteral *S = cast<StringLiteral>(Lit); 3375 const ConstantArrayType *CAT = 3376 Info.Ctx.getAsConstantArrayType(S->getType()); 3377 assert(CAT && "string literal isn't an array"); 3378 QualType CharType = CAT->getElementType(); 3379 assert(CharType->isIntegerType() && "unexpected character type"); 3380 3381 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3382 CharType->isUnsignedIntegerType()); 3383 if (Index < S->getLength()) 3384 Value = S->getCodeUnit(Index); 3385 return Value; 3386 } 3387 3388 // Expand a string literal into an array of characters. 3389 // 3390 // FIXME: This is inefficient; we should probably introduce something similar 3391 // to the LLVM ConstantDataArray to make this cheaper. 3392 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3393 APValue &Result, 3394 QualType AllocType = QualType()) { 3395 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3396 AllocType.isNull() ? S->getType() : AllocType); 3397 assert(CAT && "string literal isn't an array"); 3398 QualType CharType = CAT->getElementType(); 3399 assert(CharType->isIntegerType() && "unexpected character type"); 3400 3401 unsigned Elts = CAT->getSize().getZExtValue(); 3402 Result = APValue(APValue::UninitArray(), 3403 std::min(S->getLength(), Elts), Elts); 3404 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3405 CharType->isUnsignedIntegerType()); 3406 if (Result.hasArrayFiller()) 3407 Result.getArrayFiller() = APValue(Value); 3408 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3409 Value = S->getCodeUnit(I); 3410 Result.getArrayInitializedElt(I) = APValue(Value); 3411 } 3412 } 3413 3414 // Expand an array so that it has more than Index filled elements. 3415 static void expandArray(APValue &Array, unsigned Index) { 3416 unsigned Size = Array.getArraySize(); 3417 assert(Index < Size); 3418 3419 // Always at least double the number of elements for which we store a value. 3420 unsigned OldElts = Array.getArrayInitializedElts(); 3421 unsigned NewElts = std::max(Index+1, OldElts * 2); 3422 NewElts = std::min(Size, std::max(NewElts, 8u)); 3423 3424 // Copy the data across. 3425 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3426 for (unsigned I = 0; I != OldElts; ++I) 3427 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3428 for (unsigned I = OldElts; I != NewElts; ++I) 3429 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3430 if (NewValue.hasArrayFiller()) 3431 NewValue.getArrayFiller() = Array.getArrayFiller(); 3432 Array.swap(NewValue); 3433 } 3434 3435 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3436 /// conversion. If it's of class type, we may assume that the copy operation 3437 /// is trivial. Note that this is never true for a union type with fields 3438 /// (because the copy always "reads" the active member) and always true for 3439 /// a non-class type. 3440 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3441 static bool isReadByLvalueToRvalueConversion(QualType T) { 3442 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3443 return !RD || isReadByLvalueToRvalueConversion(RD); 3444 } 3445 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3446 // FIXME: A trivial copy of a union copies the object representation, even if 3447 // the union is empty. 3448 if (RD->isUnion()) 3449 return !RD->field_empty(); 3450 if (RD->isEmpty()) 3451 return false; 3452 3453 for (auto *Field : RD->fields()) 3454 if (!Field->isUnnamedBitfield() && 3455 isReadByLvalueToRvalueConversion(Field->getType())) 3456 return true; 3457 3458 for (auto &BaseSpec : RD->bases()) 3459 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3460 return true; 3461 3462 return false; 3463 } 3464 3465 /// Diagnose an attempt to read from any unreadable field within the specified 3466 /// type, which might be a class type. 3467 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3468 QualType T) { 3469 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3470 if (!RD) 3471 return false; 3472 3473 if (!RD->hasMutableFields()) 3474 return false; 3475 3476 for (auto *Field : RD->fields()) { 3477 // If we're actually going to read this field in some way, then it can't 3478 // be mutable. If we're in a union, then assigning to a mutable field 3479 // (even an empty one) can change the active member, so that's not OK. 3480 // FIXME: Add core issue number for the union case. 3481 if (Field->isMutable() && 3482 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3483 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3484 Info.Note(Field->getLocation(), diag::note_declared_at); 3485 return true; 3486 } 3487 3488 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3489 return true; 3490 } 3491 3492 for (auto &BaseSpec : RD->bases()) 3493 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3494 return true; 3495 3496 // All mutable fields were empty, and thus not actually read. 3497 return false; 3498 } 3499 3500 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3501 APValue::LValueBase Base, 3502 bool MutableSubobject = false) { 3503 // A temporary or transient heap allocation we created. 3504 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3505 return true; 3506 3507 switch (Info.IsEvaluatingDecl) { 3508 case EvalInfo::EvaluatingDeclKind::None: 3509 return false; 3510 3511 case EvalInfo::EvaluatingDeclKind::Ctor: 3512 // The variable whose initializer we're evaluating. 3513 if (Info.EvaluatingDecl == Base) 3514 return true; 3515 3516 // A temporary lifetime-extended by the variable whose initializer we're 3517 // evaluating. 3518 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3519 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3520 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3521 return false; 3522 3523 case EvalInfo::EvaluatingDeclKind::Dtor: 3524 // C++2a [expr.const]p6: 3525 // [during constant destruction] the lifetime of a and its non-mutable 3526 // subobjects (but not its mutable subobjects) [are] considered to start 3527 // within e. 3528 if (MutableSubobject || Base != Info.EvaluatingDecl) 3529 return false; 3530 // FIXME: We can meaningfully extend this to cover non-const objects, but 3531 // we will need special handling: we should be able to access only 3532 // subobjects of such objects that are themselves declared const. 3533 QualType T = getType(Base); 3534 return T.isConstQualified() || T->isReferenceType(); 3535 } 3536 3537 llvm_unreachable("unknown evaluating decl kind"); 3538 } 3539 3540 namespace { 3541 /// A handle to a complete object (an object that is not a subobject of 3542 /// another object). 3543 struct CompleteObject { 3544 /// The identity of the object. 3545 APValue::LValueBase Base; 3546 /// The value of the complete object. 3547 APValue *Value; 3548 /// The type of the complete object. 3549 QualType Type; 3550 3551 CompleteObject() : Value(nullptr) {} 3552 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3553 : Base(Base), Value(Value), Type(Type) {} 3554 3555 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3556 // If this isn't a "real" access (eg, if it's just accessing the type 3557 // info), allow it. We assume the type doesn't change dynamically for 3558 // subobjects of constexpr objects (even though we'd hit UB here if it 3559 // did). FIXME: Is this right? 3560 if (!isAnyAccess(AK)) 3561 return true; 3562 3563 // In C++14 onwards, it is permitted to read a mutable member whose 3564 // lifetime began within the evaluation. 3565 // FIXME: Should we also allow this in C++11? 3566 if (!Info.getLangOpts().CPlusPlus14) 3567 return false; 3568 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3569 } 3570 3571 explicit operator bool() const { return !Type.isNull(); } 3572 }; 3573 } // end anonymous namespace 3574 3575 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3576 bool IsMutable = false) { 3577 // C++ [basic.type.qualifier]p1: 3578 // - A const object is an object of type const T or a non-mutable subobject 3579 // of a const object. 3580 if (ObjType.isConstQualified() && !IsMutable) 3581 SubobjType.addConst(); 3582 // - A volatile object is an object of type const T or a subobject of a 3583 // volatile object. 3584 if (ObjType.isVolatileQualified()) 3585 SubobjType.addVolatile(); 3586 return SubobjType; 3587 } 3588 3589 /// Find the designated sub-object of an rvalue. 3590 template<typename SubobjectHandler> 3591 typename SubobjectHandler::result_type 3592 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3593 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3594 if (Sub.Invalid) 3595 // A diagnostic will have already been produced. 3596 return handler.failed(); 3597 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3598 if (Info.getLangOpts().CPlusPlus11) 3599 Info.FFDiag(E, Sub.isOnePastTheEnd() 3600 ? diag::note_constexpr_access_past_end 3601 : diag::note_constexpr_access_unsized_array) 3602 << handler.AccessKind; 3603 else 3604 Info.FFDiag(E); 3605 return handler.failed(); 3606 } 3607 3608 APValue *O = Obj.Value; 3609 QualType ObjType = Obj.Type; 3610 const FieldDecl *LastField = nullptr; 3611 const FieldDecl *VolatileField = nullptr; 3612 3613 // Walk the designator's path to find the subobject. 3614 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3615 // Reading an indeterminate value is undefined, but assigning over one is OK. 3616 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3617 (O->isIndeterminate() && 3618 !isValidIndeterminateAccess(handler.AccessKind))) { 3619 if (!Info.checkingPotentialConstantExpression()) 3620 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3621 << handler.AccessKind << O->isIndeterminate(); 3622 return handler.failed(); 3623 } 3624 3625 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3626 // const and volatile semantics are not applied on an object under 3627 // {con,de}struction. 3628 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3629 ObjType->isRecordType() && 3630 Info.isEvaluatingCtorDtor( 3631 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3632 Sub.Entries.begin() + I)) != 3633 ConstructionPhase::None) { 3634 ObjType = Info.Ctx.getCanonicalType(ObjType); 3635 ObjType.removeLocalConst(); 3636 ObjType.removeLocalVolatile(); 3637 } 3638 3639 // If this is our last pass, check that the final object type is OK. 3640 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3641 // Accesses to volatile objects are prohibited. 3642 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3643 if (Info.getLangOpts().CPlusPlus) { 3644 int DiagKind; 3645 SourceLocation Loc; 3646 const NamedDecl *Decl = nullptr; 3647 if (VolatileField) { 3648 DiagKind = 2; 3649 Loc = VolatileField->getLocation(); 3650 Decl = VolatileField; 3651 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3652 DiagKind = 1; 3653 Loc = VD->getLocation(); 3654 Decl = VD; 3655 } else { 3656 DiagKind = 0; 3657 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3658 Loc = E->getExprLoc(); 3659 } 3660 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3661 << handler.AccessKind << DiagKind << Decl; 3662 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3663 } else { 3664 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3665 } 3666 return handler.failed(); 3667 } 3668 3669 // If we are reading an object of class type, there may still be more 3670 // things we need to check: if there are any mutable subobjects, we 3671 // cannot perform this read. (This only happens when performing a trivial 3672 // copy or assignment.) 3673 if (ObjType->isRecordType() && 3674 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3675 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3676 return handler.failed(); 3677 } 3678 3679 if (I == N) { 3680 if (!handler.found(*O, ObjType)) 3681 return false; 3682 3683 // If we modified a bit-field, truncate it to the right width. 3684 if (isModification(handler.AccessKind) && 3685 LastField && LastField->isBitField() && 3686 !truncateBitfieldValue(Info, E, *O, LastField)) 3687 return false; 3688 3689 return true; 3690 } 3691 3692 LastField = nullptr; 3693 if (ObjType->isArrayType()) { 3694 // Next subobject is an array element. 3695 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3696 assert(CAT && "vla in literal type?"); 3697 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3698 if (CAT->getSize().ule(Index)) { 3699 // Note, it should not be possible to form a pointer with a valid 3700 // designator which points more than one past the end of the array. 3701 if (Info.getLangOpts().CPlusPlus11) 3702 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3703 << handler.AccessKind; 3704 else 3705 Info.FFDiag(E); 3706 return handler.failed(); 3707 } 3708 3709 ObjType = CAT->getElementType(); 3710 3711 if (O->getArrayInitializedElts() > Index) 3712 O = &O->getArrayInitializedElt(Index); 3713 else if (!isRead(handler.AccessKind)) { 3714 expandArray(*O, Index); 3715 O = &O->getArrayInitializedElt(Index); 3716 } else 3717 O = &O->getArrayFiller(); 3718 } else if (ObjType->isAnyComplexType()) { 3719 // Next subobject is a complex number. 3720 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3721 if (Index > 1) { 3722 if (Info.getLangOpts().CPlusPlus11) 3723 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3724 << handler.AccessKind; 3725 else 3726 Info.FFDiag(E); 3727 return handler.failed(); 3728 } 3729 3730 ObjType = getSubobjectType( 3731 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3732 3733 assert(I == N - 1 && "extracting subobject of scalar?"); 3734 if (O->isComplexInt()) { 3735 return handler.found(Index ? O->getComplexIntImag() 3736 : O->getComplexIntReal(), ObjType); 3737 } else { 3738 assert(O->isComplexFloat()); 3739 return handler.found(Index ? O->getComplexFloatImag() 3740 : O->getComplexFloatReal(), ObjType); 3741 } 3742 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3743 if (Field->isMutable() && 3744 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3745 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3746 << handler.AccessKind << Field; 3747 Info.Note(Field->getLocation(), diag::note_declared_at); 3748 return handler.failed(); 3749 } 3750 3751 // Next subobject is a class, struct or union field. 3752 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3753 if (RD->isUnion()) { 3754 const FieldDecl *UnionField = O->getUnionField(); 3755 if (!UnionField || 3756 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3757 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3758 // Placement new onto an inactive union member makes it active. 3759 O->setUnion(Field, APValue()); 3760 } else { 3761 // FIXME: If O->getUnionValue() is absent, report that there's no 3762 // active union member rather than reporting the prior active union 3763 // member. We'll need to fix nullptr_t to not use APValue() as its 3764 // representation first. 3765 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3766 << handler.AccessKind << Field << !UnionField << UnionField; 3767 return handler.failed(); 3768 } 3769 } 3770 O = &O->getUnionValue(); 3771 } else 3772 O = &O->getStructField(Field->getFieldIndex()); 3773 3774 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3775 LastField = Field; 3776 if (Field->getType().isVolatileQualified()) 3777 VolatileField = Field; 3778 } else { 3779 // Next subobject is a base class. 3780 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3781 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3782 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3783 3784 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3785 } 3786 } 3787 } 3788 3789 namespace { 3790 struct ExtractSubobjectHandler { 3791 EvalInfo &Info; 3792 const Expr *E; 3793 APValue &Result; 3794 const AccessKinds AccessKind; 3795 3796 typedef bool result_type; 3797 bool failed() { return false; } 3798 bool found(APValue &Subobj, QualType SubobjType) { 3799 Result = Subobj; 3800 if (AccessKind == AK_ReadObjectRepresentation) 3801 return true; 3802 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3803 } 3804 bool found(APSInt &Value, QualType SubobjType) { 3805 Result = APValue(Value); 3806 return true; 3807 } 3808 bool found(APFloat &Value, QualType SubobjType) { 3809 Result = APValue(Value); 3810 return true; 3811 } 3812 }; 3813 } // end anonymous namespace 3814 3815 /// Extract the designated sub-object of an rvalue. 3816 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3817 const CompleteObject &Obj, 3818 const SubobjectDesignator &Sub, APValue &Result, 3819 AccessKinds AK = AK_Read) { 3820 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3821 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3822 return findSubobject(Info, E, Obj, Sub, Handler); 3823 } 3824 3825 namespace { 3826 struct ModifySubobjectHandler { 3827 EvalInfo &Info; 3828 APValue &NewVal; 3829 const Expr *E; 3830 3831 typedef bool result_type; 3832 static const AccessKinds AccessKind = AK_Assign; 3833 3834 bool checkConst(QualType QT) { 3835 // Assigning to a const object has undefined behavior. 3836 if (QT.isConstQualified()) { 3837 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3838 return false; 3839 } 3840 return true; 3841 } 3842 3843 bool failed() { return false; } 3844 bool found(APValue &Subobj, QualType SubobjType) { 3845 if (!checkConst(SubobjType)) 3846 return false; 3847 // We've been given ownership of NewVal, so just swap it in. 3848 Subobj.swap(NewVal); 3849 return true; 3850 } 3851 bool found(APSInt &Value, QualType SubobjType) { 3852 if (!checkConst(SubobjType)) 3853 return false; 3854 if (!NewVal.isInt()) { 3855 // Maybe trying to write a cast pointer value into a complex? 3856 Info.FFDiag(E); 3857 return false; 3858 } 3859 Value = NewVal.getInt(); 3860 return true; 3861 } 3862 bool found(APFloat &Value, QualType SubobjType) { 3863 if (!checkConst(SubobjType)) 3864 return false; 3865 Value = NewVal.getFloat(); 3866 return true; 3867 } 3868 }; 3869 } // end anonymous namespace 3870 3871 const AccessKinds ModifySubobjectHandler::AccessKind; 3872 3873 /// Update the designated sub-object of an rvalue to the given value. 3874 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3875 const CompleteObject &Obj, 3876 const SubobjectDesignator &Sub, 3877 APValue &NewVal) { 3878 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3879 return findSubobject(Info, E, Obj, Sub, Handler); 3880 } 3881 3882 /// Find the position where two subobject designators diverge, or equivalently 3883 /// the length of the common initial subsequence. 3884 static unsigned FindDesignatorMismatch(QualType ObjType, 3885 const SubobjectDesignator &A, 3886 const SubobjectDesignator &B, 3887 bool &WasArrayIndex) { 3888 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3889 for (/**/; I != N; ++I) { 3890 if (!ObjType.isNull() && 3891 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3892 // Next subobject is an array element. 3893 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3894 WasArrayIndex = true; 3895 return I; 3896 } 3897 if (ObjType->isAnyComplexType()) 3898 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3899 else 3900 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3901 } else { 3902 if (A.Entries[I].getAsBaseOrMember() != 3903 B.Entries[I].getAsBaseOrMember()) { 3904 WasArrayIndex = false; 3905 return I; 3906 } 3907 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3908 // Next subobject is a field. 3909 ObjType = FD->getType(); 3910 else 3911 // Next subobject is a base class. 3912 ObjType = QualType(); 3913 } 3914 } 3915 WasArrayIndex = false; 3916 return I; 3917 } 3918 3919 /// Determine whether the given subobject designators refer to elements of the 3920 /// same array object. 3921 static bool AreElementsOfSameArray(QualType ObjType, 3922 const SubobjectDesignator &A, 3923 const SubobjectDesignator &B) { 3924 if (A.Entries.size() != B.Entries.size()) 3925 return false; 3926 3927 bool IsArray = A.MostDerivedIsArrayElement; 3928 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3929 // A is a subobject of the array element. 3930 return false; 3931 3932 // If A (and B) designates an array element, the last entry will be the array 3933 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3934 // of length 1' case, and the entire path must match. 3935 bool WasArrayIndex; 3936 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3937 return CommonLength >= A.Entries.size() - IsArray; 3938 } 3939 3940 /// Find the complete object to which an LValue refers. 3941 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3942 AccessKinds AK, const LValue &LVal, 3943 QualType LValType) { 3944 if (LVal.InvalidBase) { 3945 Info.FFDiag(E); 3946 return CompleteObject(); 3947 } 3948 3949 if (!LVal.Base) { 3950 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3951 return CompleteObject(); 3952 } 3953 3954 CallStackFrame *Frame = nullptr; 3955 unsigned Depth = 0; 3956 if (LVal.getLValueCallIndex()) { 3957 std::tie(Frame, Depth) = 3958 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3959 if (!Frame) { 3960 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3961 << AK << LVal.Base.is<const ValueDecl*>(); 3962 NoteLValueLocation(Info, LVal.Base); 3963 return CompleteObject(); 3964 } 3965 } 3966 3967 bool IsAccess = isAnyAccess(AK); 3968 3969 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3970 // is not a constant expression (even if the object is non-volatile). We also 3971 // apply this rule to C++98, in order to conform to the expected 'volatile' 3972 // semantics. 3973 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3974 if (Info.getLangOpts().CPlusPlus) 3975 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3976 << AK << LValType; 3977 else 3978 Info.FFDiag(E); 3979 return CompleteObject(); 3980 } 3981 3982 // Compute value storage location and type of base object. 3983 APValue *BaseVal = nullptr; 3984 QualType BaseType = getType(LVal.Base); 3985 3986 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3987 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3988 // This is the object whose initializer we're evaluating, so its lifetime 3989 // started in the current evaluation. 3990 BaseVal = Info.EvaluatingDeclValue; 3991 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3992 // Allow reading from a GUID declaration. 3993 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3994 if (isModification(AK)) { 3995 // All the remaining cases do not permit modification of the object. 3996 Info.FFDiag(E, diag::note_constexpr_modify_global); 3997 return CompleteObject(); 3998 } 3999 APValue &V = GD->getAsAPValue(); 4000 if (V.isAbsent()) { 4001 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4002 << GD->getType(); 4003 return CompleteObject(); 4004 } 4005 return CompleteObject(LVal.Base, &V, GD->getType()); 4006 } 4007 4008 // Allow reading from template parameter objects. 4009 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4010 if (isModification(AK)) { 4011 Info.FFDiag(E, diag::note_constexpr_modify_global); 4012 return CompleteObject(); 4013 } 4014 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4015 TPO->getType()); 4016 } 4017 4018 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4019 // In C++11, constexpr, non-volatile variables initialized with constant 4020 // expressions are constant expressions too. Inside constexpr functions, 4021 // parameters are constant expressions even if they're non-const. 4022 // In C++1y, objects local to a constant expression (those with a Frame) are 4023 // both readable and writable inside constant expressions. 4024 // In C, such things can also be folded, although they are not ICEs. 4025 const VarDecl *VD = dyn_cast<VarDecl>(D); 4026 if (VD) { 4027 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4028 VD = VDef; 4029 } 4030 if (!VD || VD->isInvalidDecl()) { 4031 Info.FFDiag(E); 4032 return CompleteObject(); 4033 } 4034 4035 bool IsConstant = BaseType.isConstant(Info.Ctx); 4036 4037 // Unless we're looking at a local variable or argument in a constexpr call, 4038 // the variable we're reading must be const. 4039 if (!Frame) { 4040 if (IsAccess && isa<ParmVarDecl>(VD)) { 4041 // Access of a parameter that's not associated with a frame isn't going 4042 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4043 // suitable diagnostic. 4044 } else if (Info.getLangOpts().CPlusPlus14 && 4045 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4046 // OK, we can read and modify an object if we're in the process of 4047 // evaluating its initializer, because its lifetime began in this 4048 // evaluation. 4049 } else if (isModification(AK)) { 4050 // All the remaining cases do not permit modification of the object. 4051 Info.FFDiag(E, diag::note_constexpr_modify_global); 4052 return CompleteObject(); 4053 } else if (VD->isConstexpr()) { 4054 // OK, we can read this variable. 4055 } else if (BaseType->isIntegralOrEnumerationType()) { 4056 if (!IsConstant) { 4057 if (!IsAccess) 4058 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4059 if (Info.getLangOpts().CPlusPlus) { 4060 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4061 Info.Note(VD->getLocation(), diag::note_declared_at); 4062 } else { 4063 Info.FFDiag(E); 4064 } 4065 return CompleteObject(); 4066 } 4067 } else if (!IsAccess) { 4068 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4069 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4070 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4071 // This variable might end up being constexpr. Don't diagnose it yet. 4072 } else if (IsConstant) { 4073 // Keep evaluating to see what we can do. In particular, we support 4074 // folding of const floating-point types, in order to make static const 4075 // data members of such types (supported as an extension) more useful. 4076 if (Info.getLangOpts().CPlusPlus) { 4077 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4078 ? diag::note_constexpr_ltor_non_constexpr 4079 : diag::note_constexpr_ltor_non_integral, 1) 4080 << VD << BaseType; 4081 Info.Note(VD->getLocation(), diag::note_declared_at); 4082 } else { 4083 Info.CCEDiag(E); 4084 } 4085 } else { 4086 // Never allow reading a non-const value. 4087 if (Info.getLangOpts().CPlusPlus) { 4088 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4089 ? diag::note_constexpr_ltor_non_constexpr 4090 : diag::note_constexpr_ltor_non_integral, 1) 4091 << VD << BaseType; 4092 Info.Note(VD->getLocation(), diag::note_declared_at); 4093 } else { 4094 Info.FFDiag(E); 4095 } 4096 return CompleteObject(); 4097 } 4098 } 4099 4100 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4101 return CompleteObject(); 4102 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4103 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4104 if (!Alloc) { 4105 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4106 return CompleteObject(); 4107 } 4108 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4109 LVal.Base.getDynamicAllocType()); 4110 } else { 4111 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4112 4113 if (!Frame) { 4114 if (const MaterializeTemporaryExpr *MTE = 4115 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4116 assert(MTE->getStorageDuration() == SD_Static && 4117 "should have a frame for a non-global materialized temporary"); 4118 4119 // C++20 [expr.const]p4: [DR2126] 4120 // An object or reference is usable in constant expressions if it is 4121 // - a temporary object of non-volatile const-qualified literal type 4122 // whose lifetime is extended to that of a variable that is usable 4123 // in constant expressions 4124 // 4125 // C++20 [expr.const]p5: 4126 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4127 // - a non-volatile glvalue that refers to an object that is usable 4128 // in constant expressions, or 4129 // - a non-volatile glvalue of literal type that refers to a 4130 // non-volatile object whose lifetime began within the evaluation 4131 // of E; 4132 // 4133 // C++11 misses the 'began within the evaluation of e' check and 4134 // instead allows all temporaries, including things like: 4135 // int &&r = 1; 4136 // int x = ++r; 4137 // constexpr int k = r; 4138 // Therefore we use the C++14-onwards rules in C++11 too. 4139 // 4140 // Note that temporaries whose lifetimes began while evaluating a 4141 // variable's constructor are not usable while evaluating the 4142 // corresponding destructor, not even if they're of const-qualified 4143 // types. 4144 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4145 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4146 if (!IsAccess) 4147 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4148 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4149 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4150 return CompleteObject(); 4151 } 4152 4153 BaseVal = MTE->getOrCreateValue(false); 4154 assert(BaseVal && "got reference to unevaluated temporary"); 4155 } else { 4156 if (!IsAccess) 4157 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4158 APValue Val; 4159 LVal.moveInto(Val); 4160 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4161 << AK 4162 << Val.getAsString(Info.Ctx, 4163 Info.Ctx.getLValueReferenceType(LValType)); 4164 NoteLValueLocation(Info, LVal.Base); 4165 return CompleteObject(); 4166 } 4167 } else { 4168 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4169 assert(BaseVal && "missing value for temporary"); 4170 } 4171 } 4172 4173 // In C++14, we can't safely access any mutable state when we might be 4174 // evaluating after an unmodeled side effect. Parameters are modeled as state 4175 // in the caller, but aren't visible once the call returns, so they can be 4176 // modified in a speculatively-evaluated call. 4177 // 4178 // FIXME: Not all local state is mutable. Allow local constant subobjects 4179 // to be read here (but take care with 'mutable' fields). 4180 unsigned VisibleDepth = Depth; 4181 if (llvm::isa_and_nonnull<ParmVarDecl>( 4182 LVal.Base.dyn_cast<const ValueDecl *>())) 4183 ++VisibleDepth; 4184 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4185 Info.EvalStatus.HasSideEffects) || 4186 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4187 return CompleteObject(); 4188 4189 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4190 } 4191 4192 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4193 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4194 /// glvalue referred to by an entity of reference type. 4195 /// 4196 /// \param Info - Information about the ongoing evaluation. 4197 /// \param Conv - The expression for which we are performing the conversion. 4198 /// Used for diagnostics. 4199 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4200 /// case of a non-class type). 4201 /// \param LVal - The glvalue on which we are attempting to perform this action. 4202 /// \param RVal - The produced value will be placed here. 4203 /// \param WantObjectRepresentation - If true, we're looking for the object 4204 /// representation rather than the value, and in particular, 4205 /// there is no requirement that the result be fully initialized. 4206 static bool 4207 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4208 const LValue &LVal, APValue &RVal, 4209 bool WantObjectRepresentation = false) { 4210 if (LVal.Designator.Invalid) 4211 return false; 4212 4213 // Check for special cases where there is no existing APValue to look at. 4214 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4215 4216 AccessKinds AK = 4217 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4218 4219 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4220 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4221 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4222 // initializer until now for such expressions. Such an expression can't be 4223 // an ICE in C, so this only matters for fold. 4224 if (Type.isVolatileQualified()) { 4225 Info.FFDiag(Conv); 4226 return false; 4227 } 4228 APValue Lit; 4229 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4230 return false; 4231 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4232 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4233 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4234 // Special-case character extraction so we don't have to construct an 4235 // APValue for the whole string. 4236 assert(LVal.Designator.Entries.size() <= 1 && 4237 "Can only read characters from string literals"); 4238 if (LVal.Designator.Entries.empty()) { 4239 // Fail for now for LValue to RValue conversion of an array. 4240 // (This shouldn't show up in C/C++, but it could be triggered by a 4241 // weird EvaluateAsRValue call from a tool.) 4242 Info.FFDiag(Conv); 4243 return false; 4244 } 4245 if (LVal.Designator.isOnePastTheEnd()) { 4246 if (Info.getLangOpts().CPlusPlus11) 4247 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4248 else 4249 Info.FFDiag(Conv); 4250 return false; 4251 } 4252 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4253 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4254 return true; 4255 } 4256 } 4257 4258 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4259 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4260 } 4261 4262 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4263 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4264 QualType LValType, APValue &Val) { 4265 if (LVal.Designator.Invalid) 4266 return false; 4267 4268 if (!Info.getLangOpts().CPlusPlus14) { 4269 Info.FFDiag(E); 4270 return false; 4271 } 4272 4273 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4274 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4275 } 4276 4277 namespace { 4278 struct CompoundAssignSubobjectHandler { 4279 EvalInfo &Info; 4280 const CompoundAssignOperator *E; 4281 QualType PromotedLHSType; 4282 BinaryOperatorKind Opcode; 4283 const APValue &RHS; 4284 4285 static const AccessKinds AccessKind = AK_Assign; 4286 4287 typedef bool result_type; 4288 4289 bool checkConst(QualType QT) { 4290 // Assigning to a const object has undefined behavior. 4291 if (QT.isConstQualified()) { 4292 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4293 return false; 4294 } 4295 return true; 4296 } 4297 4298 bool failed() { return false; } 4299 bool found(APValue &Subobj, QualType SubobjType) { 4300 switch (Subobj.getKind()) { 4301 case APValue::Int: 4302 return found(Subobj.getInt(), SubobjType); 4303 case APValue::Float: 4304 return found(Subobj.getFloat(), SubobjType); 4305 case APValue::ComplexInt: 4306 case APValue::ComplexFloat: 4307 // FIXME: Implement complex compound assignment. 4308 Info.FFDiag(E); 4309 return false; 4310 case APValue::LValue: 4311 return foundPointer(Subobj, SubobjType); 4312 case APValue::Vector: 4313 return foundVector(Subobj, SubobjType); 4314 default: 4315 // FIXME: can this happen? 4316 Info.FFDiag(E); 4317 return false; 4318 } 4319 } 4320 4321 bool foundVector(APValue &Value, QualType SubobjType) { 4322 if (!checkConst(SubobjType)) 4323 return false; 4324 4325 if (!SubobjType->isVectorType()) { 4326 Info.FFDiag(E); 4327 return false; 4328 } 4329 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4330 } 4331 4332 bool found(APSInt &Value, QualType SubobjType) { 4333 if (!checkConst(SubobjType)) 4334 return false; 4335 4336 if (!SubobjType->isIntegerType()) { 4337 // We don't support compound assignment on integer-cast-to-pointer 4338 // values. 4339 Info.FFDiag(E); 4340 return false; 4341 } 4342 4343 if (RHS.isInt()) { 4344 APSInt LHS = 4345 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4346 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4347 return false; 4348 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4349 return true; 4350 } else if (RHS.isFloat()) { 4351 const FPOptions FPO = E->getFPFeaturesInEffect( 4352 Info.Ctx.getLangOpts()); 4353 APFloat FValue(0.0); 4354 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4355 PromotedLHSType, FValue) && 4356 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4357 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4358 Value); 4359 } 4360 4361 Info.FFDiag(E); 4362 return false; 4363 } 4364 bool found(APFloat &Value, QualType SubobjType) { 4365 return checkConst(SubobjType) && 4366 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4367 Value) && 4368 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4369 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4370 } 4371 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4372 if (!checkConst(SubobjType)) 4373 return false; 4374 4375 QualType PointeeType; 4376 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4377 PointeeType = PT->getPointeeType(); 4378 4379 if (PointeeType.isNull() || !RHS.isInt() || 4380 (Opcode != BO_Add && Opcode != BO_Sub)) { 4381 Info.FFDiag(E); 4382 return false; 4383 } 4384 4385 APSInt Offset = RHS.getInt(); 4386 if (Opcode == BO_Sub) 4387 negateAsSigned(Offset); 4388 4389 LValue LVal; 4390 LVal.setFrom(Info.Ctx, Subobj); 4391 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4392 return false; 4393 LVal.moveInto(Subobj); 4394 return true; 4395 } 4396 }; 4397 } // end anonymous namespace 4398 4399 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4400 4401 /// Perform a compound assignment of LVal <op>= RVal. 4402 static bool handleCompoundAssignment(EvalInfo &Info, 4403 const CompoundAssignOperator *E, 4404 const LValue &LVal, QualType LValType, 4405 QualType PromotedLValType, 4406 BinaryOperatorKind Opcode, 4407 const APValue &RVal) { 4408 if (LVal.Designator.Invalid) 4409 return false; 4410 4411 if (!Info.getLangOpts().CPlusPlus14) { 4412 Info.FFDiag(E); 4413 return false; 4414 } 4415 4416 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4417 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4418 RVal }; 4419 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4420 } 4421 4422 namespace { 4423 struct IncDecSubobjectHandler { 4424 EvalInfo &Info; 4425 const UnaryOperator *E; 4426 AccessKinds AccessKind; 4427 APValue *Old; 4428 4429 typedef bool result_type; 4430 4431 bool checkConst(QualType QT) { 4432 // Assigning to a const object has undefined behavior. 4433 if (QT.isConstQualified()) { 4434 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4435 return false; 4436 } 4437 return true; 4438 } 4439 4440 bool failed() { return false; } 4441 bool found(APValue &Subobj, QualType SubobjType) { 4442 // Stash the old value. Also clear Old, so we don't clobber it later 4443 // if we're post-incrementing a complex. 4444 if (Old) { 4445 *Old = Subobj; 4446 Old = nullptr; 4447 } 4448 4449 switch (Subobj.getKind()) { 4450 case APValue::Int: 4451 return found(Subobj.getInt(), SubobjType); 4452 case APValue::Float: 4453 return found(Subobj.getFloat(), SubobjType); 4454 case APValue::ComplexInt: 4455 return found(Subobj.getComplexIntReal(), 4456 SubobjType->castAs<ComplexType>()->getElementType() 4457 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4458 case APValue::ComplexFloat: 4459 return found(Subobj.getComplexFloatReal(), 4460 SubobjType->castAs<ComplexType>()->getElementType() 4461 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4462 case APValue::LValue: 4463 return foundPointer(Subobj, SubobjType); 4464 default: 4465 // FIXME: can this happen? 4466 Info.FFDiag(E); 4467 return false; 4468 } 4469 } 4470 bool found(APSInt &Value, QualType SubobjType) { 4471 if (!checkConst(SubobjType)) 4472 return false; 4473 4474 if (!SubobjType->isIntegerType()) { 4475 // We don't support increment / decrement on integer-cast-to-pointer 4476 // values. 4477 Info.FFDiag(E); 4478 return false; 4479 } 4480 4481 if (Old) *Old = APValue(Value); 4482 4483 // bool arithmetic promotes to int, and the conversion back to bool 4484 // doesn't reduce mod 2^n, so special-case it. 4485 if (SubobjType->isBooleanType()) { 4486 if (AccessKind == AK_Increment) 4487 Value = 1; 4488 else 4489 Value = !Value; 4490 return true; 4491 } 4492 4493 bool WasNegative = Value.isNegative(); 4494 if (AccessKind == AK_Increment) { 4495 ++Value; 4496 4497 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4498 APSInt ActualValue(Value, /*IsUnsigned*/true); 4499 return HandleOverflow(Info, E, ActualValue, SubobjType); 4500 } 4501 } else { 4502 --Value; 4503 4504 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4505 unsigned BitWidth = Value.getBitWidth(); 4506 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4507 ActualValue.setBit(BitWidth); 4508 return HandleOverflow(Info, E, ActualValue, SubobjType); 4509 } 4510 } 4511 return true; 4512 } 4513 bool found(APFloat &Value, QualType SubobjType) { 4514 if (!checkConst(SubobjType)) 4515 return false; 4516 4517 if (Old) *Old = APValue(Value); 4518 4519 APFloat One(Value.getSemantics(), 1); 4520 if (AccessKind == AK_Increment) 4521 Value.add(One, APFloat::rmNearestTiesToEven); 4522 else 4523 Value.subtract(One, APFloat::rmNearestTiesToEven); 4524 return true; 4525 } 4526 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4527 if (!checkConst(SubobjType)) 4528 return false; 4529 4530 QualType PointeeType; 4531 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4532 PointeeType = PT->getPointeeType(); 4533 else { 4534 Info.FFDiag(E); 4535 return false; 4536 } 4537 4538 LValue LVal; 4539 LVal.setFrom(Info.Ctx, Subobj); 4540 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4541 AccessKind == AK_Increment ? 1 : -1)) 4542 return false; 4543 LVal.moveInto(Subobj); 4544 return true; 4545 } 4546 }; 4547 } // end anonymous namespace 4548 4549 /// Perform an increment or decrement on LVal. 4550 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4551 QualType LValType, bool IsIncrement, APValue *Old) { 4552 if (LVal.Designator.Invalid) 4553 return false; 4554 4555 if (!Info.getLangOpts().CPlusPlus14) { 4556 Info.FFDiag(E); 4557 return false; 4558 } 4559 4560 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4561 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4562 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4563 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4564 } 4565 4566 /// Build an lvalue for the object argument of a member function call. 4567 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4568 LValue &This) { 4569 if (Object->getType()->isPointerType() && Object->isPRValue()) 4570 return EvaluatePointer(Object, This, Info); 4571 4572 if (Object->isGLValue()) 4573 return EvaluateLValue(Object, This, Info); 4574 4575 if (Object->getType()->isLiteralType(Info.Ctx)) 4576 return EvaluateTemporary(Object, This, Info); 4577 4578 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4579 return false; 4580 } 4581 4582 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4583 /// lvalue referring to the result. 4584 /// 4585 /// \param Info - Information about the ongoing evaluation. 4586 /// \param LV - An lvalue referring to the base of the member pointer. 4587 /// \param RHS - The member pointer expression. 4588 /// \param IncludeMember - Specifies whether the member itself is included in 4589 /// the resulting LValue subobject designator. This is not possible when 4590 /// creating a bound member function. 4591 /// \return The field or method declaration to which the member pointer refers, 4592 /// or 0 if evaluation fails. 4593 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4594 QualType LVType, 4595 LValue &LV, 4596 const Expr *RHS, 4597 bool IncludeMember = true) { 4598 MemberPtr MemPtr; 4599 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4600 return nullptr; 4601 4602 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4603 // member value, the behavior is undefined. 4604 if (!MemPtr.getDecl()) { 4605 // FIXME: Specific diagnostic. 4606 Info.FFDiag(RHS); 4607 return nullptr; 4608 } 4609 4610 if (MemPtr.isDerivedMember()) { 4611 // This is a member of some derived class. Truncate LV appropriately. 4612 // The end of the derived-to-base path for the base object must match the 4613 // derived-to-base path for the member pointer. 4614 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4615 LV.Designator.Entries.size()) { 4616 Info.FFDiag(RHS); 4617 return nullptr; 4618 } 4619 unsigned PathLengthToMember = 4620 LV.Designator.Entries.size() - MemPtr.Path.size(); 4621 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4622 const CXXRecordDecl *LVDecl = getAsBaseClass( 4623 LV.Designator.Entries[PathLengthToMember + I]); 4624 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4625 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4626 Info.FFDiag(RHS); 4627 return nullptr; 4628 } 4629 } 4630 4631 // Truncate the lvalue to the appropriate derived class. 4632 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4633 PathLengthToMember)) 4634 return nullptr; 4635 } else if (!MemPtr.Path.empty()) { 4636 // Extend the LValue path with the member pointer's path. 4637 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4638 MemPtr.Path.size() + IncludeMember); 4639 4640 // Walk down to the appropriate base class. 4641 if (const PointerType *PT = LVType->getAs<PointerType>()) 4642 LVType = PT->getPointeeType(); 4643 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4644 assert(RD && "member pointer access on non-class-type expression"); 4645 // The first class in the path is that of the lvalue. 4646 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4647 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4648 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4649 return nullptr; 4650 RD = Base; 4651 } 4652 // Finally cast to the class containing the member. 4653 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4654 MemPtr.getContainingRecord())) 4655 return nullptr; 4656 } 4657 4658 // Add the member. Note that we cannot build bound member functions here. 4659 if (IncludeMember) { 4660 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4661 if (!HandleLValueMember(Info, RHS, LV, FD)) 4662 return nullptr; 4663 } else if (const IndirectFieldDecl *IFD = 4664 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4665 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4666 return nullptr; 4667 } else { 4668 llvm_unreachable("can't construct reference to bound member function"); 4669 } 4670 } 4671 4672 return MemPtr.getDecl(); 4673 } 4674 4675 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4676 const BinaryOperator *BO, 4677 LValue &LV, 4678 bool IncludeMember = true) { 4679 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4680 4681 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4682 if (Info.noteFailure()) { 4683 MemberPtr MemPtr; 4684 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4685 } 4686 return nullptr; 4687 } 4688 4689 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4690 BO->getRHS(), IncludeMember); 4691 } 4692 4693 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4694 /// the provided lvalue, which currently refers to the base object. 4695 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4696 LValue &Result) { 4697 SubobjectDesignator &D = Result.Designator; 4698 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4699 return false; 4700 4701 QualType TargetQT = E->getType(); 4702 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4703 TargetQT = PT->getPointeeType(); 4704 4705 // Check this cast lands within the final derived-to-base subobject path. 4706 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4707 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4708 << D.MostDerivedType << TargetQT; 4709 return false; 4710 } 4711 4712 // Check the type of the final cast. We don't need to check the path, 4713 // since a cast can only be formed if the path is unique. 4714 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4715 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4716 const CXXRecordDecl *FinalType; 4717 if (NewEntriesSize == D.MostDerivedPathLength) 4718 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4719 else 4720 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4721 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4722 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4723 << D.MostDerivedType << TargetQT; 4724 return false; 4725 } 4726 4727 // Truncate the lvalue to the appropriate derived class. 4728 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4729 } 4730 4731 /// Get the value to use for a default-initialized object of type T. 4732 /// Return false if it encounters something invalid. 4733 static bool getDefaultInitValue(QualType T, APValue &Result) { 4734 bool Success = true; 4735 if (auto *RD = T->getAsCXXRecordDecl()) { 4736 if (RD->isInvalidDecl()) { 4737 Result = APValue(); 4738 return false; 4739 } 4740 if (RD->isUnion()) { 4741 Result = APValue((const FieldDecl *)nullptr); 4742 return true; 4743 } 4744 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4745 std::distance(RD->field_begin(), RD->field_end())); 4746 4747 unsigned Index = 0; 4748 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4749 End = RD->bases_end(); 4750 I != End; ++I, ++Index) 4751 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4752 4753 for (const auto *I : RD->fields()) { 4754 if (I->isUnnamedBitfield()) 4755 continue; 4756 Success &= getDefaultInitValue(I->getType(), 4757 Result.getStructField(I->getFieldIndex())); 4758 } 4759 return Success; 4760 } 4761 4762 if (auto *AT = 4763 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4764 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4765 if (Result.hasArrayFiller()) 4766 Success &= 4767 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4768 4769 return Success; 4770 } 4771 4772 Result = APValue::IndeterminateValue(); 4773 return true; 4774 } 4775 4776 namespace { 4777 enum EvalStmtResult { 4778 /// Evaluation failed. 4779 ESR_Failed, 4780 /// Hit a 'return' statement. 4781 ESR_Returned, 4782 /// Evaluation succeeded. 4783 ESR_Succeeded, 4784 /// Hit a 'continue' statement. 4785 ESR_Continue, 4786 /// Hit a 'break' statement. 4787 ESR_Break, 4788 /// Still scanning for 'case' or 'default' statement. 4789 ESR_CaseNotFound 4790 }; 4791 } 4792 4793 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4794 // We don't need to evaluate the initializer for a static local. 4795 if (!VD->hasLocalStorage()) 4796 return true; 4797 4798 LValue Result; 4799 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4800 ScopeKind::Block, Result); 4801 4802 const Expr *InitE = VD->getInit(); 4803 if (!InitE) { 4804 if (VD->getType()->isDependentType()) 4805 return Info.noteSideEffect(); 4806 return getDefaultInitValue(VD->getType(), Val); 4807 } 4808 if (InitE->isValueDependent()) 4809 return false; 4810 4811 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4812 // Wipe out any partially-computed value, to allow tracking that this 4813 // evaluation failed. 4814 Val = APValue(); 4815 return false; 4816 } 4817 4818 return true; 4819 } 4820 4821 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4822 bool OK = true; 4823 4824 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4825 OK &= EvaluateVarDecl(Info, VD); 4826 4827 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4828 for (auto *BD : DD->bindings()) 4829 if (auto *VD = BD->getHoldingVar()) 4830 OK &= EvaluateDecl(Info, VD); 4831 4832 return OK; 4833 } 4834 4835 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4836 assert(E->isValueDependent()); 4837 if (Info.noteSideEffect()) 4838 return true; 4839 assert(E->containsErrors() && "valid value-dependent expression should never " 4840 "reach invalid code path."); 4841 return false; 4842 } 4843 4844 /// Evaluate a condition (either a variable declaration or an expression). 4845 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4846 const Expr *Cond, bool &Result) { 4847 if (Cond->isValueDependent()) 4848 return false; 4849 FullExpressionRAII Scope(Info); 4850 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4851 return false; 4852 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4853 return false; 4854 return Scope.destroy(); 4855 } 4856 4857 namespace { 4858 /// A location where the result (returned value) of evaluating a 4859 /// statement should be stored. 4860 struct StmtResult { 4861 /// The APValue that should be filled in with the returned value. 4862 APValue &Value; 4863 /// The location containing the result, if any (used to support RVO). 4864 const LValue *Slot; 4865 }; 4866 4867 struct TempVersionRAII { 4868 CallStackFrame &Frame; 4869 4870 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4871 Frame.pushTempVersion(); 4872 } 4873 4874 ~TempVersionRAII() { 4875 Frame.popTempVersion(); 4876 } 4877 }; 4878 4879 } 4880 4881 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4882 const Stmt *S, 4883 const SwitchCase *SC = nullptr); 4884 4885 /// Evaluate the body of a loop, and translate the result as appropriate. 4886 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4887 const Stmt *Body, 4888 const SwitchCase *Case = nullptr) { 4889 BlockScopeRAII Scope(Info); 4890 4891 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4892 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4893 ESR = ESR_Failed; 4894 4895 switch (ESR) { 4896 case ESR_Break: 4897 return ESR_Succeeded; 4898 case ESR_Succeeded: 4899 case ESR_Continue: 4900 return ESR_Continue; 4901 case ESR_Failed: 4902 case ESR_Returned: 4903 case ESR_CaseNotFound: 4904 return ESR; 4905 } 4906 llvm_unreachable("Invalid EvalStmtResult!"); 4907 } 4908 4909 /// Evaluate a switch statement. 4910 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4911 const SwitchStmt *SS) { 4912 BlockScopeRAII Scope(Info); 4913 4914 // Evaluate the switch condition. 4915 APSInt Value; 4916 { 4917 if (const Stmt *Init = SS->getInit()) { 4918 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4919 if (ESR != ESR_Succeeded) { 4920 if (ESR != ESR_Failed && !Scope.destroy()) 4921 ESR = ESR_Failed; 4922 return ESR; 4923 } 4924 } 4925 4926 FullExpressionRAII CondScope(Info); 4927 if (SS->getConditionVariable() && 4928 !EvaluateDecl(Info, SS->getConditionVariable())) 4929 return ESR_Failed; 4930 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4931 return ESR_Failed; 4932 if (!CondScope.destroy()) 4933 return ESR_Failed; 4934 } 4935 4936 // Find the switch case corresponding to the value of the condition. 4937 // FIXME: Cache this lookup. 4938 const SwitchCase *Found = nullptr; 4939 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4940 SC = SC->getNextSwitchCase()) { 4941 if (isa<DefaultStmt>(SC)) { 4942 Found = SC; 4943 continue; 4944 } 4945 4946 const CaseStmt *CS = cast<CaseStmt>(SC); 4947 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4948 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4949 : LHS; 4950 if (LHS <= Value && Value <= RHS) { 4951 Found = SC; 4952 break; 4953 } 4954 } 4955 4956 if (!Found) 4957 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4958 4959 // Search the switch body for the switch case and evaluate it from there. 4960 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4961 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4962 return ESR_Failed; 4963 4964 switch (ESR) { 4965 case ESR_Break: 4966 return ESR_Succeeded; 4967 case ESR_Succeeded: 4968 case ESR_Continue: 4969 case ESR_Failed: 4970 case ESR_Returned: 4971 return ESR; 4972 case ESR_CaseNotFound: 4973 // This can only happen if the switch case is nested within a statement 4974 // expression. We have no intention of supporting that. 4975 Info.FFDiag(Found->getBeginLoc(), 4976 diag::note_constexpr_stmt_expr_unsupported); 4977 return ESR_Failed; 4978 } 4979 llvm_unreachable("Invalid EvalStmtResult!"); 4980 } 4981 4982 // Evaluate a statement. 4983 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4984 const Stmt *S, const SwitchCase *Case) { 4985 if (!Info.nextStep(S)) 4986 return ESR_Failed; 4987 4988 // If we're hunting down a 'case' or 'default' label, recurse through 4989 // substatements until we hit the label. 4990 if (Case) { 4991 switch (S->getStmtClass()) { 4992 case Stmt::CompoundStmtClass: 4993 // FIXME: Precompute which substatement of a compound statement we 4994 // would jump to, and go straight there rather than performing a 4995 // linear scan each time. 4996 case Stmt::LabelStmtClass: 4997 case Stmt::AttributedStmtClass: 4998 case Stmt::DoStmtClass: 4999 break; 5000 5001 case Stmt::CaseStmtClass: 5002 case Stmt::DefaultStmtClass: 5003 if (Case == S) 5004 Case = nullptr; 5005 break; 5006 5007 case Stmt::IfStmtClass: { 5008 // FIXME: Precompute which side of an 'if' we would jump to, and go 5009 // straight there rather than scanning both sides. 5010 const IfStmt *IS = cast<IfStmt>(S); 5011 5012 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5013 // preceded by our switch label. 5014 BlockScopeRAII Scope(Info); 5015 5016 // Step into the init statement in case it brings an (uninitialized) 5017 // variable into scope. 5018 if (const Stmt *Init = IS->getInit()) { 5019 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5020 if (ESR != ESR_CaseNotFound) { 5021 assert(ESR != ESR_Succeeded); 5022 return ESR; 5023 } 5024 } 5025 5026 // Condition variable must be initialized if it exists. 5027 // FIXME: We can skip evaluating the body if there's a condition 5028 // variable, as there can't be any case labels within it. 5029 // (The same is true for 'for' statements.) 5030 5031 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5032 if (ESR == ESR_Failed) 5033 return ESR; 5034 if (ESR != ESR_CaseNotFound) 5035 return Scope.destroy() ? ESR : ESR_Failed; 5036 if (!IS->getElse()) 5037 return ESR_CaseNotFound; 5038 5039 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5040 if (ESR == ESR_Failed) 5041 return ESR; 5042 if (ESR != ESR_CaseNotFound) 5043 return Scope.destroy() ? ESR : ESR_Failed; 5044 return ESR_CaseNotFound; 5045 } 5046 5047 case Stmt::WhileStmtClass: { 5048 EvalStmtResult ESR = 5049 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5050 if (ESR != ESR_Continue) 5051 return ESR; 5052 break; 5053 } 5054 5055 case Stmt::ForStmtClass: { 5056 const ForStmt *FS = cast<ForStmt>(S); 5057 BlockScopeRAII Scope(Info); 5058 5059 // Step into the init statement in case it brings an (uninitialized) 5060 // variable into scope. 5061 if (const Stmt *Init = FS->getInit()) { 5062 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5063 if (ESR != ESR_CaseNotFound) { 5064 assert(ESR != ESR_Succeeded); 5065 return ESR; 5066 } 5067 } 5068 5069 EvalStmtResult ESR = 5070 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5071 if (ESR != ESR_Continue) 5072 return ESR; 5073 if (const auto *Inc = FS->getInc()) { 5074 if (Inc->isValueDependent()) { 5075 if (!EvaluateDependentExpr(Inc, Info)) 5076 return ESR_Failed; 5077 } else { 5078 FullExpressionRAII IncScope(Info); 5079 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5080 return ESR_Failed; 5081 } 5082 } 5083 break; 5084 } 5085 5086 case Stmt::DeclStmtClass: { 5087 // Start the lifetime of any uninitialized variables we encounter. They 5088 // might be used by the selected branch of the switch. 5089 const DeclStmt *DS = cast<DeclStmt>(S); 5090 for (const auto *D : DS->decls()) { 5091 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5092 if (VD->hasLocalStorage() && !VD->getInit()) 5093 if (!EvaluateVarDecl(Info, VD)) 5094 return ESR_Failed; 5095 // FIXME: If the variable has initialization that can't be jumped 5096 // over, bail out of any immediately-surrounding compound-statement 5097 // too. There can't be any case labels here. 5098 } 5099 } 5100 return ESR_CaseNotFound; 5101 } 5102 5103 default: 5104 return ESR_CaseNotFound; 5105 } 5106 } 5107 5108 switch (S->getStmtClass()) { 5109 default: 5110 if (const Expr *E = dyn_cast<Expr>(S)) { 5111 if (E->isValueDependent()) { 5112 if (!EvaluateDependentExpr(E, Info)) 5113 return ESR_Failed; 5114 } else { 5115 // Don't bother evaluating beyond an expression-statement which couldn't 5116 // be evaluated. 5117 // FIXME: Do we need the FullExpressionRAII object here? 5118 // VisitExprWithCleanups should create one when necessary. 5119 FullExpressionRAII Scope(Info); 5120 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5121 return ESR_Failed; 5122 } 5123 return ESR_Succeeded; 5124 } 5125 5126 Info.FFDiag(S->getBeginLoc()); 5127 return ESR_Failed; 5128 5129 case Stmt::NullStmtClass: 5130 return ESR_Succeeded; 5131 5132 case Stmt::DeclStmtClass: { 5133 const DeclStmt *DS = cast<DeclStmt>(S); 5134 for (const auto *D : DS->decls()) { 5135 // Each declaration initialization is its own full-expression. 5136 FullExpressionRAII Scope(Info); 5137 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5138 return ESR_Failed; 5139 if (!Scope.destroy()) 5140 return ESR_Failed; 5141 } 5142 return ESR_Succeeded; 5143 } 5144 5145 case Stmt::ReturnStmtClass: { 5146 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5147 FullExpressionRAII Scope(Info); 5148 if (RetExpr && RetExpr->isValueDependent()) { 5149 EvaluateDependentExpr(RetExpr, Info); 5150 // We know we returned, but we don't know what the value is. 5151 return ESR_Failed; 5152 } 5153 if (RetExpr && 5154 !(Result.Slot 5155 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5156 : Evaluate(Result.Value, Info, RetExpr))) 5157 return ESR_Failed; 5158 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5159 } 5160 5161 case Stmt::CompoundStmtClass: { 5162 BlockScopeRAII Scope(Info); 5163 5164 const CompoundStmt *CS = cast<CompoundStmt>(S); 5165 for (const auto *BI : CS->body()) { 5166 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5167 if (ESR == ESR_Succeeded) 5168 Case = nullptr; 5169 else if (ESR != ESR_CaseNotFound) { 5170 if (ESR != ESR_Failed && !Scope.destroy()) 5171 return ESR_Failed; 5172 return ESR; 5173 } 5174 } 5175 if (Case) 5176 return ESR_CaseNotFound; 5177 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5178 } 5179 5180 case Stmt::IfStmtClass: { 5181 const IfStmt *IS = cast<IfStmt>(S); 5182 5183 // Evaluate the condition, as either a var decl or as an expression. 5184 BlockScopeRAII Scope(Info); 5185 if (const Stmt *Init = IS->getInit()) { 5186 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5187 if (ESR != ESR_Succeeded) { 5188 if (ESR != ESR_Failed && !Scope.destroy()) 5189 return ESR_Failed; 5190 return ESR; 5191 } 5192 } 5193 bool Cond; 5194 if (IS->isConsteval()) 5195 Cond = IS->isNonNegatedConsteval(); 5196 else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5197 Cond)) 5198 return ESR_Failed; 5199 5200 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5201 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5202 if (ESR != ESR_Succeeded) { 5203 if (ESR != ESR_Failed && !Scope.destroy()) 5204 return ESR_Failed; 5205 return ESR; 5206 } 5207 } 5208 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5209 } 5210 5211 case Stmt::WhileStmtClass: { 5212 const WhileStmt *WS = cast<WhileStmt>(S); 5213 while (true) { 5214 BlockScopeRAII Scope(Info); 5215 bool Continue; 5216 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5217 Continue)) 5218 return ESR_Failed; 5219 if (!Continue) 5220 break; 5221 5222 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5223 if (ESR != ESR_Continue) { 5224 if (ESR != ESR_Failed && !Scope.destroy()) 5225 return ESR_Failed; 5226 return ESR; 5227 } 5228 if (!Scope.destroy()) 5229 return ESR_Failed; 5230 } 5231 return ESR_Succeeded; 5232 } 5233 5234 case Stmt::DoStmtClass: { 5235 const DoStmt *DS = cast<DoStmt>(S); 5236 bool Continue; 5237 do { 5238 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5239 if (ESR != ESR_Continue) 5240 return ESR; 5241 Case = nullptr; 5242 5243 if (DS->getCond()->isValueDependent()) { 5244 EvaluateDependentExpr(DS->getCond(), Info); 5245 // Bailout as we don't know whether to keep going or terminate the loop. 5246 return ESR_Failed; 5247 } 5248 FullExpressionRAII CondScope(Info); 5249 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5250 !CondScope.destroy()) 5251 return ESR_Failed; 5252 } while (Continue); 5253 return ESR_Succeeded; 5254 } 5255 5256 case Stmt::ForStmtClass: { 5257 const ForStmt *FS = cast<ForStmt>(S); 5258 BlockScopeRAII ForScope(Info); 5259 if (FS->getInit()) { 5260 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5261 if (ESR != ESR_Succeeded) { 5262 if (ESR != ESR_Failed && !ForScope.destroy()) 5263 return ESR_Failed; 5264 return ESR; 5265 } 5266 } 5267 while (true) { 5268 BlockScopeRAII IterScope(Info); 5269 bool Continue = true; 5270 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5271 FS->getCond(), Continue)) 5272 return ESR_Failed; 5273 if (!Continue) 5274 break; 5275 5276 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5277 if (ESR != ESR_Continue) { 5278 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5279 return ESR_Failed; 5280 return ESR; 5281 } 5282 5283 if (const auto *Inc = FS->getInc()) { 5284 if (Inc->isValueDependent()) { 5285 if (!EvaluateDependentExpr(Inc, Info)) 5286 return ESR_Failed; 5287 } else { 5288 FullExpressionRAII IncScope(Info); 5289 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5290 return ESR_Failed; 5291 } 5292 } 5293 5294 if (!IterScope.destroy()) 5295 return ESR_Failed; 5296 } 5297 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5298 } 5299 5300 case Stmt::CXXForRangeStmtClass: { 5301 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5302 BlockScopeRAII Scope(Info); 5303 5304 // Evaluate the init-statement if present. 5305 if (FS->getInit()) { 5306 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5307 if (ESR != ESR_Succeeded) { 5308 if (ESR != ESR_Failed && !Scope.destroy()) 5309 return ESR_Failed; 5310 return ESR; 5311 } 5312 } 5313 5314 // Initialize the __range variable. 5315 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5316 if (ESR != ESR_Succeeded) { 5317 if (ESR != ESR_Failed && !Scope.destroy()) 5318 return ESR_Failed; 5319 return ESR; 5320 } 5321 5322 // In error-recovery cases it's possible to get here even if we failed to 5323 // synthesize the __begin and __end variables. 5324 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5325 return ESR_Failed; 5326 5327 // Create the __begin and __end iterators. 5328 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5329 if (ESR != ESR_Succeeded) { 5330 if (ESR != ESR_Failed && !Scope.destroy()) 5331 return ESR_Failed; 5332 return ESR; 5333 } 5334 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5335 if (ESR != ESR_Succeeded) { 5336 if (ESR != ESR_Failed && !Scope.destroy()) 5337 return ESR_Failed; 5338 return ESR; 5339 } 5340 5341 while (true) { 5342 // Condition: __begin != __end. 5343 { 5344 if (FS->getCond()->isValueDependent()) { 5345 EvaluateDependentExpr(FS->getCond(), Info); 5346 // We don't know whether to keep going or terminate the loop. 5347 return ESR_Failed; 5348 } 5349 bool Continue = true; 5350 FullExpressionRAII CondExpr(Info); 5351 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5352 return ESR_Failed; 5353 if (!Continue) 5354 break; 5355 } 5356 5357 // User's variable declaration, initialized by *__begin. 5358 BlockScopeRAII InnerScope(Info); 5359 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5360 if (ESR != ESR_Succeeded) { 5361 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5362 return ESR_Failed; 5363 return ESR; 5364 } 5365 5366 // Loop body. 5367 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5368 if (ESR != ESR_Continue) { 5369 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5370 return ESR_Failed; 5371 return ESR; 5372 } 5373 if (FS->getInc()->isValueDependent()) { 5374 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5375 return ESR_Failed; 5376 } else { 5377 // Increment: ++__begin 5378 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5379 return ESR_Failed; 5380 } 5381 5382 if (!InnerScope.destroy()) 5383 return ESR_Failed; 5384 } 5385 5386 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5387 } 5388 5389 case Stmt::SwitchStmtClass: 5390 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5391 5392 case Stmt::ContinueStmtClass: 5393 return ESR_Continue; 5394 5395 case Stmt::BreakStmtClass: 5396 return ESR_Break; 5397 5398 case Stmt::LabelStmtClass: 5399 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5400 5401 case Stmt::AttributedStmtClass: 5402 // As a general principle, C++11 attributes can be ignored without 5403 // any semantic impact. 5404 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5405 Case); 5406 5407 case Stmt::CaseStmtClass: 5408 case Stmt::DefaultStmtClass: 5409 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5410 case Stmt::CXXTryStmtClass: 5411 // Evaluate try blocks by evaluating all sub statements. 5412 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5413 } 5414 } 5415 5416 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5417 /// default constructor. If so, we'll fold it whether or not it's marked as 5418 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5419 /// so we need special handling. 5420 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5421 const CXXConstructorDecl *CD, 5422 bool IsValueInitialization) { 5423 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5424 return false; 5425 5426 // Value-initialization does not call a trivial default constructor, so such a 5427 // call is a core constant expression whether or not the constructor is 5428 // constexpr. 5429 if (!CD->isConstexpr() && !IsValueInitialization) { 5430 if (Info.getLangOpts().CPlusPlus11) { 5431 // FIXME: If DiagDecl is an implicitly-declared special member function, 5432 // we should be much more explicit about why it's not constexpr. 5433 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5434 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5435 Info.Note(CD->getLocation(), diag::note_declared_at); 5436 } else { 5437 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5438 } 5439 } 5440 return true; 5441 } 5442 5443 /// CheckConstexprFunction - Check that a function can be called in a constant 5444 /// expression. 5445 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5446 const FunctionDecl *Declaration, 5447 const FunctionDecl *Definition, 5448 const Stmt *Body) { 5449 // Potential constant expressions can contain calls to declared, but not yet 5450 // defined, constexpr functions. 5451 if (Info.checkingPotentialConstantExpression() && !Definition && 5452 Declaration->isConstexpr()) 5453 return false; 5454 5455 // Bail out if the function declaration itself is invalid. We will 5456 // have produced a relevant diagnostic while parsing it, so just 5457 // note the problematic sub-expression. 5458 if (Declaration->isInvalidDecl()) { 5459 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5460 return false; 5461 } 5462 5463 // DR1872: An instantiated virtual constexpr function can't be called in a 5464 // constant expression (prior to C++20). We can still constant-fold such a 5465 // call. 5466 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5467 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5468 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5469 5470 if (Definition && Definition->isInvalidDecl()) { 5471 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5472 return false; 5473 } 5474 5475 // Can we evaluate this function call? 5476 if (Definition && Definition->isConstexpr() && Body) 5477 return true; 5478 5479 if (Info.getLangOpts().CPlusPlus11) { 5480 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5481 5482 // If this function is not constexpr because it is an inherited 5483 // non-constexpr constructor, diagnose that directly. 5484 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5485 if (CD && CD->isInheritingConstructor()) { 5486 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5487 if (!Inherited->isConstexpr()) 5488 DiagDecl = CD = Inherited; 5489 } 5490 5491 // FIXME: If DiagDecl is an implicitly-declared special member function 5492 // or an inheriting constructor, we should be much more explicit about why 5493 // it's not constexpr. 5494 if (CD && CD->isInheritingConstructor()) 5495 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5496 << CD->getInheritedConstructor().getConstructor()->getParent(); 5497 else 5498 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5499 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5500 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5501 } else { 5502 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5503 } 5504 return false; 5505 } 5506 5507 namespace { 5508 struct CheckDynamicTypeHandler { 5509 AccessKinds AccessKind; 5510 typedef bool result_type; 5511 bool failed() { return false; } 5512 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5513 bool found(APSInt &Value, QualType SubobjType) { return true; } 5514 bool found(APFloat &Value, QualType SubobjType) { return true; } 5515 }; 5516 } // end anonymous namespace 5517 5518 /// Check that we can access the notional vptr of an object / determine its 5519 /// dynamic type. 5520 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5521 AccessKinds AK, bool Polymorphic) { 5522 if (This.Designator.Invalid) 5523 return false; 5524 5525 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5526 5527 if (!Obj) 5528 return false; 5529 5530 if (!Obj.Value) { 5531 // The object is not usable in constant expressions, so we can't inspect 5532 // its value to see if it's in-lifetime or what the active union members 5533 // are. We can still check for a one-past-the-end lvalue. 5534 if (This.Designator.isOnePastTheEnd() || 5535 This.Designator.isMostDerivedAnUnsizedArray()) { 5536 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5537 ? diag::note_constexpr_access_past_end 5538 : diag::note_constexpr_access_unsized_array) 5539 << AK; 5540 return false; 5541 } else if (Polymorphic) { 5542 // Conservatively refuse to perform a polymorphic operation if we would 5543 // not be able to read a notional 'vptr' value. 5544 APValue Val; 5545 This.moveInto(Val); 5546 QualType StarThisType = 5547 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5548 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5549 << AK << Val.getAsString(Info.Ctx, StarThisType); 5550 return false; 5551 } 5552 return true; 5553 } 5554 5555 CheckDynamicTypeHandler Handler{AK}; 5556 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5557 } 5558 5559 /// Check that the pointee of the 'this' pointer in a member function call is 5560 /// either within its lifetime or in its period of construction or destruction. 5561 static bool 5562 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5563 const LValue &This, 5564 const CXXMethodDecl *NamedMember) { 5565 return checkDynamicType( 5566 Info, E, This, 5567 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5568 } 5569 5570 struct DynamicType { 5571 /// The dynamic class type of the object. 5572 const CXXRecordDecl *Type; 5573 /// The corresponding path length in the lvalue. 5574 unsigned PathLength; 5575 }; 5576 5577 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5578 unsigned PathLength) { 5579 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5580 Designator.Entries.size() && "invalid path length"); 5581 return (PathLength == Designator.MostDerivedPathLength) 5582 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5583 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5584 } 5585 5586 /// Determine the dynamic type of an object. 5587 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5588 LValue &This, AccessKinds AK) { 5589 // If we don't have an lvalue denoting an object of class type, there is no 5590 // meaningful dynamic type. (We consider objects of non-class type to have no 5591 // dynamic type.) 5592 if (!checkDynamicType(Info, E, This, AK, true)) 5593 return None; 5594 5595 // Refuse to compute a dynamic type in the presence of virtual bases. This 5596 // shouldn't happen other than in constant-folding situations, since literal 5597 // types can't have virtual bases. 5598 // 5599 // Note that consumers of DynamicType assume that the type has no virtual 5600 // bases, and will need modifications if this restriction is relaxed. 5601 const CXXRecordDecl *Class = 5602 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5603 if (!Class || Class->getNumVBases()) { 5604 Info.FFDiag(E); 5605 return None; 5606 } 5607 5608 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5609 // binary search here instead. But the overwhelmingly common case is that 5610 // we're not in the middle of a constructor, so it probably doesn't matter 5611 // in practice. 5612 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5613 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5614 PathLength <= Path.size(); ++PathLength) { 5615 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5616 Path.slice(0, PathLength))) { 5617 case ConstructionPhase::Bases: 5618 case ConstructionPhase::DestroyingBases: 5619 // We're constructing or destroying a base class. This is not the dynamic 5620 // type. 5621 break; 5622 5623 case ConstructionPhase::None: 5624 case ConstructionPhase::AfterBases: 5625 case ConstructionPhase::AfterFields: 5626 case ConstructionPhase::Destroying: 5627 // We've finished constructing the base classes and not yet started 5628 // destroying them again, so this is the dynamic type. 5629 return DynamicType{getBaseClassType(This.Designator, PathLength), 5630 PathLength}; 5631 } 5632 } 5633 5634 // CWG issue 1517: we're constructing a base class of the object described by 5635 // 'This', so that object has not yet begun its period of construction and 5636 // any polymorphic operation on it results in undefined behavior. 5637 Info.FFDiag(E); 5638 return None; 5639 } 5640 5641 /// Perform virtual dispatch. 5642 static const CXXMethodDecl *HandleVirtualDispatch( 5643 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5644 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5645 Optional<DynamicType> DynType = ComputeDynamicType( 5646 Info, E, This, 5647 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5648 if (!DynType) 5649 return nullptr; 5650 5651 // Find the final overrider. It must be declared in one of the classes on the 5652 // path from the dynamic type to the static type. 5653 // FIXME: If we ever allow literal types to have virtual base classes, that 5654 // won't be true. 5655 const CXXMethodDecl *Callee = Found; 5656 unsigned PathLength = DynType->PathLength; 5657 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5658 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5659 const CXXMethodDecl *Overrider = 5660 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5661 if (Overrider) { 5662 Callee = Overrider; 5663 break; 5664 } 5665 } 5666 5667 // C++2a [class.abstract]p6: 5668 // the effect of making a virtual call to a pure virtual function [...] is 5669 // undefined 5670 if (Callee->isPure()) { 5671 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5672 Info.Note(Callee->getLocation(), diag::note_declared_at); 5673 return nullptr; 5674 } 5675 5676 // If necessary, walk the rest of the path to determine the sequence of 5677 // covariant adjustment steps to apply. 5678 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5679 Found->getReturnType())) { 5680 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5681 for (unsigned CovariantPathLength = PathLength + 1; 5682 CovariantPathLength != This.Designator.Entries.size(); 5683 ++CovariantPathLength) { 5684 const CXXRecordDecl *NextClass = 5685 getBaseClassType(This.Designator, CovariantPathLength); 5686 const CXXMethodDecl *Next = 5687 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5688 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5689 Next->getReturnType(), CovariantAdjustmentPath.back())) 5690 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5691 } 5692 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5693 CovariantAdjustmentPath.back())) 5694 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5695 } 5696 5697 // Perform 'this' adjustment. 5698 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5699 return nullptr; 5700 5701 return Callee; 5702 } 5703 5704 /// Perform the adjustment from a value returned by a virtual function to 5705 /// a value of the statically expected type, which may be a pointer or 5706 /// reference to a base class of the returned type. 5707 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5708 APValue &Result, 5709 ArrayRef<QualType> Path) { 5710 assert(Result.isLValue() && 5711 "unexpected kind of APValue for covariant return"); 5712 if (Result.isNullPointer()) 5713 return true; 5714 5715 LValue LVal; 5716 LVal.setFrom(Info.Ctx, Result); 5717 5718 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5719 for (unsigned I = 1; I != Path.size(); ++I) { 5720 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5721 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5722 if (OldClass != NewClass && 5723 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5724 return false; 5725 OldClass = NewClass; 5726 } 5727 5728 LVal.moveInto(Result); 5729 return true; 5730 } 5731 5732 /// Determine whether \p Base, which is known to be a direct base class of 5733 /// \p Derived, is a public base class. 5734 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5735 const CXXRecordDecl *Base) { 5736 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5737 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5738 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5739 return BaseSpec.getAccessSpecifier() == AS_public; 5740 } 5741 llvm_unreachable("Base is not a direct base of Derived"); 5742 } 5743 5744 /// Apply the given dynamic cast operation on the provided lvalue. 5745 /// 5746 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5747 /// to find a suitable target subobject. 5748 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5749 LValue &Ptr) { 5750 // We can't do anything with a non-symbolic pointer value. 5751 SubobjectDesignator &D = Ptr.Designator; 5752 if (D.Invalid) 5753 return false; 5754 5755 // C++ [expr.dynamic.cast]p6: 5756 // If v is a null pointer value, the result is a null pointer value. 5757 if (Ptr.isNullPointer() && !E->isGLValue()) 5758 return true; 5759 5760 // For all the other cases, we need the pointer to point to an object within 5761 // its lifetime / period of construction / destruction, and we need to know 5762 // its dynamic type. 5763 Optional<DynamicType> DynType = 5764 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5765 if (!DynType) 5766 return false; 5767 5768 // C++ [expr.dynamic.cast]p7: 5769 // If T is "pointer to cv void", then the result is a pointer to the most 5770 // derived object 5771 if (E->getType()->isVoidPointerType()) 5772 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5773 5774 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5775 assert(C && "dynamic_cast target is not void pointer nor class"); 5776 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5777 5778 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5779 // C++ [expr.dynamic.cast]p9: 5780 if (!E->isGLValue()) { 5781 // The value of a failed cast to pointer type is the null pointer value 5782 // of the required result type. 5783 Ptr.setNull(Info.Ctx, E->getType()); 5784 return true; 5785 } 5786 5787 // A failed cast to reference type throws [...] std::bad_cast. 5788 unsigned DiagKind; 5789 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5790 DynType->Type->isDerivedFrom(C))) 5791 DiagKind = 0; 5792 else if (!Paths || Paths->begin() == Paths->end()) 5793 DiagKind = 1; 5794 else if (Paths->isAmbiguous(CQT)) 5795 DiagKind = 2; 5796 else { 5797 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5798 DiagKind = 3; 5799 } 5800 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5801 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5802 << Info.Ctx.getRecordType(DynType->Type) 5803 << E->getType().getUnqualifiedType(); 5804 return false; 5805 }; 5806 5807 // Runtime check, phase 1: 5808 // Walk from the base subobject towards the derived object looking for the 5809 // target type. 5810 for (int PathLength = Ptr.Designator.Entries.size(); 5811 PathLength >= (int)DynType->PathLength; --PathLength) { 5812 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5813 if (declaresSameEntity(Class, C)) 5814 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5815 // We can only walk across public inheritance edges. 5816 if (PathLength > (int)DynType->PathLength && 5817 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5818 Class)) 5819 return RuntimeCheckFailed(nullptr); 5820 } 5821 5822 // Runtime check, phase 2: 5823 // Search the dynamic type for an unambiguous public base of type C. 5824 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5825 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5826 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5827 Paths.front().Access == AS_public) { 5828 // Downcast to the dynamic type... 5829 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5830 return false; 5831 // ... then upcast to the chosen base class subobject. 5832 for (CXXBasePathElement &Elem : Paths.front()) 5833 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5834 return false; 5835 return true; 5836 } 5837 5838 // Otherwise, the runtime check fails. 5839 return RuntimeCheckFailed(&Paths); 5840 } 5841 5842 namespace { 5843 struct StartLifetimeOfUnionMemberHandler { 5844 EvalInfo &Info; 5845 const Expr *LHSExpr; 5846 const FieldDecl *Field; 5847 bool DuringInit; 5848 bool Failed = false; 5849 static const AccessKinds AccessKind = AK_Assign; 5850 5851 typedef bool result_type; 5852 bool failed() { return Failed; } 5853 bool found(APValue &Subobj, QualType SubobjType) { 5854 // We are supposed to perform no initialization but begin the lifetime of 5855 // the object. We interpret that as meaning to do what default 5856 // initialization of the object would do if all constructors involved were 5857 // trivial: 5858 // * All base, non-variant member, and array element subobjects' lifetimes 5859 // begin 5860 // * No variant members' lifetimes begin 5861 // * All scalar subobjects whose lifetimes begin have indeterminate values 5862 assert(SubobjType->isUnionType()); 5863 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5864 // This union member is already active. If it's also in-lifetime, there's 5865 // nothing to do. 5866 if (Subobj.getUnionValue().hasValue()) 5867 return true; 5868 } else if (DuringInit) { 5869 // We're currently in the process of initializing a different union 5870 // member. If we carried on, that initialization would attempt to 5871 // store to an inactive union member, resulting in undefined behavior. 5872 Info.FFDiag(LHSExpr, 5873 diag::note_constexpr_union_member_change_during_init); 5874 return false; 5875 } 5876 APValue Result; 5877 Failed = !getDefaultInitValue(Field->getType(), Result); 5878 Subobj.setUnion(Field, Result); 5879 return true; 5880 } 5881 bool found(APSInt &Value, QualType SubobjType) { 5882 llvm_unreachable("wrong value kind for union object"); 5883 } 5884 bool found(APFloat &Value, QualType SubobjType) { 5885 llvm_unreachable("wrong value kind for union object"); 5886 } 5887 }; 5888 } // end anonymous namespace 5889 5890 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5891 5892 /// Handle a builtin simple-assignment or a call to a trivial assignment 5893 /// operator whose left-hand side might involve a union member access. If it 5894 /// does, implicitly start the lifetime of any accessed union elements per 5895 /// C++20 [class.union]5. 5896 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5897 const LValue &LHS) { 5898 if (LHS.InvalidBase || LHS.Designator.Invalid) 5899 return false; 5900 5901 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5902 // C++ [class.union]p5: 5903 // define the set S(E) of subexpressions of E as follows: 5904 unsigned PathLength = LHS.Designator.Entries.size(); 5905 for (const Expr *E = LHSExpr; E != nullptr;) { 5906 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5907 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5908 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5909 // Note that we can't implicitly start the lifetime of a reference, 5910 // so we don't need to proceed any further if we reach one. 5911 if (!FD || FD->getType()->isReferenceType()) 5912 break; 5913 5914 // ... and also contains A.B if B names a union member ... 5915 if (FD->getParent()->isUnion()) { 5916 // ... of a non-class, non-array type, or of a class type with a 5917 // trivial default constructor that is not deleted, or an array of 5918 // such types. 5919 auto *RD = 5920 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5921 if (!RD || RD->hasTrivialDefaultConstructor()) 5922 UnionPathLengths.push_back({PathLength - 1, FD}); 5923 } 5924 5925 E = ME->getBase(); 5926 --PathLength; 5927 assert(declaresSameEntity(FD, 5928 LHS.Designator.Entries[PathLength] 5929 .getAsBaseOrMember().getPointer())); 5930 5931 // -- If E is of the form A[B] and is interpreted as a built-in array 5932 // subscripting operator, S(E) is [S(the array operand, if any)]. 5933 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5934 // Step over an ArrayToPointerDecay implicit cast. 5935 auto *Base = ASE->getBase()->IgnoreImplicit(); 5936 if (!Base->getType()->isArrayType()) 5937 break; 5938 5939 E = Base; 5940 --PathLength; 5941 5942 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5943 // Step over a derived-to-base conversion. 5944 E = ICE->getSubExpr(); 5945 if (ICE->getCastKind() == CK_NoOp) 5946 continue; 5947 if (ICE->getCastKind() != CK_DerivedToBase && 5948 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5949 break; 5950 // Walk path backwards as we walk up from the base to the derived class. 5951 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5952 --PathLength; 5953 (void)Elt; 5954 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5955 LHS.Designator.Entries[PathLength] 5956 .getAsBaseOrMember().getPointer())); 5957 } 5958 5959 // -- Otherwise, S(E) is empty. 5960 } else { 5961 break; 5962 } 5963 } 5964 5965 // Common case: no unions' lifetimes are started. 5966 if (UnionPathLengths.empty()) 5967 return true; 5968 5969 // if modification of X [would access an inactive union member], an object 5970 // of the type of X is implicitly created 5971 CompleteObject Obj = 5972 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5973 if (!Obj) 5974 return false; 5975 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5976 llvm::reverse(UnionPathLengths)) { 5977 // Form a designator for the union object. 5978 SubobjectDesignator D = LHS.Designator; 5979 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5980 5981 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5982 ConstructionPhase::AfterBases; 5983 StartLifetimeOfUnionMemberHandler StartLifetime{ 5984 Info, LHSExpr, LengthAndField.second, DuringInit}; 5985 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5986 return false; 5987 } 5988 5989 return true; 5990 } 5991 5992 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5993 CallRef Call, EvalInfo &Info, 5994 bool NonNull = false) { 5995 LValue LV; 5996 // Create the parameter slot and register its destruction. For a vararg 5997 // argument, create a temporary. 5998 // FIXME: For calling conventions that destroy parameters in the callee, 5999 // should we consider performing destruction when the function returns 6000 // instead? 6001 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6002 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6003 ScopeKind::Call, LV); 6004 if (!EvaluateInPlace(V, Info, LV, Arg)) 6005 return false; 6006 6007 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6008 // undefined behavior, so is non-constant. 6009 if (NonNull && V.isLValue() && V.isNullPointer()) { 6010 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6011 return false; 6012 } 6013 6014 return true; 6015 } 6016 6017 /// Evaluate the arguments to a function call. 6018 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6019 EvalInfo &Info, const FunctionDecl *Callee, 6020 bool RightToLeft = false) { 6021 bool Success = true; 6022 llvm::SmallBitVector ForbiddenNullArgs; 6023 if (Callee->hasAttr<NonNullAttr>()) { 6024 ForbiddenNullArgs.resize(Args.size()); 6025 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6026 if (!Attr->args_size()) { 6027 ForbiddenNullArgs.set(); 6028 break; 6029 } else 6030 for (auto Idx : Attr->args()) { 6031 unsigned ASTIdx = Idx.getASTIndex(); 6032 if (ASTIdx >= Args.size()) 6033 continue; 6034 ForbiddenNullArgs[ASTIdx] = 1; 6035 } 6036 } 6037 } 6038 for (unsigned I = 0; I < Args.size(); I++) { 6039 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6040 const ParmVarDecl *PVD = 6041 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6042 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6043 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6044 // If we're checking for a potential constant expression, evaluate all 6045 // initializers even if some of them fail. 6046 if (!Info.noteFailure()) 6047 return false; 6048 Success = false; 6049 } 6050 } 6051 return Success; 6052 } 6053 6054 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6055 /// constructor or assignment operator. 6056 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6057 const Expr *E, APValue &Result, 6058 bool CopyObjectRepresentation) { 6059 // Find the reference argument. 6060 CallStackFrame *Frame = Info.CurrentCall; 6061 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6062 if (!RefValue) { 6063 Info.FFDiag(E); 6064 return false; 6065 } 6066 6067 // Copy out the contents of the RHS object. 6068 LValue RefLValue; 6069 RefLValue.setFrom(Info.Ctx, *RefValue); 6070 return handleLValueToRValueConversion( 6071 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6072 CopyObjectRepresentation); 6073 } 6074 6075 /// Evaluate a function call. 6076 static bool HandleFunctionCall(SourceLocation CallLoc, 6077 const FunctionDecl *Callee, const LValue *This, 6078 ArrayRef<const Expr *> Args, CallRef Call, 6079 const Stmt *Body, EvalInfo &Info, 6080 APValue &Result, const LValue *ResultSlot) { 6081 if (!Info.CheckCallLimit(CallLoc)) 6082 return false; 6083 6084 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6085 6086 // For a trivial copy or move assignment, perform an APValue copy. This is 6087 // essential for unions, where the operations performed by the assignment 6088 // operator cannot be represented as statements. 6089 // 6090 // Skip this for non-union classes with no fields; in that case, the defaulted 6091 // copy/move does not actually read the object. 6092 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6093 if (MD && MD->isDefaulted() && 6094 (MD->getParent()->isUnion() || 6095 (MD->isTrivial() && 6096 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6097 assert(This && 6098 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6099 APValue RHSValue; 6100 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6101 MD->getParent()->isUnion())) 6102 return false; 6103 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6104 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6105 return false; 6106 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6107 RHSValue)) 6108 return false; 6109 This->moveInto(Result); 6110 return true; 6111 } else if (MD && isLambdaCallOperator(MD)) { 6112 // We're in a lambda; determine the lambda capture field maps unless we're 6113 // just constexpr checking a lambda's call operator. constexpr checking is 6114 // done before the captures have been added to the closure object (unless 6115 // we're inferring constexpr-ness), so we don't have access to them in this 6116 // case. But since we don't need the captures to constexpr check, we can 6117 // just ignore them. 6118 if (!Info.checkingPotentialConstantExpression()) 6119 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6120 Frame.LambdaThisCaptureField); 6121 } 6122 6123 StmtResult Ret = {Result, ResultSlot}; 6124 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6125 if (ESR == ESR_Succeeded) { 6126 if (Callee->getReturnType()->isVoidType()) 6127 return true; 6128 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6129 } 6130 return ESR == ESR_Returned; 6131 } 6132 6133 /// Evaluate a constructor call. 6134 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6135 CallRef Call, 6136 const CXXConstructorDecl *Definition, 6137 EvalInfo &Info, APValue &Result) { 6138 SourceLocation CallLoc = E->getExprLoc(); 6139 if (!Info.CheckCallLimit(CallLoc)) 6140 return false; 6141 6142 const CXXRecordDecl *RD = Definition->getParent(); 6143 if (RD->getNumVBases()) { 6144 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6145 return false; 6146 } 6147 6148 EvalInfo::EvaluatingConstructorRAII EvalObj( 6149 Info, 6150 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6151 RD->getNumBases()); 6152 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6153 6154 // FIXME: Creating an APValue just to hold a nonexistent return value is 6155 // wasteful. 6156 APValue RetVal; 6157 StmtResult Ret = {RetVal, nullptr}; 6158 6159 // If it's a delegating constructor, delegate. 6160 if (Definition->isDelegatingConstructor()) { 6161 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6162 if ((*I)->getInit()->isValueDependent()) { 6163 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6164 return false; 6165 } else { 6166 FullExpressionRAII InitScope(Info); 6167 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6168 !InitScope.destroy()) 6169 return false; 6170 } 6171 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6172 } 6173 6174 // For a trivial copy or move constructor, perform an APValue copy. This is 6175 // essential for unions (or classes with anonymous union members), where the 6176 // operations performed by the constructor cannot be represented by 6177 // ctor-initializers. 6178 // 6179 // Skip this for empty non-union classes; we should not perform an 6180 // lvalue-to-rvalue conversion on them because their copy constructor does not 6181 // actually read them. 6182 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6183 (Definition->getParent()->isUnion() || 6184 (Definition->isTrivial() && 6185 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6186 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6187 Definition->getParent()->isUnion()); 6188 } 6189 6190 // Reserve space for the struct members. 6191 if (!Result.hasValue()) { 6192 if (!RD->isUnion()) 6193 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6194 std::distance(RD->field_begin(), RD->field_end())); 6195 else 6196 // A union starts with no active member. 6197 Result = APValue((const FieldDecl*)nullptr); 6198 } 6199 6200 if (RD->isInvalidDecl()) return false; 6201 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6202 6203 // A scope for temporaries lifetime-extended by reference members. 6204 BlockScopeRAII LifetimeExtendedScope(Info); 6205 6206 bool Success = true; 6207 unsigned BasesSeen = 0; 6208 #ifndef NDEBUG 6209 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6210 #endif 6211 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6212 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6213 // We might be initializing the same field again if this is an indirect 6214 // field initialization. 6215 if (FieldIt == RD->field_end() || 6216 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6217 assert(Indirect && "fields out of order?"); 6218 return; 6219 } 6220 6221 // Default-initialize any fields with no explicit initializer. 6222 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6223 assert(FieldIt != RD->field_end() && "missing field?"); 6224 if (!FieldIt->isUnnamedBitfield()) 6225 Success &= getDefaultInitValue( 6226 FieldIt->getType(), 6227 Result.getStructField(FieldIt->getFieldIndex())); 6228 } 6229 ++FieldIt; 6230 }; 6231 for (const auto *I : Definition->inits()) { 6232 LValue Subobject = This; 6233 LValue SubobjectParent = This; 6234 APValue *Value = &Result; 6235 6236 // Determine the subobject to initialize. 6237 FieldDecl *FD = nullptr; 6238 if (I->isBaseInitializer()) { 6239 QualType BaseType(I->getBaseClass(), 0); 6240 #ifndef NDEBUG 6241 // Non-virtual base classes are initialized in the order in the class 6242 // definition. We have already checked for virtual base classes. 6243 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6244 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6245 "base class initializers not in expected order"); 6246 ++BaseIt; 6247 #endif 6248 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6249 BaseType->getAsCXXRecordDecl(), &Layout)) 6250 return false; 6251 Value = &Result.getStructBase(BasesSeen++); 6252 } else if ((FD = I->getMember())) { 6253 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6254 return false; 6255 if (RD->isUnion()) { 6256 Result = APValue(FD); 6257 Value = &Result.getUnionValue(); 6258 } else { 6259 SkipToField(FD, false); 6260 Value = &Result.getStructField(FD->getFieldIndex()); 6261 } 6262 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6263 // Walk the indirect field decl's chain to find the object to initialize, 6264 // and make sure we've initialized every step along it. 6265 auto IndirectFieldChain = IFD->chain(); 6266 for (auto *C : IndirectFieldChain) { 6267 FD = cast<FieldDecl>(C); 6268 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6269 // Switch the union field if it differs. This happens if we had 6270 // preceding zero-initialization, and we're now initializing a union 6271 // subobject other than the first. 6272 // FIXME: In this case, the values of the other subobjects are 6273 // specified, since zero-initialization sets all padding bits to zero. 6274 if (!Value->hasValue() || 6275 (Value->isUnion() && Value->getUnionField() != FD)) { 6276 if (CD->isUnion()) 6277 *Value = APValue(FD); 6278 else 6279 // FIXME: This immediately starts the lifetime of all members of 6280 // an anonymous struct. It would be preferable to strictly start 6281 // member lifetime in initialization order. 6282 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6283 } 6284 // Store Subobject as its parent before updating it for the last element 6285 // in the chain. 6286 if (C == IndirectFieldChain.back()) 6287 SubobjectParent = Subobject; 6288 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6289 return false; 6290 if (CD->isUnion()) 6291 Value = &Value->getUnionValue(); 6292 else { 6293 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6294 SkipToField(FD, true); 6295 Value = &Value->getStructField(FD->getFieldIndex()); 6296 } 6297 } 6298 } else { 6299 llvm_unreachable("unknown base initializer kind"); 6300 } 6301 6302 // Need to override This for implicit field initializers as in this case 6303 // This refers to innermost anonymous struct/union containing initializer, 6304 // not to currently constructed class. 6305 const Expr *Init = I->getInit(); 6306 if (Init->isValueDependent()) { 6307 if (!EvaluateDependentExpr(Init, Info)) 6308 return false; 6309 } else { 6310 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6311 isa<CXXDefaultInitExpr>(Init)); 6312 FullExpressionRAII InitScope(Info); 6313 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6314 (FD && FD->isBitField() && 6315 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6316 // If we're checking for a potential constant expression, evaluate all 6317 // initializers even if some of them fail. 6318 if (!Info.noteFailure()) 6319 return false; 6320 Success = false; 6321 } 6322 } 6323 6324 // This is the point at which the dynamic type of the object becomes this 6325 // class type. 6326 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6327 EvalObj.finishedConstructingBases(); 6328 } 6329 6330 // Default-initialize any remaining fields. 6331 if (!RD->isUnion()) { 6332 for (; FieldIt != RD->field_end(); ++FieldIt) { 6333 if (!FieldIt->isUnnamedBitfield()) 6334 Success &= getDefaultInitValue( 6335 FieldIt->getType(), 6336 Result.getStructField(FieldIt->getFieldIndex())); 6337 } 6338 } 6339 6340 EvalObj.finishedConstructingFields(); 6341 6342 return Success && 6343 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6344 LifetimeExtendedScope.destroy(); 6345 } 6346 6347 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6348 ArrayRef<const Expr*> Args, 6349 const CXXConstructorDecl *Definition, 6350 EvalInfo &Info, APValue &Result) { 6351 CallScopeRAII CallScope(Info); 6352 CallRef Call = Info.CurrentCall->createCall(Definition); 6353 if (!EvaluateArgs(Args, Call, Info, Definition)) 6354 return false; 6355 6356 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6357 CallScope.destroy(); 6358 } 6359 6360 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6361 const LValue &This, APValue &Value, 6362 QualType T) { 6363 // Objects can only be destroyed while they're within their lifetimes. 6364 // FIXME: We have no representation for whether an object of type nullptr_t 6365 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6366 // as indeterminate instead? 6367 if (Value.isAbsent() && !T->isNullPtrType()) { 6368 APValue Printable; 6369 This.moveInto(Printable); 6370 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6371 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6372 return false; 6373 } 6374 6375 // Invent an expression for location purposes. 6376 // FIXME: We shouldn't need to do this. 6377 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6378 6379 // For arrays, destroy elements right-to-left. 6380 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6381 uint64_t Size = CAT->getSize().getZExtValue(); 6382 QualType ElemT = CAT->getElementType(); 6383 6384 LValue ElemLV = This; 6385 ElemLV.addArray(Info, &LocE, CAT); 6386 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6387 return false; 6388 6389 // Ensure that we have actual array elements available to destroy; the 6390 // destructors might mutate the value, so we can't run them on the array 6391 // filler. 6392 if (Size && Size > Value.getArrayInitializedElts()) 6393 expandArray(Value, Value.getArraySize() - 1); 6394 6395 for (; Size != 0; --Size) { 6396 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6397 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6398 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6399 return false; 6400 } 6401 6402 // End the lifetime of this array now. 6403 Value = APValue(); 6404 return true; 6405 } 6406 6407 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6408 if (!RD) { 6409 if (T.isDestructedType()) { 6410 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6411 return false; 6412 } 6413 6414 Value = APValue(); 6415 return true; 6416 } 6417 6418 if (RD->getNumVBases()) { 6419 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6420 return false; 6421 } 6422 6423 const CXXDestructorDecl *DD = RD->getDestructor(); 6424 if (!DD && !RD->hasTrivialDestructor()) { 6425 Info.FFDiag(CallLoc); 6426 return false; 6427 } 6428 6429 if (!DD || DD->isTrivial() || 6430 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6431 // A trivial destructor just ends the lifetime of the object. Check for 6432 // this case before checking for a body, because we might not bother 6433 // building a body for a trivial destructor. Note that it doesn't matter 6434 // whether the destructor is constexpr in this case; all trivial 6435 // destructors are constexpr. 6436 // 6437 // If an anonymous union would be destroyed, some enclosing destructor must 6438 // have been explicitly defined, and the anonymous union destruction should 6439 // have no effect. 6440 Value = APValue(); 6441 return true; 6442 } 6443 6444 if (!Info.CheckCallLimit(CallLoc)) 6445 return false; 6446 6447 const FunctionDecl *Definition = nullptr; 6448 const Stmt *Body = DD->getBody(Definition); 6449 6450 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6451 return false; 6452 6453 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6454 6455 // We're now in the period of destruction of this object. 6456 unsigned BasesLeft = RD->getNumBases(); 6457 EvalInfo::EvaluatingDestructorRAII EvalObj( 6458 Info, 6459 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6460 if (!EvalObj.DidInsert) { 6461 // C++2a [class.dtor]p19: 6462 // the behavior is undefined if the destructor is invoked for an object 6463 // whose lifetime has ended 6464 // (Note that formally the lifetime ends when the period of destruction 6465 // begins, even though certain uses of the object remain valid until the 6466 // period of destruction ends.) 6467 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6468 return false; 6469 } 6470 6471 // FIXME: Creating an APValue just to hold a nonexistent return value is 6472 // wasteful. 6473 APValue RetVal; 6474 StmtResult Ret = {RetVal, nullptr}; 6475 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6476 return false; 6477 6478 // A union destructor does not implicitly destroy its members. 6479 if (RD->isUnion()) 6480 return true; 6481 6482 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6483 6484 // We don't have a good way to iterate fields in reverse, so collect all the 6485 // fields first and then walk them backwards. 6486 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6487 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6488 if (FD->isUnnamedBitfield()) 6489 continue; 6490 6491 LValue Subobject = This; 6492 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6493 return false; 6494 6495 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6496 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6497 FD->getType())) 6498 return false; 6499 } 6500 6501 if (BasesLeft != 0) 6502 EvalObj.startedDestroyingBases(); 6503 6504 // Destroy base classes in reverse order. 6505 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6506 --BasesLeft; 6507 6508 QualType BaseType = Base.getType(); 6509 LValue Subobject = This; 6510 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6511 BaseType->getAsCXXRecordDecl(), &Layout)) 6512 return false; 6513 6514 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6515 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6516 BaseType)) 6517 return false; 6518 } 6519 assert(BasesLeft == 0 && "NumBases was wrong?"); 6520 6521 // The period of destruction ends now. The object is gone. 6522 Value = APValue(); 6523 return true; 6524 } 6525 6526 namespace { 6527 struct DestroyObjectHandler { 6528 EvalInfo &Info; 6529 const Expr *E; 6530 const LValue &This; 6531 const AccessKinds AccessKind; 6532 6533 typedef bool result_type; 6534 bool failed() { return false; } 6535 bool found(APValue &Subobj, QualType SubobjType) { 6536 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6537 SubobjType); 6538 } 6539 bool found(APSInt &Value, QualType SubobjType) { 6540 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6541 return false; 6542 } 6543 bool found(APFloat &Value, QualType SubobjType) { 6544 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6545 return false; 6546 } 6547 }; 6548 } 6549 6550 /// Perform a destructor or pseudo-destructor call on the given object, which 6551 /// might in general not be a complete object. 6552 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6553 const LValue &This, QualType ThisType) { 6554 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6555 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6556 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6557 } 6558 6559 /// Destroy and end the lifetime of the given complete object. 6560 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6561 APValue::LValueBase LVBase, APValue &Value, 6562 QualType T) { 6563 // If we've had an unmodeled side-effect, we can't rely on mutable state 6564 // (such as the object we're about to destroy) being correct. 6565 if (Info.EvalStatus.HasSideEffects) 6566 return false; 6567 6568 LValue LV; 6569 LV.set({LVBase}); 6570 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6571 } 6572 6573 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6574 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6575 LValue &Result) { 6576 if (Info.checkingPotentialConstantExpression() || 6577 Info.SpeculativeEvaluationDepth) 6578 return false; 6579 6580 // This is permitted only within a call to std::allocator<T>::allocate. 6581 auto Caller = Info.getStdAllocatorCaller("allocate"); 6582 if (!Caller) { 6583 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6584 ? diag::note_constexpr_new_untyped 6585 : diag::note_constexpr_new); 6586 return false; 6587 } 6588 6589 QualType ElemType = Caller.ElemType; 6590 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6591 Info.FFDiag(E->getExprLoc(), 6592 diag::note_constexpr_new_not_complete_object_type) 6593 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6594 return false; 6595 } 6596 6597 APSInt ByteSize; 6598 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6599 return false; 6600 bool IsNothrow = false; 6601 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6602 EvaluateIgnoredValue(Info, E->getArg(I)); 6603 IsNothrow |= E->getType()->isNothrowT(); 6604 } 6605 6606 CharUnits ElemSize; 6607 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6608 return false; 6609 APInt Size, Remainder; 6610 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6611 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6612 if (Remainder != 0) { 6613 // This likely indicates a bug in the implementation of 'std::allocator'. 6614 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6615 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6616 return false; 6617 } 6618 6619 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6620 if (IsNothrow) { 6621 Result.setNull(Info.Ctx, E->getType()); 6622 return true; 6623 } 6624 6625 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6626 return false; 6627 } 6628 6629 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6630 ArrayType::Normal, 0); 6631 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6632 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6633 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6634 return true; 6635 } 6636 6637 static bool hasVirtualDestructor(QualType T) { 6638 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6639 if (CXXDestructorDecl *DD = RD->getDestructor()) 6640 return DD->isVirtual(); 6641 return false; 6642 } 6643 6644 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6645 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6646 if (CXXDestructorDecl *DD = RD->getDestructor()) 6647 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6648 return nullptr; 6649 } 6650 6651 /// Check that the given object is a suitable pointer to a heap allocation that 6652 /// still exists and is of the right kind for the purpose of a deletion. 6653 /// 6654 /// On success, returns the heap allocation to deallocate. On failure, produces 6655 /// a diagnostic and returns None. 6656 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6657 const LValue &Pointer, 6658 DynAlloc::Kind DeallocKind) { 6659 auto PointerAsString = [&] { 6660 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6661 }; 6662 6663 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6664 if (!DA) { 6665 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6666 << PointerAsString(); 6667 if (Pointer.Base) 6668 NoteLValueLocation(Info, Pointer.Base); 6669 return None; 6670 } 6671 6672 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6673 if (!Alloc) { 6674 Info.FFDiag(E, diag::note_constexpr_double_delete); 6675 return None; 6676 } 6677 6678 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6679 if (DeallocKind != (*Alloc)->getKind()) { 6680 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6681 << DeallocKind << (*Alloc)->getKind() << AllocType; 6682 NoteLValueLocation(Info, Pointer.Base); 6683 return None; 6684 } 6685 6686 bool Subobject = false; 6687 if (DeallocKind == DynAlloc::New) { 6688 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6689 Pointer.Designator.isOnePastTheEnd(); 6690 } else { 6691 Subobject = Pointer.Designator.Entries.size() != 1 || 6692 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6693 } 6694 if (Subobject) { 6695 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6696 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6697 return None; 6698 } 6699 6700 return Alloc; 6701 } 6702 6703 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6704 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6705 if (Info.checkingPotentialConstantExpression() || 6706 Info.SpeculativeEvaluationDepth) 6707 return false; 6708 6709 // This is permitted only within a call to std::allocator<T>::deallocate. 6710 if (!Info.getStdAllocatorCaller("deallocate")) { 6711 Info.FFDiag(E->getExprLoc()); 6712 return true; 6713 } 6714 6715 LValue Pointer; 6716 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6717 return false; 6718 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6719 EvaluateIgnoredValue(Info, E->getArg(I)); 6720 6721 if (Pointer.Designator.Invalid) 6722 return false; 6723 6724 // Deleting a null pointer would have no effect, but it's not permitted by 6725 // std::allocator<T>::deallocate's contract. 6726 if (Pointer.isNullPointer()) { 6727 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6728 return true; 6729 } 6730 6731 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6732 return false; 6733 6734 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6735 return true; 6736 } 6737 6738 //===----------------------------------------------------------------------===// 6739 // Generic Evaluation 6740 //===----------------------------------------------------------------------===// 6741 namespace { 6742 6743 class BitCastBuffer { 6744 // FIXME: We're going to need bit-level granularity when we support 6745 // bit-fields. 6746 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6747 // we don't support a host or target where that is the case. Still, we should 6748 // use a more generic type in case we ever do. 6749 SmallVector<Optional<unsigned char>, 32> Bytes; 6750 6751 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6752 "Need at least 8 bit unsigned char"); 6753 6754 bool TargetIsLittleEndian; 6755 6756 public: 6757 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6758 : Bytes(Width.getQuantity()), 6759 TargetIsLittleEndian(TargetIsLittleEndian) {} 6760 6761 LLVM_NODISCARD 6762 bool readObject(CharUnits Offset, CharUnits Width, 6763 SmallVectorImpl<unsigned char> &Output) const { 6764 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6765 // If a byte of an integer is uninitialized, then the whole integer is 6766 // uninitialized. 6767 if (!Bytes[I.getQuantity()]) 6768 return false; 6769 Output.push_back(*Bytes[I.getQuantity()]); 6770 } 6771 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6772 std::reverse(Output.begin(), Output.end()); 6773 return true; 6774 } 6775 6776 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6777 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6778 std::reverse(Input.begin(), Input.end()); 6779 6780 size_t Index = 0; 6781 for (unsigned char Byte : Input) { 6782 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6783 Bytes[Offset.getQuantity() + Index] = Byte; 6784 ++Index; 6785 } 6786 } 6787 6788 size_t size() { return Bytes.size(); } 6789 }; 6790 6791 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6792 /// target would represent the value at runtime. 6793 class APValueToBufferConverter { 6794 EvalInfo &Info; 6795 BitCastBuffer Buffer; 6796 const CastExpr *BCE; 6797 6798 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6799 const CastExpr *BCE) 6800 : Info(Info), 6801 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6802 BCE(BCE) {} 6803 6804 bool visit(const APValue &Val, QualType Ty) { 6805 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6806 } 6807 6808 // Write out Val with type Ty into Buffer starting at Offset. 6809 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6810 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6811 6812 // As a special case, nullptr_t has an indeterminate value. 6813 if (Ty->isNullPtrType()) 6814 return true; 6815 6816 // Dig through Src to find the byte at SrcOffset. 6817 switch (Val.getKind()) { 6818 case APValue::Indeterminate: 6819 case APValue::None: 6820 return true; 6821 6822 case APValue::Int: 6823 return visitInt(Val.getInt(), Ty, Offset); 6824 case APValue::Float: 6825 return visitFloat(Val.getFloat(), Ty, Offset); 6826 case APValue::Array: 6827 return visitArray(Val, Ty, Offset); 6828 case APValue::Struct: 6829 return visitRecord(Val, Ty, Offset); 6830 6831 case APValue::ComplexInt: 6832 case APValue::ComplexFloat: 6833 case APValue::Vector: 6834 case APValue::FixedPoint: 6835 // FIXME: We should support these. 6836 6837 case APValue::Union: 6838 case APValue::MemberPointer: 6839 case APValue::AddrLabelDiff: { 6840 Info.FFDiag(BCE->getBeginLoc(), 6841 diag::note_constexpr_bit_cast_unsupported_type) 6842 << Ty; 6843 return false; 6844 } 6845 6846 case APValue::LValue: 6847 llvm_unreachable("LValue subobject in bit_cast?"); 6848 } 6849 llvm_unreachable("Unhandled APValue::ValueKind"); 6850 } 6851 6852 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6853 const RecordDecl *RD = Ty->getAsRecordDecl(); 6854 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6855 6856 // Visit the base classes. 6857 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6858 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6859 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6860 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6861 6862 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6863 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6864 return false; 6865 } 6866 } 6867 6868 // Visit the fields. 6869 unsigned FieldIdx = 0; 6870 for (FieldDecl *FD : RD->fields()) { 6871 if (FD->isBitField()) { 6872 Info.FFDiag(BCE->getBeginLoc(), 6873 diag::note_constexpr_bit_cast_unsupported_bitfield); 6874 return false; 6875 } 6876 6877 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6878 6879 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6880 "only bit-fields can have sub-char alignment"); 6881 CharUnits FieldOffset = 6882 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6883 QualType FieldTy = FD->getType(); 6884 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6885 return false; 6886 ++FieldIdx; 6887 } 6888 6889 return true; 6890 } 6891 6892 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6893 const auto *CAT = 6894 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6895 if (!CAT) 6896 return false; 6897 6898 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6899 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6900 unsigned ArraySize = Val.getArraySize(); 6901 // First, initialize the initialized elements. 6902 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6903 const APValue &SubObj = Val.getArrayInitializedElt(I); 6904 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6905 return false; 6906 } 6907 6908 // Next, initialize the rest of the array using the filler. 6909 if (Val.hasArrayFiller()) { 6910 const APValue &Filler = Val.getArrayFiller(); 6911 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6912 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6913 return false; 6914 } 6915 } 6916 6917 return true; 6918 } 6919 6920 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6921 APSInt AdjustedVal = Val; 6922 unsigned Width = AdjustedVal.getBitWidth(); 6923 if (Ty->isBooleanType()) { 6924 Width = Info.Ctx.getTypeSize(Ty); 6925 AdjustedVal = AdjustedVal.extend(Width); 6926 } 6927 6928 SmallVector<unsigned char, 8> Bytes(Width / 8); 6929 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6930 Buffer.writeObject(Offset, Bytes); 6931 return true; 6932 } 6933 6934 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6935 APSInt AsInt(Val.bitcastToAPInt()); 6936 return visitInt(AsInt, Ty, Offset); 6937 } 6938 6939 public: 6940 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6941 const CastExpr *BCE) { 6942 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6943 APValueToBufferConverter Converter(Info, DstSize, BCE); 6944 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6945 return None; 6946 return Converter.Buffer; 6947 } 6948 }; 6949 6950 /// Write an BitCastBuffer into an APValue. 6951 class BufferToAPValueConverter { 6952 EvalInfo &Info; 6953 const BitCastBuffer &Buffer; 6954 const CastExpr *BCE; 6955 6956 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6957 const CastExpr *BCE) 6958 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6959 6960 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6961 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6962 // Ideally this will be unreachable. 6963 llvm::NoneType unsupportedType(QualType Ty) { 6964 Info.FFDiag(BCE->getBeginLoc(), 6965 diag::note_constexpr_bit_cast_unsupported_type) 6966 << Ty; 6967 return None; 6968 } 6969 6970 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6971 Info.FFDiag(BCE->getBeginLoc(), 6972 diag::note_constexpr_bit_cast_unrepresentable_value) 6973 << Ty << toString(Val, /*Radix=*/10); 6974 return None; 6975 } 6976 6977 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6978 const EnumType *EnumSugar = nullptr) { 6979 if (T->isNullPtrType()) { 6980 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6981 return APValue((Expr *)nullptr, 6982 /*Offset=*/CharUnits::fromQuantity(NullValue), 6983 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6984 } 6985 6986 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6987 6988 // Work around floating point types that contain unused padding bytes. This 6989 // is really just `long double` on x86, which is the only fundamental type 6990 // with padding bytes. 6991 if (T->isRealFloatingType()) { 6992 const llvm::fltSemantics &Semantics = 6993 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6994 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6995 assert(NumBits % 8 == 0); 6996 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6997 if (NumBytes != SizeOf) 6998 SizeOf = NumBytes; 6999 } 7000 7001 SmallVector<uint8_t, 8> Bytes; 7002 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7003 // If this is std::byte or unsigned char, then its okay to store an 7004 // indeterminate value. 7005 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7006 bool IsUChar = 7007 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7008 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7009 if (!IsStdByte && !IsUChar) { 7010 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7011 Info.FFDiag(BCE->getExprLoc(), 7012 diag::note_constexpr_bit_cast_indet_dest) 7013 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7014 return None; 7015 } 7016 7017 return APValue::IndeterminateValue(); 7018 } 7019 7020 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7021 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7022 7023 if (T->isIntegralOrEnumerationType()) { 7024 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7025 7026 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7027 if (IntWidth != Val.getBitWidth()) { 7028 APSInt Truncated = Val.trunc(IntWidth); 7029 if (Truncated.extend(Val.getBitWidth()) != Val) 7030 return unrepresentableValue(QualType(T, 0), Val); 7031 Val = Truncated; 7032 } 7033 7034 return APValue(Val); 7035 } 7036 7037 if (T->isRealFloatingType()) { 7038 const llvm::fltSemantics &Semantics = 7039 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7040 return APValue(APFloat(Semantics, Val)); 7041 } 7042 7043 return unsupportedType(QualType(T, 0)); 7044 } 7045 7046 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7047 const RecordDecl *RD = RTy->getAsRecordDecl(); 7048 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7049 7050 unsigned NumBases = 0; 7051 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7052 NumBases = CXXRD->getNumBases(); 7053 7054 APValue ResultVal(APValue::UninitStruct(), NumBases, 7055 std::distance(RD->field_begin(), RD->field_end())); 7056 7057 // Visit the base classes. 7058 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7059 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7060 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7061 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7062 if (BaseDecl->isEmpty() || 7063 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7064 continue; 7065 7066 Optional<APValue> SubObj = visitType( 7067 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7068 if (!SubObj) 7069 return None; 7070 ResultVal.getStructBase(I) = *SubObj; 7071 } 7072 } 7073 7074 // Visit the fields. 7075 unsigned FieldIdx = 0; 7076 for (FieldDecl *FD : RD->fields()) { 7077 // FIXME: We don't currently support bit-fields. A lot of the logic for 7078 // this is in CodeGen, so we need to factor it around. 7079 if (FD->isBitField()) { 7080 Info.FFDiag(BCE->getBeginLoc(), 7081 diag::note_constexpr_bit_cast_unsupported_bitfield); 7082 return None; 7083 } 7084 7085 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7086 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7087 7088 CharUnits FieldOffset = 7089 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7090 Offset; 7091 QualType FieldTy = FD->getType(); 7092 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7093 if (!SubObj) 7094 return None; 7095 ResultVal.getStructField(FieldIdx) = *SubObj; 7096 ++FieldIdx; 7097 } 7098 7099 return ResultVal; 7100 } 7101 7102 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7103 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7104 assert(!RepresentationType.isNull() && 7105 "enum forward decl should be caught by Sema"); 7106 const auto *AsBuiltin = 7107 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7108 // Recurse into the underlying type. Treat std::byte transparently as 7109 // unsigned char. 7110 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7111 } 7112 7113 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7114 size_t Size = Ty->getSize().getLimitedValue(); 7115 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7116 7117 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7118 for (size_t I = 0; I != Size; ++I) { 7119 Optional<APValue> ElementValue = 7120 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7121 if (!ElementValue) 7122 return None; 7123 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7124 } 7125 7126 return ArrayValue; 7127 } 7128 7129 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7130 return unsupportedType(QualType(Ty, 0)); 7131 } 7132 7133 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7134 QualType Can = Ty.getCanonicalType(); 7135 7136 switch (Can->getTypeClass()) { 7137 #define TYPE(Class, Base) \ 7138 case Type::Class: \ 7139 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7140 #define ABSTRACT_TYPE(Class, Base) 7141 #define NON_CANONICAL_TYPE(Class, Base) \ 7142 case Type::Class: \ 7143 llvm_unreachable("non-canonical type should be impossible!"); 7144 #define DEPENDENT_TYPE(Class, Base) \ 7145 case Type::Class: \ 7146 llvm_unreachable( \ 7147 "dependent types aren't supported in the constant evaluator!"); 7148 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7149 case Type::Class: \ 7150 llvm_unreachable("either dependent or not canonical!"); 7151 #include "clang/AST/TypeNodes.inc" 7152 } 7153 llvm_unreachable("Unhandled Type::TypeClass"); 7154 } 7155 7156 public: 7157 // Pull out a full value of type DstType. 7158 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7159 const CastExpr *BCE) { 7160 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7161 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7162 } 7163 }; 7164 7165 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7166 QualType Ty, EvalInfo *Info, 7167 const ASTContext &Ctx, 7168 bool CheckingDest) { 7169 Ty = Ty.getCanonicalType(); 7170 7171 auto diag = [&](int Reason) { 7172 if (Info) 7173 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7174 << CheckingDest << (Reason == 4) << Reason; 7175 return false; 7176 }; 7177 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7178 if (Info) 7179 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7180 << NoteTy << Construct << Ty; 7181 return false; 7182 }; 7183 7184 if (Ty->isUnionType()) 7185 return diag(0); 7186 if (Ty->isPointerType()) 7187 return diag(1); 7188 if (Ty->isMemberPointerType()) 7189 return diag(2); 7190 if (Ty.isVolatileQualified()) 7191 return diag(3); 7192 7193 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7194 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7195 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7196 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7197 CheckingDest)) 7198 return note(1, BS.getType(), BS.getBeginLoc()); 7199 } 7200 for (FieldDecl *FD : Record->fields()) { 7201 if (FD->getType()->isReferenceType()) 7202 return diag(4); 7203 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7204 CheckingDest)) 7205 return note(0, FD->getType(), FD->getBeginLoc()); 7206 } 7207 } 7208 7209 if (Ty->isArrayType() && 7210 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7211 Info, Ctx, CheckingDest)) 7212 return false; 7213 7214 return true; 7215 } 7216 7217 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7218 const ASTContext &Ctx, 7219 const CastExpr *BCE) { 7220 bool DestOK = checkBitCastConstexprEligibilityType( 7221 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7222 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7223 BCE->getBeginLoc(), 7224 BCE->getSubExpr()->getType(), Info, Ctx, false); 7225 return SourceOK; 7226 } 7227 7228 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7229 APValue &SourceValue, 7230 const CastExpr *BCE) { 7231 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7232 "no host or target supports non 8-bit chars"); 7233 assert(SourceValue.isLValue() && 7234 "LValueToRValueBitcast requires an lvalue operand!"); 7235 7236 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7237 return false; 7238 7239 LValue SourceLValue; 7240 APValue SourceRValue; 7241 SourceLValue.setFrom(Info.Ctx, SourceValue); 7242 if (!handleLValueToRValueConversion( 7243 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7244 SourceRValue, /*WantObjectRepresentation=*/true)) 7245 return false; 7246 7247 // Read out SourceValue into a char buffer. 7248 Optional<BitCastBuffer> Buffer = 7249 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7250 if (!Buffer) 7251 return false; 7252 7253 // Write out the buffer into a new APValue. 7254 Optional<APValue> MaybeDestValue = 7255 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7256 if (!MaybeDestValue) 7257 return false; 7258 7259 DestValue = std::move(*MaybeDestValue); 7260 return true; 7261 } 7262 7263 template <class Derived> 7264 class ExprEvaluatorBase 7265 : public ConstStmtVisitor<Derived, bool> { 7266 private: 7267 Derived &getDerived() { return static_cast<Derived&>(*this); } 7268 bool DerivedSuccess(const APValue &V, const Expr *E) { 7269 return getDerived().Success(V, E); 7270 } 7271 bool DerivedZeroInitialization(const Expr *E) { 7272 return getDerived().ZeroInitialization(E); 7273 } 7274 7275 // Check whether a conditional operator with a non-constant condition is a 7276 // potential constant expression. If neither arm is a potential constant 7277 // expression, then the conditional operator is not either. 7278 template<typename ConditionalOperator> 7279 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7280 assert(Info.checkingPotentialConstantExpression()); 7281 7282 // Speculatively evaluate both arms. 7283 SmallVector<PartialDiagnosticAt, 8> Diag; 7284 { 7285 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7286 StmtVisitorTy::Visit(E->getFalseExpr()); 7287 if (Diag.empty()) 7288 return; 7289 } 7290 7291 { 7292 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7293 Diag.clear(); 7294 StmtVisitorTy::Visit(E->getTrueExpr()); 7295 if (Diag.empty()) 7296 return; 7297 } 7298 7299 Error(E, diag::note_constexpr_conditional_never_const); 7300 } 7301 7302 7303 template<typename ConditionalOperator> 7304 bool HandleConditionalOperator(const ConditionalOperator *E) { 7305 bool BoolResult; 7306 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7307 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7308 CheckPotentialConstantConditional(E); 7309 return false; 7310 } 7311 if (Info.noteFailure()) { 7312 StmtVisitorTy::Visit(E->getTrueExpr()); 7313 StmtVisitorTy::Visit(E->getFalseExpr()); 7314 } 7315 return false; 7316 } 7317 7318 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7319 return StmtVisitorTy::Visit(EvalExpr); 7320 } 7321 7322 protected: 7323 EvalInfo &Info; 7324 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7325 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7326 7327 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7328 return Info.CCEDiag(E, D); 7329 } 7330 7331 bool ZeroInitialization(const Expr *E) { return Error(E); } 7332 7333 public: 7334 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7335 7336 EvalInfo &getEvalInfo() { return Info; } 7337 7338 /// Report an evaluation error. This should only be called when an error is 7339 /// first discovered. When propagating an error, just return false. 7340 bool Error(const Expr *E, diag::kind D) { 7341 Info.FFDiag(E, D); 7342 return false; 7343 } 7344 bool Error(const Expr *E) { 7345 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7346 } 7347 7348 bool VisitStmt(const Stmt *) { 7349 llvm_unreachable("Expression evaluator should not be called on stmts"); 7350 } 7351 bool VisitExpr(const Expr *E) { 7352 return Error(E); 7353 } 7354 7355 bool VisitConstantExpr(const ConstantExpr *E) { 7356 if (E->hasAPValueResult()) 7357 return DerivedSuccess(E->getAPValueResult(), E); 7358 7359 return StmtVisitorTy::Visit(E->getSubExpr()); 7360 } 7361 7362 bool VisitParenExpr(const ParenExpr *E) 7363 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7364 bool VisitUnaryExtension(const UnaryOperator *E) 7365 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7366 bool VisitUnaryPlus(const UnaryOperator *E) 7367 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7368 bool VisitChooseExpr(const ChooseExpr *E) 7369 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7370 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7371 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7372 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7373 { return StmtVisitorTy::Visit(E->getReplacement()); } 7374 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7375 TempVersionRAII RAII(*Info.CurrentCall); 7376 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7377 return StmtVisitorTy::Visit(E->getExpr()); 7378 } 7379 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7380 TempVersionRAII RAII(*Info.CurrentCall); 7381 // The initializer may not have been parsed yet, or might be erroneous. 7382 if (!E->getExpr()) 7383 return Error(E); 7384 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7385 return StmtVisitorTy::Visit(E->getExpr()); 7386 } 7387 7388 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7389 FullExpressionRAII Scope(Info); 7390 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7391 } 7392 7393 // Temporaries are registered when created, so we don't care about 7394 // CXXBindTemporaryExpr. 7395 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7396 return StmtVisitorTy::Visit(E->getSubExpr()); 7397 } 7398 7399 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7400 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7401 return static_cast<Derived*>(this)->VisitCastExpr(E); 7402 } 7403 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7404 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7405 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7406 return static_cast<Derived*>(this)->VisitCastExpr(E); 7407 } 7408 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7409 return static_cast<Derived*>(this)->VisitCastExpr(E); 7410 } 7411 7412 bool VisitBinaryOperator(const BinaryOperator *E) { 7413 switch (E->getOpcode()) { 7414 default: 7415 return Error(E); 7416 7417 case BO_Comma: 7418 VisitIgnoredValue(E->getLHS()); 7419 return StmtVisitorTy::Visit(E->getRHS()); 7420 7421 case BO_PtrMemD: 7422 case BO_PtrMemI: { 7423 LValue Obj; 7424 if (!HandleMemberPointerAccess(Info, E, Obj)) 7425 return false; 7426 APValue Result; 7427 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7428 return false; 7429 return DerivedSuccess(Result, E); 7430 } 7431 } 7432 } 7433 7434 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7435 return StmtVisitorTy::Visit(E->getSemanticForm()); 7436 } 7437 7438 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7439 // Evaluate and cache the common expression. We treat it as a temporary, 7440 // even though it's not quite the same thing. 7441 LValue CommonLV; 7442 if (!Evaluate(Info.CurrentCall->createTemporary( 7443 E->getOpaqueValue(), 7444 getStorageType(Info.Ctx, E->getOpaqueValue()), 7445 ScopeKind::FullExpression, CommonLV), 7446 Info, E->getCommon())) 7447 return false; 7448 7449 return HandleConditionalOperator(E); 7450 } 7451 7452 bool VisitConditionalOperator(const ConditionalOperator *E) { 7453 bool IsBcpCall = false; 7454 // If the condition (ignoring parens) is a __builtin_constant_p call, 7455 // the result is a constant expression if it can be folded without 7456 // side-effects. This is an important GNU extension. See GCC PR38377 7457 // for discussion. 7458 if (const CallExpr *CallCE = 7459 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7460 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7461 IsBcpCall = true; 7462 7463 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7464 // constant expression; we can't check whether it's potentially foldable. 7465 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7466 // it would return 'false' in this mode. 7467 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7468 return false; 7469 7470 FoldConstant Fold(Info, IsBcpCall); 7471 if (!HandleConditionalOperator(E)) { 7472 Fold.keepDiagnostics(); 7473 return false; 7474 } 7475 7476 return true; 7477 } 7478 7479 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7480 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7481 return DerivedSuccess(*Value, E); 7482 7483 const Expr *Source = E->getSourceExpr(); 7484 if (!Source) 7485 return Error(E); 7486 if (Source == E) { // sanity checking. 7487 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7488 return Error(E); 7489 } 7490 return StmtVisitorTy::Visit(Source); 7491 } 7492 7493 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7494 for (const Expr *SemE : E->semantics()) { 7495 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7496 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7497 // result expression: there could be two different LValues that would 7498 // refer to the same object in that case, and we can't model that. 7499 if (SemE == E->getResultExpr()) 7500 return Error(E); 7501 7502 // Unique OVEs get evaluated if and when we encounter them when 7503 // emitting the rest of the semantic form, rather than eagerly. 7504 if (OVE->isUnique()) 7505 continue; 7506 7507 LValue LV; 7508 if (!Evaluate(Info.CurrentCall->createTemporary( 7509 OVE, getStorageType(Info.Ctx, OVE), 7510 ScopeKind::FullExpression, LV), 7511 Info, OVE->getSourceExpr())) 7512 return false; 7513 } else if (SemE == E->getResultExpr()) { 7514 if (!StmtVisitorTy::Visit(SemE)) 7515 return false; 7516 } else { 7517 if (!EvaluateIgnoredValue(Info, SemE)) 7518 return false; 7519 } 7520 } 7521 return true; 7522 } 7523 7524 bool VisitCallExpr(const CallExpr *E) { 7525 APValue Result; 7526 if (!handleCallExpr(E, Result, nullptr)) 7527 return false; 7528 return DerivedSuccess(Result, E); 7529 } 7530 7531 bool handleCallExpr(const CallExpr *E, APValue &Result, 7532 const LValue *ResultSlot) { 7533 CallScopeRAII CallScope(Info); 7534 7535 const Expr *Callee = E->getCallee()->IgnoreParens(); 7536 QualType CalleeType = Callee->getType(); 7537 7538 const FunctionDecl *FD = nullptr; 7539 LValue *This = nullptr, ThisVal; 7540 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7541 bool HasQualifier = false; 7542 7543 CallRef Call; 7544 7545 // Extract function decl and 'this' pointer from the callee. 7546 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7547 const CXXMethodDecl *Member = nullptr; 7548 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7549 // Explicit bound member calls, such as x.f() or p->g(); 7550 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7551 return false; 7552 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7553 if (!Member) 7554 return Error(Callee); 7555 This = &ThisVal; 7556 HasQualifier = ME->hasQualifier(); 7557 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7558 // Indirect bound member calls ('.*' or '->*'). 7559 const ValueDecl *D = 7560 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7561 if (!D) 7562 return false; 7563 Member = dyn_cast<CXXMethodDecl>(D); 7564 if (!Member) 7565 return Error(Callee); 7566 This = &ThisVal; 7567 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7568 if (!Info.getLangOpts().CPlusPlus20) 7569 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7570 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7571 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7572 } else 7573 return Error(Callee); 7574 FD = Member; 7575 } else if (CalleeType->isFunctionPointerType()) { 7576 LValue CalleeLV; 7577 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7578 return false; 7579 7580 if (!CalleeLV.getLValueOffset().isZero()) 7581 return Error(Callee); 7582 FD = dyn_cast_or_null<FunctionDecl>( 7583 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7584 if (!FD) 7585 return Error(Callee); 7586 // Don't call function pointers which have been cast to some other type. 7587 // Per DR (no number yet), the caller and callee can differ in noexcept. 7588 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7589 CalleeType->getPointeeType(), FD->getType())) { 7590 return Error(E); 7591 } 7592 7593 // For an (overloaded) assignment expression, evaluate the RHS before the 7594 // LHS. 7595 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7596 if (OCE && OCE->isAssignmentOp()) { 7597 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7598 Call = Info.CurrentCall->createCall(FD); 7599 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7600 Info, FD, /*RightToLeft=*/true)) 7601 return false; 7602 } 7603 7604 // Overloaded operator calls to member functions are represented as normal 7605 // calls with '*this' as the first argument. 7606 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7607 if (MD && !MD->isStatic()) { 7608 // FIXME: When selecting an implicit conversion for an overloaded 7609 // operator delete, we sometimes try to evaluate calls to conversion 7610 // operators without a 'this' parameter! 7611 if (Args.empty()) 7612 return Error(E); 7613 7614 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7615 return false; 7616 This = &ThisVal; 7617 Args = Args.slice(1); 7618 } else if (MD && MD->isLambdaStaticInvoker()) { 7619 // Map the static invoker for the lambda back to the call operator. 7620 // Conveniently, we don't have to slice out the 'this' argument (as is 7621 // being done for the non-static case), since a static member function 7622 // doesn't have an implicit argument passed in. 7623 const CXXRecordDecl *ClosureClass = MD->getParent(); 7624 assert( 7625 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7626 "Number of captures must be zero for conversion to function-ptr"); 7627 7628 const CXXMethodDecl *LambdaCallOp = 7629 ClosureClass->getLambdaCallOperator(); 7630 7631 // Set 'FD', the function that will be called below, to the call 7632 // operator. If the closure object represents a generic lambda, find 7633 // the corresponding specialization of the call operator. 7634 7635 if (ClosureClass->isGenericLambda()) { 7636 assert(MD->isFunctionTemplateSpecialization() && 7637 "A generic lambda's static-invoker function must be a " 7638 "template specialization"); 7639 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7640 FunctionTemplateDecl *CallOpTemplate = 7641 LambdaCallOp->getDescribedFunctionTemplate(); 7642 void *InsertPos = nullptr; 7643 FunctionDecl *CorrespondingCallOpSpecialization = 7644 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7645 assert(CorrespondingCallOpSpecialization && 7646 "We must always have a function call operator specialization " 7647 "that corresponds to our static invoker specialization"); 7648 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7649 } else 7650 FD = LambdaCallOp; 7651 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7652 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7653 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7654 LValue Ptr; 7655 if (!HandleOperatorNewCall(Info, E, Ptr)) 7656 return false; 7657 Ptr.moveInto(Result); 7658 return CallScope.destroy(); 7659 } else { 7660 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7661 } 7662 } 7663 } else 7664 return Error(E); 7665 7666 // Evaluate the arguments now if we've not already done so. 7667 if (!Call) { 7668 Call = Info.CurrentCall->createCall(FD); 7669 if (!EvaluateArgs(Args, Call, Info, FD)) 7670 return false; 7671 } 7672 7673 SmallVector<QualType, 4> CovariantAdjustmentPath; 7674 if (This) { 7675 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7676 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7677 // Perform virtual dispatch, if necessary. 7678 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7679 CovariantAdjustmentPath); 7680 if (!FD) 7681 return false; 7682 } else { 7683 // Check that the 'this' pointer points to an object of the right type. 7684 // FIXME: If this is an assignment operator call, we may need to change 7685 // the active union member before we check this. 7686 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7687 return false; 7688 } 7689 } 7690 7691 // Destructor calls are different enough that they have their own codepath. 7692 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7693 assert(This && "no 'this' pointer for destructor call"); 7694 return HandleDestruction(Info, E, *This, 7695 Info.Ctx.getRecordType(DD->getParent())) && 7696 CallScope.destroy(); 7697 } 7698 7699 const FunctionDecl *Definition = nullptr; 7700 Stmt *Body = FD->getBody(Definition); 7701 7702 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7703 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7704 Body, Info, Result, ResultSlot)) 7705 return false; 7706 7707 if (!CovariantAdjustmentPath.empty() && 7708 !HandleCovariantReturnAdjustment(Info, E, Result, 7709 CovariantAdjustmentPath)) 7710 return false; 7711 7712 return CallScope.destroy(); 7713 } 7714 7715 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7716 return StmtVisitorTy::Visit(E->getInitializer()); 7717 } 7718 bool VisitInitListExpr(const InitListExpr *E) { 7719 if (E->getNumInits() == 0) 7720 return DerivedZeroInitialization(E); 7721 if (E->getNumInits() == 1) 7722 return StmtVisitorTy::Visit(E->getInit(0)); 7723 return Error(E); 7724 } 7725 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7726 return DerivedZeroInitialization(E); 7727 } 7728 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7729 return DerivedZeroInitialization(E); 7730 } 7731 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7732 return DerivedZeroInitialization(E); 7733 } 7734 7735 /// A member expression where the object is a prvalue is itself a prvalue. 7736 bool VisitMemberExpr(const MemberExpr *E) { 7737 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7738 "missing temporary materialization conversion"); 7739 assert(!E->isArrow() && "missing call to bound member function?"); 7740 7741 APValue Val; 7742 if (!Evaluate(Val, Info, E->getBase())) 7743 return false; 7744 7745 QualType BaseTy = E->getBase()->getType(); 7746 7747 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7748 if (!FD) return Error(E); 7749 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7750 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7751 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7752 7753 // Note: there is no lvalue base here. But this case should only ever 7754 // happen in C or in C++98, where we cannot be evaluating a constexpr 7755 // constructor, which is the only case the base matters. 7756 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7757 SubobjectDesignator Designator(BaseTy); 7758 Designator.addDeclUnchecked(FD); 7759 7760 APValue Result; 7761 return extractSubobject(Info, E, Obj, Designator, Result) && 7762 DerivedSuccess(Result, E); 7763 } 7764 7765 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7766 APValue Val; 7767 if (!Evaluate(Val, Info, E->getBase())) 7768 return false; 7769 7770 if (Val.isVector()) { 7771 SmallVector<uint32_t, 4> Indices; 7772 E->getEncodedElementAccess(Indices); 7773 if (Indices.size() == 1) { 7774 // Return scalar. 7775 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7776 } else { 7777 // Construct new APValue vector. 7778 SmallVector<APValue, 4> Elts; 7779 for (unsigned I = 0; I < Indices.size(); ++I) { 7780 Elts.push_back(Val.getVectorElt(Indices[I])); 7781 } 7782 APValue VecResult(Elts.data(), Indices.size()); 7783 return DerivedSuccess(VecResult, E); 7784 } 7785 } 7786 7787 return false; 7788 } 7789 7790 bool VisitCastExpr(const CastExpr *E) { 7791 switch (E->getCastKind()) { 7792 default: 7793 break; 7794 7795 case CK_AtomicToNonAtomic: { 7796 APValue AtomicVal; 7797 // This does not need to be done in place even for class/array types: 7798 // atomic-to-non-atomic conversion implies copying the object 7799 // representation. 7800 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7801 return false; 7802 return DerivedSuccess(AtomicVal, E); 7803 } 7804 7805 case CK_NoOp: 7806 case CK_UserDefinedConversion: 7807 return StmtVisitorTy::Visit(E->getSubExpr()); 7808 7809 case CK_LValueToRValue: { 7810 LValue LVal; 7811 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7812 return false; 7813 APValue RVal; 7814 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7815 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7816 LVal, RVal)) 7817 return false; 7818 return DerivedSuccess(RVal, E); 7819 } 7820 case CK_LValueToRValueBitCast: { 7821 APValue DestValue, SourceValue; 7822 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7823 return false; 7824 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7825 return false; 7826 return DerivedSuccess(DestValue, E); 7827 } 7828 7829 case CK_AddressSpaceConversion: { 7830 APValue Value; 7831 if (!Evaluate(Value, Info, E->getSubExpr())) 7832 return false; 7833 return DerivedSuccess(Value, E); 7834 } 7835 } 7836 7837 return Error(E); 7838 } 7839 7840 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7841 return VisitUnaryPostIncDec(UO); 7842 } 7843 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7844 return VisitUnaryPostIncDec(UO); 7845 } 7846 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7847 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7848 return Error(UO); 7849 7850 LValue LVal; 7851 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7852 return false; 7853 APValue RVal; 7854 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7855 UO->isIncrementOp(), &RVal)) 7856 return false; 7857 return DerivedSuccess(RVal, UO); 7858 } 7859 7860 bool VisitStmtExpr(const StmtExpr *E) { 7861 // We will have checked the full-expressions inside the statement expression 7862 // when they were completed, and don't need to check them again now. 7863 llvm::SaveAndRestore<bool> NotCheckingForUB( 7864 Info.CheckingForUndefinedBehavior, false); 7865 7866 const CompoundStmt *CS = E->getSubStmt(); 7867 if (CS->body_empty()) 7868 return true; 7869 7870 BlockScopeRAII Scope(Info); 7871 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7872 BE = CS->body_end(); 7873 /**/; ++BI) { 7874 if (BI + 1 == BE) { 7875 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7876 if (!FinalExpr) { 7877 Info.FFDiag((*BI)->getBeginLoc(), 7878 diag::note_constexpr_stmt_expr_unsupported); 7879 return false; 7880 } 7881 return this->Visit(FinalExpr) && Scope.destroy(); 7882 } 7883 7884 APValue ReturnValue; 7885 StmtResult Result = { ReturnValue, nullptr }; 7886 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7887 if (ESR != ESR_Succeeded) { 7888 // FIXME: If the statement-expression terminated due to 'return', 7889 // 'break', or 'continue', it would be nice to propagate that to 7890 // the outer statement evaluation rather than bailing out. 7891 if (ESR != ESR_Failed) 7892 Info.FFDiag((*BI)->getBeginLoc(), 7893 diag::note_constexpr_stmt_expr_unsupported); 7894 return false; 7895 } 7896 } 7897 7898 llvm_unreachable("Return from function from the loop above."); 7899 } 7900 7901 /// Visit a value which is evaluated, but whose value is ignored. 7902 void VisitIgnoredValue(const Expr *E) { 7903 EvaluateIgnoredValue(Info, E); 7904 } 7905 7906 /// Potentially visit a MemberExpr's base expression. 7907 void VisitIgnoredBaseExpression(const Expr *E) { 7908 // While MSVC doesn't evaluate the base expression, it does diagnose the 7909 // presence of side-effecting behavior. 7910 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7911 return; 7912 VisitIgnoredValue(E); 7913 } 7914 }; 7915 7916 } // namespace 7917 7918 //===----------------------------------------------------------------------===// 7919 // Common base class for lvalue and temporary evaluation. 7920 //===----------------------------------------------------------------------===// 7921 namespace { 7922 template<class Derived> 7923 class LValueExprEvaluatorBase 7924 : public ExprEvaluatorBase<Derived> { 7925 protected: 7926 LValue &Result; 7927 bool InvalidBaseOK; 7928 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7929 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7930 7931 bool Success(APValue::LValueBase B) { 7932 Result.set(B); 7933 return true; 7934 } 7935 7936 bool evaluatePointer(const Expr *E, LValue &Result) { 7937 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7938 } 7939 7940 public: 7941 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7942 : ExprEvaluatorBaseTy(Info), Result(Result), 7943 InvalidBaseOK(InvalidBaseOK) {} 7944 7945 bool Success(const APValue &V, const Expr *E) { 7946 Result.setFrom(this->Info.Ctx, V); 7947 return true; 7948 } 7949 7950 bool VisitMemberExpr(const MemberExpr *E) { 7951 // Handle non-static data members. 7952 QualType BaseTy; 7953 bool EvalOK; 7954 if (E->isArrow()) { 7955 EvalOK = evaluatePointer(E->getBase(), Result); 7956 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7957 } else if (E->getBase()->isPRValue()) { 7958 assert(E->getBase()->getType()->isRecordType()); 7959 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7960 BaseTy = E->getBase()->getType(); 7961 } else { 7962 EvalOK = this->Visit(E->getBase()); 7963 BaseTy = E->getBase()->getType(); 7964 } 7965 if (!EvalOK) { 7966 if (!InvalidBaseOK) 7967 return false; 7968 Result.setInvalid(E); 7969 return true; 7970 } 7971 7972 const ValueDecl *MD = E->getMemberDecl(); 7973 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7974 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7975 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7976 (void)BaseTy; 7977 if (!HandleLValueMember(this->Info, E, Result, FD)) 7978 return false; 7979 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7980 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7981 return false; 7982 } else 7983 return this->Error(E); 7984 7985 if (MD->getType()->isReferenceType()) { 7986 APValue RefValue; 7987 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7988 RefValue)) 7989 return false; 7990 return Success(RefValue, E); 7991 } 7992 return true; 7993 } 7994 7995 bool VisitBinaryOperator(const BinaryOperator *E) { 7996 switch (E->getOpcode()) { 7997 default: 7998 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7999 8000 case BO_PtrMemD: 8001 case BO_PtrMemI: 8002 return HandleMemberPointerAccess(this->Info, E, Result); 8003 } 8004 } 8005 8006 bool VisitCastExpr(const CastExpr *E) { 8007 switch (E->getCastKind()) { 8008 default: 8009 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8010 8011 case CK_DerivedToBase: 8012 case CK_UncheckedDerivedToBase: 8013 if (!this->Visit(E->getSubExpr())) 8014 return false; 8015 8016 // Now figure out the necessary offset to add to the base LV to get from 8017 // the derived class to the base class. 8018 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8019 Result); 8020 } 8021 } 8022 }; 8023 } 8024 8025 //===----------------------------------------------------------------------===// 8026 // LValue Evaluation 8027 // 8028 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8029 // function designators (in C), decl references to void objects (in C), and 8030 // temporaries (if building with -Wno-address-of-temporary). 8031 // 8032 // LValue evaluation produces values comprising a base expression of one of the 8033 // following types: 8034 // - Declarations 8035 // * VarDecl 8036 // * FunctionDecl 8037 // - Literals 8038 // * CompoundLiteralExpr in C (and in global scope in C++) 8039 // * StringLiteral 8040 // * PredefinedExpr 8041 // * ObjCStringLiteralExpr 8042 // * ObjCEncodeExpr 8043 // * AddrLabelExpr 8044 // * BlockExpr 8045 // * CallExpr for a MakeStringConstant builtin 8046 // - typeid(T) expressions, as TypeInfoLValues 8047 // - Locals and temporaries 8048 // * MaterializeTemporaryExpr 8049 // * Any Expr, with a CallIndex indicating the function in which the temporary 8050 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8051 // from the AST (FIXME). 8052 // * A MaterializeTemporaryExpr that has static storage duration, with no 8053 // CallIndex, for a lifetime-extended temporary. 8054 // * The ConstantExpr that is currently being evaluated during evaluation of an 8055 // immediate invocation. 8056 // plus an offset in bytes. 8057 //===----------------------------------------------------------------------===// 8058 namespace { 8059 class LValueExprEvaluator 8060 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8061 public: 8062 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8063 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8064 8065 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8066 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8067 8068 bool VisitDeclRefExpr(const DeclRefExpr *E); 8069 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8070 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8071 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8072 bool VisitMemberExpr(const MemberExpr *E); 8073 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8074 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8075 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8076 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8077 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8078 bool VisitUnaryDeref(const UnaryOperator *E); 8079 bool VisitUnaryReal(const UnaryOperator *E); 8080 bool VisitUnaryImag(const UnaryOperator *E); 8081 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8082 return VisitUnaryPreIncDec(UO); 8083 } 8084 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8085 return VisitUnaryPreIncDec(UO); 8086 } 8087 bool VisitBinAssign(const BinaryOperator *BO); 8088 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8089 8090 bool VisitCastExpr(const CastExpr *E) { 8091 switch (E->getCastKind()) { 8092 default: 8093 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8094 8095 case CK_LValueBitCast: 8096 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8097 if (!Visit(E->getSubExpr())) 8098 return false; 8099 Result.Designator.setInvalid(); 8100 return true; 8101 8102 case CK_BaseToDerived: 8103 if (!Visit(E->getSubExpr())) 8104 return false; 8105 return HandleBaseToDerivedCast(Info, E, Result); 8106 8107 case CK_Dynamic: 8108 if (!Visit(E->getSubExpr())) 8109 return false; 8110 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8111 } 8112 } 8113 }; 8114 } // end anonymous namespace 8115 8116 /// Evaluate an expression as an lvalue. This can be legitimately called on 8117 /// expressions which are not glvalues, in three cases: 8118 /// * function designators in C, and 8119 /// * "extern void" objects 8120 /// * @selector() expressions in Objective-C 8121 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8122 bool InvalidBaseOK) { 8123 assert(!E->isValueDependent()); 8124 assert(E->isGLValue() || E->getType()->isFunctionType() || 8125 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8126 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8127 } 8128 8129 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8130 const NamedDecl *D = E->getDecl(); 8131 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8132 return Success(cast<ValueDecl>(D)); 8133 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8134 return VisitVarDecl(E, VD); 8135 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8136 return Visit(BD->getBinding()); 8137 return Error(E); 8138 } 8139 8140 8141 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8142 8143 // If we are within a lambda's call operator, check whether the 'VD' referred 8144 // to within 'E' actually represents a lambda-capture that maps to a 8145 // data-member/field within the closure object, and if so, evaluate to the 8146 // field or what the field refers to. 8147 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8148 isa<DeclRefExpr>(E) && 8149 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8150 // We don't always have a complete capture-map when checking or inferring if 8151 // the function call operator meets the requirements of a constexpr function 8152 // - but we don't need to evaluate the captures to determine constexprness 8153 // (dcl.constexpr C++17). 8154 if (Info.checkingPotentialConstantExpression()) 8155 return false; 8156 8157 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8158 // Start with 'Result' referring to the complete closure object... 8159 Result = *Info.CurrentCall->This; 8160 // ... then update it to refer to the field of the closure object 8161 // that represents the capture. 8162 if (!HandleLValueMember(Info, E, Result, FD)) 8163 return false; 8164 // And if the field is of reference type, update 'Result' to refer to what 8165 // the field refers to. 8166 if (FD->getType()->isReferenceType()) { 8167 APValue RVal; 8168 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8169 RVal)) 8170 return false; 8171 Result.setFrom(Info.Ctx, RVal); 8172 } 8173 return true; 8174 } 8175 } 8176 8177 CallStackFrame *Frame = nullptr; 8178 unsigned Version = 0; 8179 if (VD->hasLocalStorage()) { 8180 // Only if a local variable was declared in the function currently being 8181 // evaluated, do we expect to be able to find its value in the current 8182 // frame. (Otherwise it was likely declared in an enclosing context and 8183 // could either have a valid evaluatable value (for e.g. a constexpr 8184 // variable) or be ill-formed (and trigger an appropriate evaluation 8185 // diagnostic)). 8186 CallStackFrame *CurrFrame = Info.CurrentCall; 8187 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8188 // Function parameters are stored in some caller's frame. (Usually the 8189 // immediate caller, but for an inherited constructor they may be more 8190 // distant.) 8191 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8192 if (CurrFrame->Arguments) { 8193 VD = CurrFrame->Arguments.getOrigParam(PVD); 8194 Frame = 8195 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8196 Version = CurrFrame->Arguments.Version; 8197 } 8198 } else { 8199 Frame = CurrFrame; 8200 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8201 } 8202 } 8203 } 8204 8205 if (!VD->getType()->isReferenceType()) { 8206 if (Frame) { 8207 Result.set({VD, Frame->Index, Version}); 8208 return true; 8209 } 8210 return Success(VD); 8211 } 8212 8213 if (!Info.getLangOpts().CPlusPlus11) { 8214 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8215 << VD << VD->getType(); 8216 Info.Note(VD->getLocation(), diag::note_declared_at); 8217 } 8218 8219 APValue *V; 8220 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8221 return false; 8222 if (!V->hasValue()) { 8223 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8224 // adjust the diagnostic to say that. 8225 if (!Info.checkingPotentialConstantExpression()) 8226 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8227 return false; 8228 } 8229 return Success(*V, E); 8230 } 8231 8232 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8233 const MaterializeTemporaryExpr *E) { 8234 // Walk through the expression to find the materialized temporary itself. 8235 SmallVector<const Expr *, 2> CommaLHSs; 8236 SmallVector<SubobjectAdjustment, 2> Adjustments; 8237 const Expr *Inner = 8238 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8239 8240 // If we passed any comma operators, evaluate their LHSs. 8241 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8242 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8243 return false; 8244 8245 // A materialized temporary with static storage duration can appear within the 8246 // result of a constant expression evaluation, so we need to preserve its 8247 // value for use outside this evaluation. 8248 APValue *Value; 8249 if (E->getStorageDuration() == SD_Static) { 8250 // FIXME: What about SD_Thread? 8251 Value = E->getOrCreateValue(true); 8252 *Value = APValue(); 8253 Result.set(E); 8254 } else { 8255 Value = &Info.CurrentCall->createTemporary( 8256 E, E->getType(), 8257 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8258 : ScopeKind::Block, 8259 Result); 8260 } 8261 8262 QualType Type = Inner->getType(); 8263 8264 // Materialize the temporary itself. 8265 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8266 *Value = APValue(); 8267 return false; 8268 } 8269 8270 // Adjust our lvalue to refer to the desired subobject. 8271 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8272 --I; 8273 switch (Adjustments[I].Kind) { 8274 case SubobjectAdjustment::DerivedToBaseAdjustment: 8275 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8276 Type, Result)) 8277 return false; 8278 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8279 break; 8280 8281 case SubobjectAdjustment::FieldAdjustment: 8282 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8283 return false; 8284 Type = Adjustments[I].Field->getType(); 8285 break; 8286 8287 case SubobjectAdjustment::MemberPointerAdjustment: 8288 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8289 Adjustments[I].Ptr.RHS)) 8290 return false; 8291 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8292 break; 8293 } 8294 } 8295 8296 return true; 8297 } 8298 8299 bool 8300 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8301 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8302 "lvalue compound literal in c++?"); 8303 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8304 // only see this when folding in C, so there's no standard to follow here. 8305 return Success(E); 8306 } 8307 8308 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8309 TypeInfoLValue TypeInfo; 8310 8311 if (!E->isPotentiallyEvaluated()) { 8312 if (E->isTypeOperand()) 8313 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8314 else 8315 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8316 } else { 8317 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8318 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8319 << E->getExprOperand()->getType() 8320 << E->getExprOperand()->getSourceRange(); 8321 } 8322 8323 if (!Visit(E->getExprOperand())) 8324 return false; 8325 8326 Optional<DynamicType> DynType = 8327 ComputeDynamicType(Info, E, Result, AK_TypeId); 8328 if (!DynType) 8329 return false; 8330 8331 TypeInfo = 8332 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8333 } 8334 8335 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8336 } 8337 8338 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8339 return Success(E->getGuidDecl()); 8340 } 8341 8342 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8343 // Handle static data members. 8344 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8345 VisitIgnoredBaseExpression(E->getBase()); 8346 return VisitVarDecl(E, VD); 8347 } 8348 8349 // Handle static member functions. 8350 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8351 if (MD->isStatic()) { 8352 VisitIgnoredBaseExpression(E->getBase()); 8353 return Success(MD); 8354 } 8355 } 8356 8357 // Handle non-static data members. 8358 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8359 } 8360 8361 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8362 // FIXME: Deal with vectors as array subscript bases. 8363 if (E->getBase()->getType()->isVectorType()) 8364 return Error(E); 8365 8366 APSInt Index; 8367 bool Success = true; 8368 8369 // C++17's rules require us to evaluate the LHS first, regardless of which 8370 // side is the base. 8371 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8372 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8373 : !EvaluateInteger(SubExpr, Index, Info)) { 8374 if (!Info.noteFailure()) 8375 return false; 8376 Success = false; 8377 } 8378 } 8379 8380 return Success && 8381 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8382 } 8383 8384 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8385 return evaluatePointer(E->getSubExpr(), Result); 8386 } 8387 8388 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8389 if (!Visit(E->getSubExpr())) 8390 return false; 8391 // __real is a no-op on scalar lvalues. 8392 if (E->getSubExpr()->getType()->isAnyComplexType()) 8393 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8394 return true; 8395 } 8396 8397 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8398 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8399 "lvalue __imag__ on scalar?"); 8400 if (!Visit(E->getSubExpr())) 8401 return false; 8402 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8403 return true; 8404 } 8405 8406 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8407 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8408 return Error(UO); 8409 8410 if (!this->Visit(UO->getSubExpr())) 8411 return false; 8412 8413 return handleIncDec( 8414 this->Info, UO, Result, UO->getSubExpr()->getType(), 8415 UO->isIncrementOp(), nullptr); 8416 } 8417 8418 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8419 const CompoundAssignOperator *CAO) { 8420 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8421 return Error(CAO); 8422 8423 bool Success = true; 8424 8425 // C++17 onwards require that we evaluate the RHS first. 8426 APValue RHS; 8427 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8428 if (!Info.noteFailure()) 8429 return false; 8430 Success = false; 8431 } 8432 8433 // The overall lvalue result is the result of evaluating the LHS. 8434 if (!this->Visit(CAO->getLHS()) || !Success) 8435 return false; 8436 8437 return handleCompoundAssignment( 8438 this->Info, CAO, 8439 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8440 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8441 } 8442 8443 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8444 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8445 return Error(E); 8446 8447 bool Success = true; 8448 8449 // C++17 onwards require that we evaluate the RHS first. 8450 APValue NewVal; 8451 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8452 if (!Info.noteFailure()) 8453 return false; 8454 Success = false; 8455 } 8456 8457 if (!this->Visit(E->getLHS()) || !Success) 8458 return false; 8459 8460 if (Info.getLangOpts().CPlusPlus20 && 8461 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8462 return false; 8463 8464 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8465 NewVal); 8466 } 8467 8468 //===----------------------------------------------------------------------===// 8469 // Pointer Evaluation 8470 //===----------------------------------------------------------------------===// 8471 8472 /// Attempts to compute the number of bytes available at the pointer 8473 /// returned by a function with the alloc_size attribute. Returns true if we 8474 /// were successful. Places an unsigned number into `Result`. 8475 /// 8476 /// This expects the given CallExpr to be a call to a function with an 8477 /// alloc_size attribute. 8478 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8479 const CallExpr *Call, 8480 llvm::APInt &Result) { 8481 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8482 8483 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8484 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8485 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8486 if (Call->getNumArgs() <= SizeArgNo) 8487 return false; 8488 8489 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8490 Expr::EvalResult ExprResult; 8491 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8492 return false; 8493 Into = ExprResult.Val.getInt(); 8494 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8495 return false; 8496 Into = Into.zextOrSelf(BitsInSizeT); 8497 return true; 8498 }; 8499 8500 APSInt SizeOfElem; 8501 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8502 return false; 8503 8504 if (!AllocSize->getNumElemsParam().isValid()) { 8505 Result = std::move(SizeOfElem); 8506 return true; 8507 } 8508 8509 APSInt NumberOfElems; 8510 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8511 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8512 return false; 8513 8514 bool Overflow; 8515 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8516 if (Overflow) 8517 return false; 8518 8519 Result = std::move(BytesAvailable); 8520 return true; 8521 } 8522 8523 /// Convenience function. LVal's base must be a call to an alloc_size 8524 /// function. 8525 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8526 const LValue &LVal, 8527 llvm::APInt &Result) { 8528 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8529 "Can't get the size of a non alloc_size function"); 8530 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8531 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8532 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8533 } 8534 8535 /// Attempts to evaluate the given LValueBase as the result of a call to 8536 /// a function with the alloc_size attribute. If it was possible to do so, this 8537 /// function will return true, make Result's Base point to said function call, 8538 /// and mark Result's Base as invalid. 8539 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8540 LValue &Result) { 8541 if (Base.isNull()) 8542 return false; 8543 8544 // Because we do no form of static analysis, we only support const variables. 8545 // 8546 // Additionally, we can't support parameters, nor can we support static 8547 // variables (in the latter case, use-before-assign isn't UB; in the former, 8548 // we have no clue what they'll be assigned to). 8549 const auto *VD = 8550 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8551 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8552 return false; 8553 8554 const Expr *Init = VD->getAnyInitializer(); 8555 if (!Init) 8556 return false; 8557 8558 const Expr *E = Init->IgnoreParens(); 8559 if (!tryUnwrapAllocSizeCall(E)) 8560 return false; 8561 8562 // Store E instead of E unwrapped so that the type of the LValue's base is 8563 // what the user wanted. 8564 Result.setInvalid(E); 8565 8566 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8567 Result.addUnsizedArray(Info, E, Pointee); 8568 return true; 8569 } 8570 8571 namespace { 8572 class PointerExprEvaluator 8573 : public ExprEvaluatorBase<PointerExprEvaluator> { 8574 LValue &Result; 8575 bool InvalidBaseOK; 8576 8577 bool Success(const Expr *E) { 8578 Result.set(E); 8579 return true; 8580 } 8581 8582 bool evaluateLValue(const Expr *E, LValue &Result) { 8583 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8584 } 8585 8586 bool evaluatePointer(const Expr *E, LValue &Result) { 8587 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8588 } 8589 8590 bool visitNonBuiltinCallExpr(const CallExpr *E); 8591 public: 8592 8593 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8594 : ExprEvaluatorBaseTy(info), Result(Result), 8595 InvalidBaseOK(InvalidBaseOK) {} 8596 8597 bool Success(const APValue &V, const Expr *E) { 8598 Result.setFrom(Info.Ctx, V); 8599 return true; 8600 } 8601 bool ZeroInitialization(const Expr *E) { 8602 Result.setNull(Info.Ctx, E->getType()); 8603 return true; 8604 } 8605 8606 bool VisitBinaryOperator(const BinaryOperator *E); 8607 bool VisitCastExpr(const CastExpr* E); 8608 bool VisitUnaryAddrOf(const UnaryOperator *E); 8609 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8610 { return Success(E); } 8611 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8612 if (E->isExpressibleAsConstantInitializer()) 8613 return Success(E); 8614 if (Info.noteFailure()) 8615 EvaluateIgnoredValue(Info, E->getSubExpr()); 8616 return Error(E); 8617 } 8618 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8619 { return Success(E); } 8620 bool VisitCallExpr(const CallExpr *E); 8621 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8622 bool VisitBlockExpr(const BlockExpr *E) { 8623 if (!E->getBlockDecl()->hasCaptures()) 8624 return Success(E); 8625 return Error(E); 8626 } 8627 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8628 // Can't look at 'this' when checking a potential constant expression. 8629 if (Info.checkingPotentialConstantExpression()) 8630 return false; 8631 if (!Info.CurrentCall->This) { 8632 if (Info.getLangOpts().CPlusPlus11) 8633 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8634 else 8635 Info.FFDiag(E); 8636 return false; 8637 } 8638 Result = *Info.CurrentCall->This; 8639 // If we are inside a lambda's call operator, the 'this' expression refers 8640 // to the enclosing '*this' object (either by value or reference) which is 8641 // either copied into the closure object's field that represents the '*this' 8642 // or refers to '*this'. 8643 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8644 // Ensure we actually have captured 'this'. (an error will have 8645 // been previously reported if not). 8646 if (!Info.CurrentCall->LambdaThisCaptureField) 8647 return false; 8648 8649 // Update 'Result' to refer to the data member/field of the closure object 8650 // that represents the '*this' capture. 8651 if (!HandleLValueMember(Info, E, Result, 8652 Info.CurrentCall->LambdaThisCaptureField)) 8653 return false; 8654 // If we captured '*this' by reference, replace the field with its referent. 8655 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8656 ->isPointerType()) { 8657 APValue RVal; 8658 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8659 RVal)) 8660 return false; 8661 8662 Result.setFrom(Info.Ctx, RVal); 8663 } 8664 } 8665 return true; 8666 } 8667 8668 bool VisitCXXNewExpr(const CXXNewExpr *E); 8669 8670 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8671 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8672 APValue LValResult = E->EvaluateInContext( 8673 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8674 Result.setFrom(Info.Ctx, LValResult); 8675 return true; 8676 } 8677 8678 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8679 std::string ResultStr = E->ComputeName(Info.Ctx); 8680 8681 QualType CharTy = Info.Ctx.CharTy.withConst(); 8682 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8683 ResultStr.size() + 1); 8684 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8685 ArrayType::Normal, 0); 8686 8687 StringLiteral *SL = 8688 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8689 /*Pascal*/ false, ArrayTy, E->getLocation()); 8690 8691 evaluateLValue(SL, Result); 8692 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8693 return true; 8694 } 8695 8696 // FIXME: Missing: @protocol, @selector 8697 }; 8698 } // end anonymous namespace 8699 8700 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8701 bool InvalidBaseOK) { 8702 assert(!E->isValueDependent()); 8703 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8704 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8705 } 8706 8707 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8708 if (E->getOpcode() != BO_Add && 8709 E->getOpcode() != BO_Sub) 8710 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8711 8712 const Expr *PExp = E->getLHS(); 8713 const Expr *IExp = E->getRHS(); 8714 if (IExp->getType()->isPointerType()) 8715 std::swap(PExp, IExp); 8716 8717 bool EvalPtrOK = evaluatePointer(PExp, Result); 8718 if (!EvalPtrOK && !Info.noteFailure()) 8719 return false; 8720 8721 llvm::APSInt Offset; 8722 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8723 return false; 8724 8725 if (E->getOpcode() == BO_Sub) 8726 negateAsSigned(Offset); 8727 8728 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8729 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8730 } 8731 8732 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8733 return evaluateLValue(E->getSubExpr(), Result); 8734 } 8735 8736 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8737 const Expr *SubExpr = E->getSubExpr(); 8738 8739 switch (E->getCastKind()) { 8740 default: 8741 break; 8742 case CK_BitCast: 8743 case CK_CPointerToObjCPointerCast: 8744 case CK_BlockPointerToObjCPointerCast: 8745 case CK_AnyPointerToBlockPointerCast: 8746 case CK_AddressSpaceConversion: 8747 if (!Visit(SubExpr)) 8748 return false; 8749 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8750 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8751 // also static_casts, but we disallow them as a resolution to DR1312. 8752 if (!E->getType()->isVoidPointerType()) { 8753 if (!Result.InvalidBase && !Result.Designator.Invalid && 8754 !Result.IsNullPtr && 8755 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8756 E->getType()->getPointeeType()) && 8757 Info.getStdAllocatorCaller("allocate")) { 8758 // Inside a call to std::allocator::allocate and friends, we permit 8759 // casting from void* back to cv1 T* for a pointer that points to a 8760 // cv2 T. 8761 } else { 8762 Result.Designator.setInvalid(); 8763 if (SubExpr->getType()->isVoidPointerType()) 8764 CCEDiag(E, diag::note_constexpr_invalid_cast) 8765 << 3 << SubExpr->getType(); 8766 else 8767 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8768 } 8769 } 8770 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8771 ZeroInitialization(E); 8772 return true; 8773 8774 case CK_DerivedToBase: 8775 case CK_UncheckedDerivedToBase: 8776 if (!evaluatePointer(E->getSubExpr(), Result)) 8777 return false; 8778 if (!Result.Base && Result.Offset.isZero()) 8779 return true; 8780 8781 // Now figure out the necessary offset to add to the base LV to get from 8782 // the derived class to the base class. 8783 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8784 castAs<PointerType>()->getPointeeType(), 8785 Result); 8786 8787 case CK_BaseToDerived: 8788 if (!Visit(E->getSubExpr())) 8789 return false; 8790 if (!Result.Base && Result.Offset.isZero()) 8791 return true; 8792 return HandleBaseToDerivedCast(Info, E, Result); 8793 8794 case CK_Dynamic: 8795 if (!Visit(E->getSubExpr())) 8796 return false; 8797 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8798 8799 case CK_NullToPointer: 8800 VisitIgnoredValue(E->getSubExpr()); 8801 return ZeroInitialization(E); 8802 8803 case CK_IntegralToPointer: { 8804 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8805 8806 APValue Value; 8807 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8808 break; 8809 8810 if (Value.isInt()) { 8811 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8812 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8813 Result.Base = (Expr*)nullptr; 8814 Result.InvalidBase = false; 8815 Result.Offset = CharUnits::fromQuantity(N); 8816 Result.Designator.setInvalid(); 8817 Result.IsNullPtr = false; 8818 return true; 8819 } else { 8820 // Cast is of an lvalue, no need to change value. 8821 Result.setFrom(Info.Ctx, Value); 8822 return true; 8823 } 8824 } 8825 8826 case CK_ArrayToPointerDecay: { 8827 if (SubExpr->isGLValue()) { 8828 if (!evaluateLValue(SubExpr, Result)) 8829 return false; 8830 } else { 8831 APValue &Value = Info.CurrentCall->createTemporary( 8832 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8833 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8834 return false; 8835 } 8836 // The result is a pointer to the first element of the array. 8837 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8838 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8839 Result.addArray(Info, E, CAT); 8840 else 8841 Result.addUnsizedArray(Info, E, AT->getElementType()); 8842 return true; 8843 } 8844 8845 case CK_FunctionToPointerDecay: 8846 return evaluateLValue(SubExpr, Result); 8847 8848 case CK_LValueToRValue: { 8849 LValue LVal; 8850 if (!evaluateLValue(E->getSubExpr(), LVal)) 8851 return false; 8852 8853 APValue RVal; 8854 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8855 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8856 LVal, RVal)) 8857 return InvalidBaseOK && 8858 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8859 return Success(RVal, E); 8860 } 8861 } 8862 8863 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8864 } 8865 8866 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8867 UnaryExprOrTypeTrait ExprKind) { 8868 // C++ [expr.alignof]p3: 8869 // When alignof is applied to a reference type, the result is the 8870 // alignment of the referenced type. 8871 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8872 T = Ref->getPointeeType(); 8873 8874 if (T.getQualifiers().hasUnaligned()) 8875 return CharUnits::One(); 8876 8877 const bool AlignOfReturnsPreferred = 8878 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8879 8880 // __alignof is defined to return the preferred alignment. 8881 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8882 // as well. 8883 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8884 return Info.Ctx.toCharUnitsFromBits( 8885 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8886 // alignof and _Alignof are defined to return the ABI alignment. 8887 else if (ExprKind == UETT_AlignOf) 8888 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8889 else 8890 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8891 } 8892 8893 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8894 UnaryExprOrTypeTrait ExprKind) { 8895 E = E->IgnoreParens(); 8896 8897 // The kinds of expressions that we have special-case logic here for 8898 // should be kept up to date with the special checks for those 8899 // expressions in Sema. 8900 8901 // alignof decl is always accepted, even if it doesn't make sense: we default 8902 // to 1 in those cases. 8903 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8904 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8905 /*RefAsPointee*/true); 8906 8907 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8908 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8909 /*RefAsPointee*/true); 8910 8911 return GetAlignOfType(Info, E->getType(), ExprKind); 8912 } 8913 8914 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8915 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8916 return Info.Ctx.getDeclAlign(VD); 8917 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8918 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8919 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8920 } 8921 8922 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8923 /// __builtin_is_aligned and __builtin_assume_aligned. 8924 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8925 EvalInfo &Info, APSInt &Alignment) { 8926 if (!EvaluateInteger(E, Alignment, Info)) 8927 return false; 8928 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8929 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8930 return false; 8931 } 8932 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8933 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8934 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8935 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8936 << MaxValue << ForType << Alignment; 8937 return false; 8938 } 8939 // Ensure both alignment and source value have the same bit width so that we 8940 // don't assert when computing the resulting value. 8941 APSInt ExtAlignment = 8942 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8943 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8944 "Alignment should not be changed by ext/trunc"); 8945 Alignment = ExtAlignment; 8946 assert(Alignment.getBitWidth() == SrcWidth); 8947 return true; 8948 } 8949 8950 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8951 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8952 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8953 return true; 8954 8955 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8956 return false; 8957 8958 Result.setInvalid(E); 8959 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8960 Result.addUnsizedArray(Info, E, PointeeTy); 8961 return true; 8962 } 8963 8964 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8965 if (IsStringLiteralCall(E)) 8966 return Success(E); 8967 8968 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8969 return VisitBuiltinCallExpr(E, BuiltinOp); 8970 8971 return visitNonBuiltinCallExpr(E); 8972 } 8973 8974 // Determine if T is a character type for which we guarantee that 8975 // sizeof(T) == 1. 8976 static bool isOneByteCharacterType(QualType T) { 8977 return T->isCharType() || T->isChar8Type(); 8978 } 8979 8980 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8981 unsigned BuiltinOp) { 8982 switch (BuiltinOp) { 8983 case Builtin::BI__builtin_addressof: 8984 return evaluateLValue(E->getArg(0), Result); 8985 case Builtin::BI__builtin_assume_aligned: { 8986 // We need to be very careful here because: if the pointer does not have the 8987 // asserted alignment, then the behavior is undefined, and undefined 8988 // behavior is non-constant. 8989 if (!evaluatePointer(E->getArg(0), Result)) 8990 return false; 8991 8992 LValue OffsetResult(Result); 8993 APSInt Alignment; 8994 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8995 Alignment)) 8996 return false; 8997 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8998 8999 if (E->getNumArgs() > 2) { 9000 APSInt Offset; 9001 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9002 return false; 9003 9004 int64_t AdditionalOffset = -Offset.getZExtValue(); 9005 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9006 } 9007 9008 // If there is a base object, then it must have the correct alignment. 9009 if (OffsetResult.Base) { 9010 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9011 9012 if (BaseAlignment < Align) { 9013 Result.Designator.setInvalid(); 9014 // FIXME: Add support to Diagnostic for long / long long. 9015 CCEDiag(E->getArg(0), 9016 diag::note_constexpr_baa_insufficient_alignment) << 0 9017 << (unsigned)BaseAlignment.getQuantity() 9018 << (unsigned)Align.getQuantity(); 9019 return false; 9020 } 9021 } 9022 9023 // The offset must also have the correct alignment. 9024 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9025 Result.Designator.setInvalid(); 9026 9027 (OffsetResult.Base 9028 ? CCEDiag(E->getArg(0), 9029 diag::note_constexpr_baa_insufficient_alignment) << 1 9030 : CCEDiag(E->getArg(0), 9031 diag::note_constexpr_baa_value_insufficient_alignment)) 9032 << (int)OffsetResult.Offset.getQuantity() 9033 << (unsigned)Align.getQuantity(); 9034 return false; 9035 } 9036 9037 return true; 9038 } 9039 case Builtin::BI__builtin_align_up: 9040 case Builtin::BI__builtin_align_down: { 9041 if (!evaluatePointer(E->getArg(0), Result)) 9042 return false; 9043 APSInt Alignment; 9044 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9045 Alignment)) 9046 return false; 9047 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9048 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9049 // For align_up/align_down, we can return the same value if the alignment 9050 // is known to be greater or equal to the requested value. 9051 if (PtrAlign.getQuantity() >= Alignment) 9052 return true; 9053 9054 // The alignment could be greater than the minimum at run-time, so we cannot 9055 // infer much about the resulting pointer value. One case is possible: 9056 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9057 // can infer the correct index if the requested alignment is smaller than 9058 // the base alignment so we can perform the computation on the offset. 9059 if (BaseAlignment.getQuantity() >= Alignment) { 9060 assert(Alignment.getBitWidth() <= 64 && 9061 "Cannot handle > 64-bit address-space"); 9062 uint64_t Alignment64 = Alignment.getZExtValue(); 9063 CharUnits NewOffset = CharUnits::fromQuantity( 9064 BuiltinOp == Builtin::BI__builtin_align_down 9065 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9066 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9067 Result.adjustOffset(NewOffset - Result.Offset); 9068 // TODO: diagnose out-of-bounds values/only allow for arrays? 9069 return true; 9070 } 9071 // Otherwise, we cannot constant-evaluate the result. 9072 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9073 << Alignment; 9074 return false; 9075 } 9076 case Builtin::BI__builtin_operator_new: 9077 return HandleOperatorNewCall(Info, E, Result); 9078 case Builtin::BI__builtin_launder: 9079 return evaluatePointer(E->getArg(0), Result); 9080 case Builtin::BIstrchr: 9081 case Builtin::BIwcschr: 9082 case Builtin::BImemchr: 9083 case Builtin::BIwmemchr: 9084 if (Info.getLangOpts().CPlusPlus11) 9085 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9086 << /*isConstexpr*/0 << /*isConstructor*/0 9087 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9088 else 9089 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9090 LLVM_FALLTHROUGH; 9091 case Builtin::BI__builtin_strchr: 9092 case Builtin::BI__builtin_wcschr: 9093 case Builtin::BI__builtin_memchr: 9094 case Builtin::BI__builtin_char_memchr: 9095 case Builtin::BI__builtin_wmemchr: { 9096 if (!Visit(E->getArg(0))) 9097 return false; 9098 APSInt Desired; 9099 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9100 return false; 9101 uint64_t MaxLength = uint64_t(-1); 9102 if (BuiltinOp != Builtin::BIstrchr && 9103 BuiltinOp != Builtin::BIwcschr && 9104 BuiltinOp != Builtin::BI__builtin_strchr && 9105 BuiltinOp != Builtin::BI__builtin_wcschr) { 9106 APSInt N; 9107 if (!EvaluateInteger(E->getArg(2), N, Info)) 9108 return false; 9109 MaxLength = N.getExtValue(); 9110 } 9111 // We cannot find the value if there are no candidates to match against. 9112 if (MaxLength == 0u) 9113 return ZeroInitialization(E); 9114 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9115 Result.Designator.Invalid) 9116 return false; 9117 QualType CharTy = Result.Designator.getType(Info.Ctx); 9118 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9119 BuiltinOp == Builtin::BI__builtin_memchr; 9120 assert(IsRawByte || 9121 Info.Ctx.hasSameUnqualifiedType( 9122 CharTy, E->getArg(0)->getType()->getPointeeType())); 9123 // Pointers to const void may point to objects of incomplete type. 9124 if (IsRawByte && CharTy->isIncompleteType()) { 9125 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9126 return false; 9127 } 9128 // Give up on byte-oriented matching against multibyte elements. 9129 // FIXME: We can compare the bytes in the correct order. 9130 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9131 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9132 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9133 << CharTy; 9134 return false; 9135 } 9136 // Figure out what value we're actually looking for (after converting to 9137 // the corresponding unsigned type if necessary). 9138 uint64_t DesiredVal; 9139 bool StopAtNull = false; 9140 switch (BuiltinOp) { 9141 case Builtin::BIstrchr: 9142 case Builtin::BI__builtin_strchr: 9143 // strchr compares directly to the passed integer, and therefore 9144 // always fails if given an int that is not a char. 9145 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9146 E->getArg(1)->getType(), 9147 Desired), 9148 Desired)) 9149 return ZeroInitialization(E); 9150 StopAtNull = true; 9151 LLVM_FALLTHROUGH; 9152 case Builtin::BImemchr: 9153 case Builtin::BI__builtin_memchr: 9154 case Builtin::BI__builtin_char_memchr: 9155 // memchr compares by converting both sides to unsigned char. That's also 9156 // correct for strchr if we get this far (to cope with plain char being 9157 // unsigned in the strchr case). 9158 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9159 break; 9160 9161 case Builtin::BIwcschr: 9162 case Builtin::BI__builtin_wcschr: 9163 StopAtNull = true; 9164 LLVM_FALLTHROUGH; 9165 case Builtin::BIwmemchr: 9166 case Builtin::BI__builtin_wmemchr: 9167 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9168 DesiredVal = Desired.getZExtValue(); 9169 break; 9170 } 9171 9172 for (; MaxLength; --MaxLength) { 9173 APValue Char; 9174 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9175 !Char.isInt()) 9176 return false; 9177 if (Char.getInt().getZExtValue() == DesiredVal) 9178 return true; 9179 if (StopAtNull && !Char.getInt()) 9180 break; 9181 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9182 return false; 9183 } 9184 // Not found: return nullptr. 9185 return ZeroInitialization(E); 9186 } 9187 9188 case Builtin::BImemcpy: 9189 case Builtin::BImemmove: 9190 case Builtin::BIwmemcpy: 9191 case Builtin::BIwmemmove: 9192 if (Info.getLangOpts().CPlusPlus11) 9193 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9194 << /*isConstexpr*/0 << /*isConstructor*/0 9195 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9196 else 9197 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9198 LLVM_FALLTHROUGH; 9199 case Builtin::BI__builtin_memcpy: 9200 case Builtin::BI__builtin_memmove: 9201 case Builtin::BI__builtin_wmemcpy: 9202 case Builtin::BI__builtin_wmemmove: { 9203 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9204 BuiltinOp == Builtin::BIwmemmove || 9205 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9206 BuiltinOp == Builtin::BI__builtin_wmemmove; 9207 bool Move = BuiltinOp == Builtin::BImemmove || 9208 BuiltinOp == Builtin::BIwmemmove || 9209 BuiltinOp == Builtin::BI__builtin_memmove || 9210 BuiltinOp == Builtin::BI__builtin_wmemmove; 9211 9212 // The result of mem* is the first argument. 9213 if (!Visit(E->getArg(0))) 9214 return false; 9215 LValue Dest = Result; 9216 9217 LValue Src; 9218 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9219 return false; 9220 9221 APSInt N; 9222 if (!EvaluateInteger(E->getArg(2), N, Info)) 9223 return false; 9224 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9225 9226 // If the size is zero, we treat this as always being a valid no-op. 9227 // (Even if one of the src and dest pointers is null.) 9228 if (!N) 9229 return true; 9230 9231 // Otherwise, if either of the operands is null, we can't proceed. Don't 9232 // try to determine the type of the copied objects, because there aren't 9233 // any. 9234 if (!Src.Base || !Dest.Base) { 9235 APValue Val; 9236 (!Src.Base ? Src : Dest).moveInto(Val); 9237 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9238 << Move << WChar << !!Src.Base 9239 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9240 return false; 9241 } 9242 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9243 return false; 9244 9245 // We require that Src and Dest are both pointers to arrays of 9246 // trivially-copyable type. (For the wide version, the designator will be 9247 // invalid if the designated object is not a wchar_t.) 9248 QualType T = Dest.Designator.getType(Info.Ctx); 9249 QualType SrcT = Src.Designator.getType(Info.Ctx); 9250 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9251 // FIXME: Consider using our bit_cast implementation to support this. 9252 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9253 return false; 9254 } 9255 if (T->isIncompleteType()) { 9256 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9257 return false; 9258 } 9259 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9260 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9261 return false; 9262 } 9263 9264 // Figure out how many T's we're copying. 9265 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9266 if (!WChar) { 9267 uint64_t Remainder; 9268 llvm::APInt OrigN = N; 9269 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9270 if (Remainder) { 9271 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9272 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9273 << (unsigned)TSize; 9274 return false; 9275 } 9276 } 9277 9278 // Check that the copying will remain within the arrays, just so that we 9279 // can give a more meaningful diagnostic. This implicitly also checks that 9280 // N fits into 64 bits. 9281 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9282 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9283 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9284 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9285 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9286 << toString(N, 10, /*Signed*/false); 9287 return false; 9288 } 9289 uint64_t NElems = N.getZExtValue(); 9290 uint64_t NBytes = NElems * TSize; 9291 9292 // Check for overlap. 9293 int Direction = 1; 9294 if (HasSameBase(Src, Dest)) { 9295 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9296 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9297 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9298 // Dest is inside the source region. 9299 if (!Move) { 9300 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9301 return false; 9302 } 9303 // For memmove and friends, copy backwards. 9304 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9305 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9306 return false; 9307 Direction = -1; 9308 } else if (!Move && SrcOffset >= DestOffset && 9309 SrcOffset - DestOffset < NBytes) { 9310 // Src is inside the destination region for memcpy: invalid. 9311 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9312 return false; 9313 } 9314 } 9315 9316 while (true) { 9317 APValue Val; 9318 // FIXME: Set WantObjectRepresentation to true if we're copying a 9319 // char-like type? 9320 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9321 !handleAssignment(Info, E, Dest, T, Val)) 9322 return false; 9323 // Do not iterate past the last element; if we're copying backwards, that 9324 // might take us off the start of the array. 9325 if (--NElems == 0) 9326 return true; 9327 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9328 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9329 return false; 9330 } 9331 } 9332 9333 default: 9334 break; 9335 } 9336 9337 return visitNonBuiltinCallExpr(E); 9338 } 9339 9340 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9341 APValue &Result, const InitListExpr *ILE, 9342 QualType AllocType); 9343 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9344 APValue &Result, 9345 const CXXConstructExpr *CCE, 9346 QualType AllocType); 9347 9348 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9349 if (!Info.getLangOpts().CPlusPlus20) 9350 Info.CCEDiag(E, diag::note_constexpr_new); 9351 9352 // We cannot speculatively evaluate a delete expression. 9353 if (Info.SpeculativeEvaluationDepth) 9354 return false; 9355 9356 FunctionDecl *OperatorNew = E->getOperatorNew(); 9357 9358 bool IsNothrow = false; 9359 bool IsPlacement = false; 9360 if (OperatorNew->isReservedGlobalPlacementOperator() && 9361 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9362 // FIXME Support array placement new. 9363 assert(E->getNumPlacementArgs() == 1); 9364 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9365 return false; 9366 if (Result.Designator.Invalid) 9367 return false; 9368 IsPlacement = true; 9369 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9370 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9371 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9372 return false; 9373 } else if (E->getNumPlacementArgs()) { 9374 // The only new-placement list we support is of the form (std::nothrow). 9375 // 9376 // FIXME: There is no restriction on this, but it's not clear that any 9377 // other form makes any sense. We get here for cases such as: 9378 // 9379 // new (std::align_val_t{N}) X(int) 9380 // 9381 // (which should presumably be valid only if N is a multiple of 9382 // alignof(int), and in any case can't be deallocated unless N is 9383 // alignof(X) and X has new-extended alignment). 9384 if (E->getNumPlacementArgs() != 1 || 9385 !E->getPlacementArg(0)->getType()->isNothrowT()) 9386 return Error(E, diag::note_constexpr_new_placement); 9387 9388 LValue Nothrow; 9389 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9390 return false; 9391 IsNothrow = true; 9392 } 9393 9394 const Expr *Init = E->getInitializer(); 9395 const InitListExpr *ResizedArrayILE = nullptr; 9396 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9397 bool ValueInit = false; 9398 9399 QualType AllocType = E->getAllocatedType(); 9400 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9401 const Expr *Stripped = *ArraySize; 9402 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9403 Stripped = ICE->getSubExpr()) 9404 if (ICE->getCastKind() != CK_NoOp && 9405 ICE->getCastKind() != CK_IntegralCast) 9406 break; 9407 9408 llvm::APSInt ArrayBound; 9409 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9410 return false; 9411 9412 // C++ [expr.new]p9: 9413 // The expression is erroneous if: 9414 // -- [...] its value before converting to size_t [or] applying the 9415 // second standard conversion sequence is less than zero 9416 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9417 if (IsNothrow) 9418 return ZeroInitialization(E); 9419 9420 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9421 << ArrayBound << (*ArraySize)->getSourceRange(); 9422 return false; 9423 } 9424 9425 // -- its value is such that the size of the allocated object would 9426 // exceed the implementation-defined limit 9427 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9428 ArrayBound) > 9429 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9430 if (IsNothrow) 9431 return ZeroInitialization(E); 9432 9433 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9434 << ArrayBound << (*ArraySize)->getSourceRange(); 9435 return false; 9436 } 9437 9438 // -- the new-initializer is a braced-init-list and the number of 9439 // array elements for which initializers are provided [...] 9440 // exceeds the number of elements to initialize 9441 if (!Init) { 9442 // No initialization is performed. 9443 } else if (isa<CXXScalarValueInitExpr>(Init) || 9444 isa<ImplicitValueInitExpr>(Init)) { 9445 ValueInit = true; 9446 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9447 ResizedArrayCCE = CCE; 9448 } else { 9449 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9450 assert(CAT && "unexpected type for array initializer"); 9451 9452 unsigned Bits = 9453 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9454 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9455 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9456 if (InitBound.ugt(AllocBound)) { 9457 if (IsNothrow) 9458 return ZeroInitialization(E); 9459 9460 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9461 << toString(AllocBound, 10, /*Signed=*/false) 9462 << toString(InitBound, 10, /*Signed=*/false) 9463 << (*ArraySize)->getSourceRange(); 9464 return false; 9465 } 9466 9467 // If the sizes differ, we must have an initializer list, and we need 9468 // special handling for this case when we initialize. 9469 if (InitBound != AllocBound) 9470 ResizedArrayILE = cast<InitListExpr>(Init); 9471 } 9472 9473 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9474 ArrayType::Normal, 0); 9475 } else { 9476 assert(!AllocType->isArrayType() && 9477 "array allocation with non-array new"); 9478 } 9479 9480 APValue *Val; 9481 if (IsPlacement) { 9482 AccessKinds AK = AK_Construct; 9483 struct FindObjectHandler { 9484 EvalInfo &Info; 9485 const Expr *E; 9486 QualType AllocType; 9487 const AccessKinds AccessKind; 9488 APValue *Value; 9489 9490 typedef bool result_type; 9491 bool failed() { return false; } 9492 bool found(APValue &Subobj, QualType SubobjType) { 9493 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9494 // old name of the object to be used to name the new object. 9495 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9496 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9497 SubobjType << AllocType; 9498 return false; 9499 } 9500 Value = &Subobj; 9501 return true; 9502 } 9503 bool found(APSInt &Value, QualType SubobjType) { 9504 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9505 return false; 9506 } 9507 bool found(APFloat &Value, QualType SubobjType) { 9508 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9509 return false; 9510 } 9511 } Handler = {Info, E, AllocType, AK, nullptr}; 9512 9513 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9514 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9515 return false; 9516 9517 Val = Handler.Value; 9518 9519 // [basic.life]p1: 9520 // The lifetime of an object o of type T ends when [...] the storage 9521 // which the object occupies is [...] reused by an object that is not 9522 // nested within o (6.6.2). 9523 *Val = APValue(); 9524 } else { 9525 // Perform the allocation and obtain a pointer to the resulting object. 9526 Val = Info.createHeapAlloc(E, AllocType, Result); 9527 if (!Val) 9528 return false; 9529 } 9530 9531 if (ValueInit) { 9532 ImplicitValueInitExpr VIE(AllocType); 9533 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9534 return false; 9535 } else if (ResizedArrayILE) { 9536 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9537 AllocType)) 9538 return false; 9539 } else if (ResizedArrayCCE) { 9540 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9541 AllocType)) 9542 return false; 9543 } else if (Init) { 9544 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9545 return false; 9546 } else if (!getDefaultInitValue(AllocType, *Val)) { 9547 return false; 9548 } 9549 9550 // Array new returns a pointer to the first element, not a pointer to the 9551 // array. 9552 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9553 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9554 9555 return true; 9556 } 9557 //===----------------------------------------------------------------------===// 9558 // Member Pointer Evaluation 9559 //===----------------------------------------------------------------------===// 9560 9561 namespace { 9562 class MemberPointerExprEvaluator 9563 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9564 MemberPtr &Result; 9565 9566 bool Success(const ValueDecl *D) { 9567 Result = MemberPtr(D); 9568 return true; 9569 } 9570 public: 9571 9572 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9573 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9574 9575 bool Success(const APValue &V, const Expr *E) { 9576 Result.setFrom(V); 9577 return true; 9578 } 9579 bool ZeroInitialization(const Expr *E) { 9580 return Success((const ValueDecl*)nullptr); 9581 } 9582 9583 bool VisitCastExpr(const CastExpr *E); 9584 bool VisitUnaryAddrOf(const UnaryOperator *E); 9585 }; 9586 } // end anonymous namespace 9587 9588 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9589 EvalInfo &Info) { 9590 assert(!E->isValueDependent()); 9591 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9592 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9593 } 9594 9595 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9596 switch (E->getCastKind()) { 9597 default: 9598 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9599 9600 case CK_NullToMemberPointer: 9601 VisitIgnoredValue(E->getSubExpr()); 9602 return ZeroInitialization(E); 9603 9604 case CK_BaseToDerivedMemberPointer: { 9605 if (!Visit(E->getSubExpr())) 9606 return false; 9607 if (E->path_empty()) 9608 return true; 9609 // Base-to-derived member pointer casts store the path in derived-to-base 9610 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9611 // the wrong end of the derived->base arc, so stagger the path by one class. 9612 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9613 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9614 PathI != PathE; ++PathI) { 9615 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9616 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9617 if (!Result.castToDerived(Derived)) 9618 return Error(E); 9619 } 9620 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9621 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9622 return Error(E); 9623 return true; 9624 } 9625 9626 case CK_DerivedToBaseMemberPointer: 9627 if (!Visit(E->getSubExpr())) 9628 return false; 9629 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9630 PathE = E->path_end(); PathI != PathE; ++PathI) { 9631 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9632 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9633 if (!Result.castToBase(Base)) 9634 return Error(E); 9635 } 9636 return true; 9637 } 9638 } 9639 9640 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9641 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9642 // member can be formed. 9643 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9644 } 9645 9646 //===----------------------------------------------------------------------===// 9647 // Record Evaluation 9648 //===----------------------------------------------------------------------===// 9649 9650 namespace { 9651 class RecordExprEvaluator 9652 : public ExprEvaluatorBase<RecordExprEvaluator> { 9653 const LValue &This; 9654 APValue &Result; 9655 public: 9656 9657 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9658 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9659 9660 bool Success(const APValue &V, const Expr *E) { 9661 Result = V; 9662 return true; 9663 } 9664 bool ZeroInitialization(const Expr *E) { 9665 return ZeroInitialization(E, E->getType()); 9666 } 9667 bool ZeroInitialization(const Expr *E, QualType T); 9668 9669 bool VisitCallExpr(const CallExpr *E) { 9670 return handleCallExpr(E, Result, &This); 9671 } 9672 bool VisitCastExpr(const CastExpr *E); 9673 bool VisitInitListExpr(const InitListExpr *E); 9674 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9675 return VisitCXXConstructExpr(E, E->getType()); 9676 } 9677 bool VisitLambdaExpr(const LambdaExpr *E); 9678 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9679 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9680 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9681 bool VisitBinCmp(const BinaryOperator *E); 9682 }; 9683 } 9684 9685 /// Perform zero-initialization on an object of non-union class type. 9686 /// C++11 [dcl.init]p5: 9687 /// To zero-initialize an object or reference of type T means: 9688 /// [...] 9689 /// -- if T is a (possibly cv-qualified) non-union class type, 9690 /// each non-static data member and each base-class subobject is 9691 /// zero-initialized 9692 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9693 const RecordDecl *RD, 9694 const LValue &This, APValue &Result) { 9695 assert(!RD->isUnion() && "Expected non-union class type"); 9696 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9697 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9698 std::distance(RD->field_begin(), RD->field_end())); 9699 9700 if (RD->isInvalidDecl()) return false; 9701 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9702 9703 if (CD) { 9704 unsigned Index = 0; 9705 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9706 End = CD->bases_end(); I != End; ++I, ++Index) { 9707 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9708 LValue Subobject = This; 9709 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9710 return false; 9711 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9712 Result.getStructBase(Index))) 9713 return false; 9714 } 9715 } 9716 9717 for (const auto *I : RD->fields()) { 9718 // -- if T is a reference type, no initialization is performed. 9719 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9720 continue; 9721 9722 LValue Subobject = This; 9723 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9724 return false; 9725 9726 ImplicitValueInitExpr VIE(I->getType()); 9727 if (!EvaluateInPlace( 9728 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9729 return false; 9730 } 9731 9732 return true; 9733 } 9734 9735 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9736 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9737 if (RD->isInvalidDecl()) return false; 9738 if (RD->isUnion()) { 9739 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9740 // object's first non-static named data member is zero-initialized 9741 RecordDecl::field_iterator I = RD->field_begin(); 9742 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9743 ++I; 9744 if (I == RD->field_end()) { 9745 Result = APValue((const FieldDecl*)nullptr); 9746 return true; 9747 } 9748 9749 LValue Subobject = This; 9750 if (!HandleLValueMember(Info, E, Subobject, *I)) 9751 return false; 9752 Result = APValue(*I); 9753 ImplicitValueInitExpr VIE(I->getType()); 9754 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9755 } 9756 9757 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9758 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9759 return false; 9760 } 9761 9762 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9763 } 9764 9765 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9766 switch (E->getCastKind()) { 9767 default: 9768 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9769 9770 case CK_ConstructorConversion: 9771 return Visit(E->getSubExpr()); 9772 9773 case CK_DerivedToBase: 9774 case CK_UncheckedDerivedToBase: { 9775 APValue DerivedObject; 9776 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9777 return false; 9778 if (!DerivedObject.isStruct()) 9779 return Error(E->getSubExpr()); 9780 9781 // Derived-to-base rvalue conversion: just slice off the derived part. 9782 APValue *Value = &DerivedObject; 9783 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9784 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9785 PathE = E->path_end(); PathI != PathE; ++PathI) { 9786 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9787 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9788 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9789 RD = Base; 9790 } 9791 Result = *Value; 9792 return true; 9793 } 9794 } 9795 } 9796 9797 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9798 if (E->isTransparent()) 9799 return Visit(E->getInit(0)); 9800 9801 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9802 if (RD->isInvalidDecl()) return false; 9803 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9804 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9805 9806 EvalInfo::EvaluatingConstructorRAII EvalObj( 9807 Info, 9808 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9809 CXXRD && CXXRD->getNumBases()); 9810 9811 if (RD->isUnion()) { 9812 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9813 Result = APValue(Field); 9814 if (!Field) 9815 return true; 9816 9817 // If the initializer list for a union does not contain any elements, the 9818 // first element of the union is value-initialized. 9819 // FIXME: The element should be initialized from an initializer list. 9820 // Is this difference ever observable for initializer lists which 9821 // we don't build? 9822 ImplicitValueInitExpr VIE(Field->getType()); 9823 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9824 9825 LValue Subobject = This; 9826 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9827 return false; 9828 9829 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9830 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9831 isa<CXXDefaultInitExpr>(InitExpr)); 9832 9833 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9834 if (Field->isBitField()) 9835 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9836 Field); 9837 return true; 9838 } 9839 9840 return false; 9841 } 9842 9843 if (!Result.hasValue()) 9844 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9845 std::distance(RD->field_begin(), RD->field_end())); 9846 unsigned ElementNo = 0; 9847 bool Success = true; 9848 9849 // Initialize base classes. 9850 if (CXXRD && CXXRD->getNumBases()) { 9851 for (const auto &Base : CXXRD->bases()) { 9852 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9853 const Expr *Init = E->getInit(ElementNo); 9854 9855 LValue Subobject = This; 9856 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9857 return false; 9858 9859 APValue &FieldVal = Result.getStructBase(ElementNo); 9860 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9861 if (!Info.noteFailure()) 9862 return false; 9863 Success = false; 9864 } 9865 ++ElementNo; 9866 } 9867 9868 EvalObj.finishedConstructingBases(); 9869 } 9870 9871 // Initialize members. 9872 for (const auto *Field : RD->fields()) { 9873 // Anonymous bit-fields are not considered members of the class for 9874 // purposes of aggregate initialization. 9875 if (Field->isUnnamedBitfield()) 9876 continue; 9877 9878 LValue Subobject = This; 9879 9880 bool HaveInit = ElementNo < E->getNumInits(); 9881 9882 // FIXME: Diagnostics here should point to the end of the initializer 9883 // list, not the start. 9884 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9885 Subobject, Field, &Layout)) 9886 return false; 9887 9888 // Perform an implicit value-initialization for members beyond the end of 9889 // the initializer list. 9890 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9891 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9892 9893 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9894 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9895 isa<CXXDefaultInitExpr>(Init)); 9896 9897 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9898 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9899 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9900 FieldVal, Field))) { 9901 if (!Info.noteFailure()) 9902 return false; 9903 Success = false; 9904 } 9905 } 9906 9907 EvalObj.finishedConstructingFields(); 9908 9909 return Success; 9910 } 9911 9912 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9913 QualType T) { 9914 // Note that E's type is not necessarily the type of our class here; we might 9915 // be initializing an array element instead. 9916 const CXXConstructorDecl *FD = E->getConstructor(); 9917 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9918 9919 bool ZeroInit = E->requiresZeroInitialization(); 9920 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9921 // If we've already performed zero-initialization, we're already done. 9922 if (Result.hasValue()) 9923 return true; 9924 9925 if (ZeroInit) 9926 return ZeroInitialization(E, T); 9927 9928 return getDefaultInitValue(T, Result); 9929 } 9930 9931 const FunctionDecl *Definition = nullptr; 9932 auto Body = FD->getBody(Definition); 9933 9934 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9935 return false; 9936 9937 // Avoid materializing a temporary for an elidable copy/move constructor. 9938 if (E->isElidable() && !ZeroInit) { 9939 // FIXME: This only handles the simplest case, where the source object 9940 // is passed directly as the first argument to the constructor. 9941 // This should also handle stepping though implicit casts and 9942 // and conversion sequences which involve two steps, with a 9943 // conversion operator followed by a converting constructor. 9944 const Expr *SrcObj = E->getArg(0); 9945 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 9946 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 9947 if (const MaterializeTemporaryExpr *ME = 9948 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 9949 return Visit(ME->getSubExpr()); 9950 } 9951 9952 if (ZeroInit && !ZeroInitialization(E, T)) 9953 return false; 9954 9955 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9956 return HandleConstructorCall(E, This, Args, 9957 cast<CXXConstructorDecl>(Definition), Info, 9958 Result); 9959 } 9960 9961 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9962 const CXXInheritedCtorInitExpr *E) { 9963 if (!Info.CurrentCall) { 9964 assert(Info.checkingPotentialConstantExpression()); 9965 return false; 9966 } 9967 9968 const CXXConstructorDecl *FD = E->getConstructor(); 9969 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9970 return false; 9971 9972 const FunctionDecl *Definition = nullptr; 9973 auto Body = FD->getBody(Definition); 9974 9975 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9976 return false; 9977 9978 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9979 cast<CXXConstructorDecl>(Definition), Info, 9980 Result); 9981 } 9982 9983 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9984 const CXXStdInitializerListExpr *E) { 9985 const ConstantArrayType *ArrayType = 9986 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9987 9988 LValue Array; 9989 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9990 return false; 9991 9992 // Get a pointer to the first element of the array. 9993 Array.addArray(Info, E, ArrayType); 9994 9995 auto InvalidType = [&] { 9996 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9997 << E->getType(); 9998 return false; 9999 }; 10000 10001 // FIXME: Perform the checks on the field types in SemaInit. 10002 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10003 RecordDecl::field_iterator Field = Record->field_begin(); 10004 if (Field == Record->field_end()) 10005 return InvalidType(); 10006 10007 // Start pointer. 10008 if (!Field->getType()->isPointerType() || 10009 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10010 ArrayType->getElementType())) 10011 return InvalidType(); 10012 10013 // FIXME: What if the initializer_list type has base classes, etc? 10014 Result = APValue(APValue::UninitStruct(), 0, 2); 10015 Array.moveInto(Result.getStructField(0)); 10016 10017 if (++Field == Record->field_end()) 10018 return InvalidType(); 10019 10020 if (Field->getType()->isPointerType() && 10021 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10022 ArrayType->getElementType())) { 10023 // End pointer. 10024 if (!HandleLValueArrayAdjustment(Info, E, Array, 10025 ArrayType->getElementType(), 10026 ArrayType->getSize().getZExtValue())) 10027 return false; 10028 Array.moveInto(Result.getStructField(1)); 10029 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10030 // Length. 10031 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10032 else 10033 return InvalidType(); 10034 10035 if (++Field != Record->field_end()) 10036 return InvalidType(); 10037 10038 return true; 10039 } 10040 10041 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10042 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10043 if (ClosureClass->isInvalidDecl()) 10044 return false; 10045 10046 const size_t NumFields = 10047 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10048 10049 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10050 E->capture_init_end()) && 10051 "The number of lambda capture initializers should equal the number of " 10052 "fields within the closure type"); 10053 10054 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10055 // Iterate through all the lambda's closure object's fields and initialize 10056 // them. 10057 auto *CaptureInitIt = E->capture_init_begin(); 10058 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10059 bool Success = true; 10060 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10061 for (const auto *Field : ClosureClass->fields()) { 10062 assert(CaptureInitIt != E->capture_init_end()); 10063 // Get the initializer for this field 10064 Expr *const CurFieldInit = *CaptureInitIt++; 10065 10066 // If there is no initializer, either this is a VLA or an error has 10067 // occurred. 10068 if (!CurFieldInit) 10069 return Error(E); 10070 10071 LValue Subobject = This; 10072 10073 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10074 return false; 10075 10076 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10077 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10078 if (!Info.keepEvaluatingAfterFailure()) 10079 return false; 10080 Success = false; 10081 } 10082 ++CaptureIt; 10083 } 10084 return Success; 10085 } 10086 10087 static bool EvaluateRecord(const Expr *E, const LValue &This, 10088 APValue &Result, EvalInfo &Info) { 10089 assert(!E->isValueDependent()); 10090 assert(E->isPRValue() && E->getType()->isRecordType() && 10091 "can't evaluate expression as a record rvalue"); 10092 return RecordExprEvaluator(Info, This, Result).Visit(E); 10093 } 10094 10095 //===----------------------------------------------------------------------===// 10096 // Temporary Evaluation 10097 // 10098 // Temporaries are represented in the AST as rvalues, but generally behave like 10099 // lvalues. The full-object of which the temporary is a subobject is implicitly 10100 // materialized so that a reference can bind to it. 10101 //===----------------------------------------------------------------------===// 10102 namespace { 10103 class TemporaryExprEvaluator 10104 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10105 public: 10106 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10107 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10108 10109 /// Visit an expression which constructs the value of this temporary. 10110 bool VisitConstructExpr(const Expr *E) { 10111 APValue &Value = Info.CurrentCall->createTemporary( 10112 E, E->getType(), ScopeKind::FullExpression, Result); 10113 return EvaluateInPlace(Value, Info, Result, E); 10114 } 10115 10116 bool VisitCastExpr(const CastExpr *E) { 10117 switch (E->getCastKind()) { 10118 default: 10119 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10120 10121 case CK_ConstructorConversion: 10122 return VisitConstructExpr(E->getSubExpr()); 10123 } 10124 } 10125 bool VisitInitListExpr(const InitListExpr *E) { 10126 return VisitConstructExpr(E); 10127 } 10128 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10129 return VisitConstructExpr(E); 10130 } 10131 bool VisitCallExpr(const CallExpr *E) { 10132 return VisitConstructExpr(E); 10133 } 10134 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10135 return VisitConstructExpr(E); 10136 } 10137 bool VisitLambdaExpr(const LambdaExpr *E) { 10138 return VisitConstructExpr(E); 10139 } 10140 }; 10141 } // end anonymous namespace 10142 10143 /// Evaluate an expression of record type as a temporary. 10144 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10145 assert(!E->isValueDependent()); 10146 assert(E->isPRValue() && E->getType()->isRecordType()); 10147 return TemporaryExprEvaluator(Info, Result).Visit(E); 10148 } 10149 10150 //===----------------------------------------------------------------------===// 10151 // Vector Evaluation 10152 //===----------------------------------------------------------------------===// 10153 10154 namespace { 10155 class VectorExprEvaluator 10156 : public ExprEvaluatorBase<VectorExprEvaluator> { 10157 APValue &Result; 10158 public: 10159 10160 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10161 : ExprEvaluatorBaseTy(info), Result(Result) {} 10162 10163 bool Success(ArrayRef<APValue> V, const Expr *E) { 10164 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10165 // FIXME: remove this APValue copy. 10166 Result = APValue(V.data(), V.size()); 10167 return true; 10168 } 10169 bool Success(const APValue &V, const Expr *E) { 10170 assert(V.isVector()); 10171 Result = V; 10172 return true; 10173 } 10174 bool ZeroInitialization(const Expr *E); 10175 10176 bool VisitUnaryReal(const UnaryOperator *E) 10177 { return Visit(E->getSubExpr()); } 10178 bool VisitCastExpr(const CastExpr* E); 10179 bool VisitInitListExpr(const InitListExpr *E); 10180 bool VisitUnaryImag(const UnaryOperator *E); 10181 bool VisitBinaryOperator(const BinaryOperator *E); 10182 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10183 // conditional select), shufflevector, ExtVectorElementExpr 10184 }; 10185 } // end anonymous namespace 10186 10187 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10188 assert(E->isPRValue() && E->getType()->isVectorType() && 10189 "not a vector prvalue"); 10190 return VectorExprEvaluator(Info, Result).Visit(E); 10191 } 10192 10193 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10194 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10195 unsigned NElts = VTy->getNumElements(); 10196 10197 const Expr *SE = E->getSubExpr(); 10198 QualType SETy = SE->getType(); 10199 10200 switch (E->getCastKind()) { 10201 case CK_VectorSplat: { 10202 APValue Val = APValue(); 10203 if (SETy->isIntegerType()) { 10204 APSInt IntResult; 10205 if (!EvaluateInteger(SE, IntResult, Info)) 10206 return false; 10207 Val = APValue(std::move(IntResult)); 10208 } else if (SETy->isRealFloatingType()) { 10209 APFloat FloatResult(0.0); 10210 if (!EvaluateFloat(SE, FloatResult, Info)) 10211 return false; 10212 Val = APValue(std::move(FloatResult)); 10213 } else { 10214 return Error(E); 10215 } 10216 10217 // Splat and create vector APValue. 10218 SmallVector<APValue, 4> Elts(NElts, Val); 10219 return Success(Elts, E); 10220 } 10221 case CK_BitCast: { 10222 // Evaluate the operand into an APInt we can extract from. 10223 llvm::APInt SValInt; 10224 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10225 return false; 10226 // Extract the elements 10227 QualType EltTy = VTy->getElementType(); 10228 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10229 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10230 SmallVector<APValue, 4> Elts; 10231 if (EltTy->isRealFloatingType()) { 10232 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10233 unsigned FloatEltSize = EltSize; 10234 if (&Sem == &APFloat::x87DoubleExtended()) 10235 FloatEltSize = 80; 10236 for (unsigned i = 0; i < NElts; i++) { 10237 llvm::APInt Elt; 10238 if (BigEndian) 10239 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10240 else 10241 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10242 Elts.push_back(APValue(APFloat(Sem, Elt))); 10243 } 10244 } else if (EltTy->isIntegerType()) { 10245 for (unsigned i = 0; i < NElts; i++) { 10246 llvm::APInt Elt; 10247 if (BigEndian) 10248 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10249 else 10250 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10251 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10252 } 10253 } else { 10254 return Error(E); 10255 } 10256 return Success(Elts, E); 10257 } 10258 default: 10259 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10260 } 10261 } 10262 10263 bool 10264 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10265 const VectorType *VT = E->getType()->castAs<VectorType>(); 10266 unsigned NumInits = E->getNumInits(); 10267 unsigned NumElements = VT->getNumElements(); 10268 10269 QualType EltTy = VT->getElementType(); 10270 SmallVector<APValue, 4> Elements; 10271 10272 // The number of initializers can be less than the number of 10273 // vector elements. For OpenCL, this can be due to nested vector 10274 // initialization. For GCC compatibility, missing trailing elements 10275 // should be initialized with zeroes. 10276 unsigned CountInits = 0, CountElts = 0; 10277 while (CountElts < NumElements) { 10278 // Handle nested vector initialization. 10279 if (CountInits < NumInits 10280 && E->getInit(CountInits)->getType()->isVectorType()) { 10281 APValue v; 10282 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10283 return Error(E); 10284 unsigned vlen = v.getVectorLength(); 10285 for (unsigned j = 0; j < vlen; j++) 10286 Elements.push_back(v.getVectorElt(j)); 10287 CountElts += vlen; 10288 } else if (EltTy->isIntegerType()) { 10289 llvm::APSInt sInt(32); 10290 if (CountInits < NumInits) { 10291 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10292 return false; 10293 } else // trailing integer zero. 10294 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10295 Elements.push_back(APValue(sInt)); 10296 CountElts++; 10297 } else { 10298 llvm::APFloat f(0.0); 10299 if (CountInits < NumInits) { 10300 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10301 return false; 10302 } else // trailing float zero. 10303 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10304 Elements.push_back(APValue(f)); 10305 CountElts++; 10306 } 10307 CountInits++; 10308 } 10309 return Success(Elements, E); 10310 } 10311 10312 bool 10313 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10314 const auto *VT = E->getType()->castAs<VectorType>(); 10315 QualType EltTy = VT->getElementType(); 10316 APValue ZeroElement; 10317 if (EltTy->isIntegerType()) 10318 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10319 else 10320 ZeroElement = 10321 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10322 10323 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10324 return Success(Elements, E); 10325 } 10326 10327 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10328 VisitIgnoredValue(E->getSubExpr()); 10329 return ZeroInitialization(E); 10330 } 10331 10332 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10333 BinaryOperatorKind Op = E->getOpcode(); 10334 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10335 "Operation not supported on vector types"); 10336 10337 if (Op == BO_Comma) 10338 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10339 10340 Expr *LHS = E->getLHS(); 10341 Expr *RHS = E->getRHS(); 10342 10343 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10344 "Must both be vector types"); 10345 // Checking JUST the types are the same would be fine, except shifts don't 10346 // need to have their types be the same (since you always shift by an int). 10347 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10348 E->getType()->castAs<VectorType>()->getNumElements() && 10349 RHS->getType()->castAs<VectorType>()->getNumElements() == 10350 E->getType()->castAs<VectorType>()->getNumElements() && 10351 "All operands must be the same size."); 10352 10353 APValue LHSValue; 10354 APValue RHSValue; 10355 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10356 if (!LHSOK && !Info.noteFailure()) 10357 return false; 10358 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10359 return false; 10360 10361 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10362 return false; 10363 10364 return Success(LHSValue, E); 10365 } 10366 10367 //===----------------------------------------------------------------------===// 10368 // Array Evaluation 10369 //===----------------------------------------------------------------------===// 10370 10371 namespace { 10372 class ArrayExprEvaluator 10373 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10374 const LValue &This; 10375 APValue &Result; 10376 public: 10377 10378 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10379 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10380 10381 bool Success(const APValue &V, const Expr *E) { 10382 assert(V.isArray() && "expected array"); 10383 Result = V; 10384 return true; 10385 } 10386 10387 bool ZeroInitialization(const Expr *E) { 10388 const ConstantArrayType *CAT = 10389 Info.Ctx.getAsConstantArrayType(E->getType()); 10390 if (!CAT) { 10391 if (E->getType()->isIncompleteArrayType()) { 10392 // We can be asked to zero-initialize a flexible array member; this 10393 // is represented as an ImplicitValueInitExpr of incomplete array 10394 // type. In this case, the array has zero elements. 10395 Result = APValue(APValue::UninitArray(), 0, 0); 10396 return true; 10397 } 10398 // FIXME: We could handle VLAs here. 10399 return Error(E); 10400 } 10401 10402 Result = APValue(APValue::UninitArray(), 0, 10403 CAT->getSize().getZExtValue()); 10404 if (!Result.hasArrayFiller()) 10405 return true; 10406 10407 // Zero-initialize all elements. 10408 LValue Subobject = This; 10409 Subobject.addArray(Info, E, CAT); 10410 ImplicitValueInitExpr VIE(CAT->getElementType()); 10411 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10412 } 10413 10414 bool VisitCallExpr(const CallExpr *E) { 10415 return handleCallExpr(E, Result, &This); 10416 } 10417 bool VisitInitListExpr(const InitListExpr *E, 10418 QualType AllocType = QualType()); 10419 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10420 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10421 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10422 const LValue &Subobject, 10423 APValue *Value, QualType Type); 10424 bool VisitStringLiteral(const StringLiteral *E, 10425 QualType AllocType = QualType()) { 10426 expandStringLiteral(Info, E, Result, AllocType); 10427 return true; 10428 } 10429 }; 10430 } // end anonymous namespace 10431 10432 static bool EvaluateArray(const Expr *E, const LValue &This, 10433 APValue &Result, EvalInfo &Info) { 10434 assert(!E->isValueDependent()); 10435 assert(E->isPRValue() && E->getType()->isArrayType() && 10436 "not an array prvalue"); 10437 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10438 } 10439 10440 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10441 APValue &Result, const InitListExpr *ILE, 10442 QualType AllocType) { 10443 assert(!ILE->isValueDependent()); 10444 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10445 "not an array prvalue"); 10446 return ArrayExprEvaluator(Info, This, Result) 10447 .VisitInitListExpr(ILE, AllocType); 10448 } 10449 10450 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10451 APValue &Result, 10452 const CXXConstructExpr *CCE, 10453 QualType AllocType) { 10454 assert(!CCE->isValueDependent()); 10455 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10456 "not an array prvalue"); 10457 return ArrayExprEvaluator(Info, This, Result) 10458 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10459 } 10460 10461 // Return true iff the given array filler may depend on the element index. 10462 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10463 // For now, just allow non-class value-initialization and initialization 10464 // lists comprised of them. 10465 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10466 return false; 10467 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10468 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10469 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10470 return true; 10471 } 10472 return false; 10473 } 10474 return true; 10475 } 10476 10477 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10478 QualType AllocType) { 10479 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10480 AllocType.isNull() ? E->getType() : AllocType); 10481 if (!CAT) 10482 return Error(E); 10483 10484 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10485 // an appropriately-typed string literal enclosed in braces. 10486 if (E->isStringLiteralInit()) { 10487 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10488 // FIXME: Support ObjCEncodeExpr here once we support it in 10489 // ArrayExprEvaluator generally. 10490 if (!SL) 10491 return Error(E); 10492 return VisitStringLiteral(SL, AllocType); 10493 } 10494 // Any other transparent list init will need proper handling of the 10495 // AllocType; we can't just recurse to the inner initializer. 10496 assert(!E->isTransparent() && 10497 "transparent array list initialization is not string literal init?"); 10498 10499 bool Success = true; 10500 10501 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10502 "zero-initialized array shouldn't have any initialized elts"); 10503 APValue Filler; 10504 if (Result.isArray() && Result.hasArrayFiller()) 10505 Filler = Result.getArrayFiller(); 10506 10507 unsigned NumEltsToInit = E->getNumInits(); 10508 unsigned NumElts = CAT->getSize().getZExtValue(); 10509 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10510 10511 // If the initializer might depend on the array index, run it for each 10512 // array element. 10513 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10514 NumEltsToInit = NumElts; 10515 10516 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10517 << NumEltsToInit << ".\n"); 10518 10519 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10520 10521 // If the array was previously zero-initialized, preserve the 10522 // zero-initialized values. 10523 if (Filler.hasValue()) { 10524 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10525 Result.getArrayInitializedElt(I) = Filler; 10526 if (Result.hasArrayFiller()) 10527 Result.getArrayFiller() = Filler; 10528 } 10529 10530 LValue Subobject = This; 10531 Subobject.addArray(Info, E, CAT); 10532 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10533 const Expr *Init = 10534 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10535 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10536 Info, Subobject, Init) || 10537 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10538 CAT->getElementType(), 1)) { 10539 if (!Info.noteFailure()) 10540 return false; 10541 Success = false; 10542 } 10543 } 10544 10545 if (!Result.hasArrayFiller()) 10546 return Success; 10547 10548 // If we get here, we have a trivial filler, which we can just evaluate 10549 // once and splat over the rest of the array elements. 10550 assert(FillerExpr && "no array filler for incomplete init list"); 10551 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10552 FillerExpr) && Success; 10553 } 10554 10555 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10556 LValue CommonLV; 10557 if (E->getCommonExpr() && 10558 !Evaluate(Info.CurrentCall->createTemporary( 10559 E->getCommonExpr(), 10560 getStorageType(Info.Ctx, E->getCommonExpr()), 10561 ScopeKind::FullExpression, CommonLV), 10562 Info, E->getCommonExpr()->getSourceExpr())) 10563 return false; 10564 10565 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10566 10567 uint64_t Elements = CAT->getSize().getZExtValue(); 10568 Result = APValue(APValue::UninitArray(), Elements, Elements); 10569 10570 LValue Subobject = This; 10571 Subobject.addArray(Info, E, CAT); 10572 10573 bool Success = true; 10574 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10575 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10576 Info, Subobject, E->getSubExpr()) || 10577 !HandleLValueArrayAdjustment(Info, E, Subobject, 10578 CAT->getElementType(), 1)) { 10579 if (!Info.noteFailure()) 10580 return false; 10581 Success = false; 10582 } 10583 } 10584 10585 return Success; 10586 } 10587 10588 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10589 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10590 } 10591 10592 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10593 const LValue &Subobject, 10594 APValue *Value, 10595 QualType Type) { 10596 bool HadZeroInit = Value->hasValue(); 10597 10598 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10599 unsigned N = CAT->getSize().getZExtValue(); 10600 10601 // Preserve the array filler if we had prior zero-initialization. 10602 APValue Filler = 10603 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10604 : APValue(); 10605 10606 *Value = APValue(APValue::UninitArray(), N, N); 10607 10608 if (HadZeroInit) 10609 for (unsigned I = 0; I != N; ++I) 10610 Value->getArrayInitializedElt(I) = Filler; 10611 10612 // Initialize the elements. 10613 LValue ArrayElt = Subobject; 10614 ArrayElt.addArray(Info, E, CAT); 10615 for (unsigned I = 0; I != N; ++I) 10616 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10617 CAT->getElementType()) || 10618 !HandleLValueArrayAdjustment(Info, E, ArrayElt, CAT->getElementType(), 10619 1)) 10620 return false; 10621 10622 return true; 10623 } 10624 10625 if (!Type->isRecordType()) 10626 return Error(E); 10627 10628 return RecordExprEvaluator(Info, Subobject, *Value) 10629 .VisitCXXConstructExpr(E, Type); 10630 } 10631 10632 //===----------------------------------------------------------------------===// 10633 // Integer Evaluation 10634 // 10635 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10636 // types and back in constant folding. Integer values are thus represented 10637 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10638 //===----------------------------------------------------------------------===// 10639 10640 namespace { 10641 class IntExprEvaluator 10642 : public ExprEvaluatorBase<IntExprEvaluator> { 10643 APValue &Result; 10644 public: 10645 IntExprEvaluator(EvalInfo &info, APValue &result) 10646 : ExprEvaluatorBaseTy(info), Result(result) {} 10647 10648 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10649 assert(E->getType()->isIntegralOrEnumerationType() && 10650 "Invalid evaluation result."); 10651 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10652 "Invalid evaluation result."); 10653 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10654 "Invalid evaluation result."); 10655 Result = APValue(SI); 10656 return true; 10657 } 10658 bool Success(const llvm::APSInt &SI, const Expr *E) { 10659 return Success(SI, E, Result); 10660 } 10661 10662 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10663 assert(E->getType()->isIntegralOrEnumerationType() && 10664 "Invalid evaluation result."); 10665 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10666 "Invalid evaluation result."); 10667 Result = APValue(APSInt(I)); 10668 Result.getInt().setIsUnsigned( 10669 E->getType()->isUnsignedIntegerOrEnumerationType()); 10670 return true; 10671 } 10672 bool Success(const llvm::APInt &I, const Expr *E) { 10673 return Success(I, E, Result); 10674 } 10675 10676 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10677 assert(E->getType()->isIntegralOrEnumerationType() && 10678 "Invalid evaluation result."); 10679 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10680 return true; 10681 } 10682 bool Success(uint64_t Value, const Expr *E) { 10683 return Success(Value, E, Result); 10684 } 10685 10686 bool Success(CharUnits Size, const Expr *E) { 10687 return Success(Size.getQuantity(), E); 10688 } 10689 10690 bool Success(const APValue &V, const Expr *E) { 10691 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10692 Result = V; 10693 return true; 10694 } 10695 return Success(V.getInt(), E); 10696 } 10697 10698 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10699 10700 //===--------------------------------------------------------------------===// 10701 // Visitor Methods 10702 //===--------------------------------------------------------------------===// 10703 10704 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10705 return Success(E->getValue(), E); 10706 } 10707 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10708 return Success(E->getValue(), E); 10709 } 10710 10711 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10712 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10713 if (CheckReferencedDecl(E, E->getDecl())) 10714 return true; 10715 10716 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10717 } 10718 bool VisitMemberExpr(const MemberExpr *E) { 10719 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10720 VisitIgnoredBaseExpression(E->getBase()); 10721 return true; 10722 } 10723 10724 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10725 } 10726 10727 bool VisitCallExpr(const CallExpr *E); 10728 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10729 bool VisitBinaryOperator(const BinaryOperator *E); 10730 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10731 bool VisitUnaryOperator(const UnaryOperator *E); 10732 10733 bool VisitCastExpr(const CastExpr* E); 10734 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10735 10736 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10737 return Success(E->getValue(), E); 10738 } 10739 10740 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10741 return Success(E->getValue(), E); 10742 } 10743 10744 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10745 if (Info.ArrayInitIndex == uint64_t(-1)) { 10746 // We were asked to evaluate this subexpression independent of the 10747 // enclosing ArrayInitLoopExpr. We can't do that. 10748 Info.FFDiag(E); 10749 return false; 10750 } 10751 return Success(Info.ArrayInitIndex, E); 10752 } 10753 10754 // Note, GNU defines __null as an integer, not a pointer. 10755 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10756 return ZeroInitialization(E); 10757 } 10758 10759 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10760 return Success(E->getValue(), E); 10761 } 10762 10763 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10764 return Success(E->getValue(), E); 10765 } 10766 10767 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10768 return Success(E->getValue(), E); 10769 } 10770 10771 bool VisitUnaryReal(const UnaryOperator *E); 10772 bool VisitUnaryImag(const UnaryOperator *E); 10773 10774 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10775 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10776 bool VisitSourceLocExpr(const SourceLocExpr *E); 10777 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10778 bool VisitRequiresExpr(const RequiresExpr *E); 10779 // FIXME: Missing: array subscript of vector, member of vector 10780 }; 10781 10782 class FixedPointExprEvaluator 10783 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10784 APValue &Result; 10785 10786 public: 10787 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10788 : ExprEvaluatorBaseTy(info), Result(result) {} 10789 10790 bool Success(const llvm::APInt &I, const Expr *E) { 10791 return Success( 10792 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10793 } 10794 10795 bool Success(uint64_t Value, const Expr *E) { 10796 return Success( 10797 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10798 } 10799 10800 bool Success(const APValue &V, const Expr *E) { 10801 return Success(V.getFixedPoint(), E); 10802 } 10803 10804 bool Success(const APFixedPoint &V, const Expr *E) { 10805 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10806 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10807 "Invalid evaluation result."); 10808 Result = APValue(V); 10809 return true; 10810 } 10811 10812 //===--------------------------------------------------------------------===// 10813 // Visitor Methods 10814 //===--------------------------------------------------------------------===// 10815 10816 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10817 return Success(E->getValue(), E); 10818 } 10819 10820 bool VisitCastExpr(const CastExpr *E); 10821 bool VisitUnaryOperator(const UnaryOperator *E); 10822 bool VisitBinaryOperator(const BinaryOperator *E); 10823 }; 10824 } // end anonymous namespace 10825 10826 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10827 /// produce either the integer value or a pointer. 10828 /// 10829 /// GCC has a heinous extension which folds casts between pointer types and 10830 /// pointer-sized integral types. We support this by allowing the evaluation of 10831 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10832 /// Some simple arithmetic on such values is supported (they are treated much 10833 /// like char*). 10834 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10835 EvalInfo &Info) { 10836 assert(!E->isValueDependent()); 10837 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 10838 return IntExprEvaluator(Info, Result).Visit(E); 10839 } 10840 10841 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10842 assert(!E->isValueDependent()); 10843 APValue Val; 10844 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10845 return false; 10846 if (!Val.isInt()) { 10847 // FIXME: It would be better to produce the diagnostic for casting 10848 // a pointer to an integer. 10849 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10850 return false; 10851 } 10852 Result = Val.getInt(); 10853 return true; 10854 } 10855 10856 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10857 APValue Evaluated = E->EvaluateInContext( 10858 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10859 return Success(Evaluated, E); 10860 } 10861 10862 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10863 EvalInfo &Info) { 10864 assert(!E->isValueDependent()); 10865 if (E->getType()->isFixedPointType()) { 10866 APValue Val; 10867 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10868 return false; 10869 if (!Val.isFixedPoint()) 10870 return false; 10871 10872 Result = Val.getFixedPoint(); 10873 return true; 10874 } 10875 return false; 10876 } 10877 10878 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10879 EvalInfo &Info) { 10880 assert(!E->isValueDependent()); 10881 if (E->getType()->isIntegerType()) { 10882 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10883 APSInt Val; 10884 if (!EvaluateInteger(E, Val, Info)) 10885 return false; 10886 Result = APFixedPoint(Val, FXSema); 10887 return true; 10888 } else if (E->getType()->isFixedPointType()) { 10889 return EvaluateFixedPoint(E, Result, Info); 10890 } 10891 return false; 10892 } 10893 10894 /// Check whether the given declaration can be directly converted to an integral 10895 /// rvalue. If not, no diagnostic is produced; there are other things we can 10896 /// try. 10897 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10898 // Enums are integer constant exprs. 10899 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10900 // Check for signedness/width mismatches between E type and ECD value. 10901 bool SameSign = (ECD->getInitVal().isSigned() 10902 == E->getType()->isSignedIntegerOrEnumerationType()); 10903 bool SameWidth = (ECD->getInitVal().getBitWidth() 10904 == Info.Ctx.getIntWidth(E->getType())); 10905 if (SameSign && SameWidth) 10906 return Success(ECD->getInitVal(), E); 10907 else { 10908 // Get rid of mismatch (otherwise Success assertions will fail) 10909 // by computing a new value matching the type of E. 10910 llvm::APSInt Val = ECD->getInitVal(); 10911 if (!SameSign) 10912 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10913 if (!SameWidth) 10914 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10915 return Success(Val, E); 10916 } 10917 } 10918 return false; 10919 } 10920 10921 /// Values returned by __builtin_classify_type, chosen to match the values 10922 /// produced by GCC's builtin. 10923 enum class GCCTypeClass { 10924 None = -1, 10925 Void = 0, 10926 Integer = 1, 10927 // GCC reserves 2 for character types, but instead classifies them as 10928 // integers. 10929 Enum = 3, 10930 Bool = 4, 10931 Pointer = 5, 10932 // GCC reserves 6 for references, but appears to never use it (because 10933 // expressions never have reference type, presumably). 10934 PointerToDataMember = 7, 10935 RealFloat = 8, 10936 Complex = 9, 10937 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10938 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10939 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10940 // uses 12 for that purpose, same as for a class or struct. Maybe it 10941 // internally implements a pointer to member as a struct? Who knows. 10942 PointerToMemberFunction = 12, // Not a bug, see above. 10943 ClassOrStruct = 12, 10944 Union = 13, 10945 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10946 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10947 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10948 // literals. 10949 }; 10950 10951 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10952 /// as GCC. 10953 static GCCTypeClass 10954 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10955 assert(!T->isDependentType() && "unexpected dependent type"); 10956 10957 QualType CanTy = T.getCanonicalType(); 10958 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10959 10960 switch (CanTy->getTypeClass()) { 10961 #define TYPE(ID, BASE) 10962 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10963 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10964 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10965 #include "clang/AST/TypeNodes.inc" 10966 case Type::Auto: 10967 case Type::DeducedTemplateSpecialization: 10968 llvm_unreachable("unexpected non-canonical or dependent type"); 10969 10970 case Type::Builtin: 10971 switch (BT->getKind()) { 10972 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10973 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10974 case BuiltinType::ID: return GCCTypeClass::Integer; 10975 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10976 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10977 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10978 case BuiltinType::ID: break; 10979 #include "clang/AST/BuiltinTypes.def" 10980 case BuiltinType::Void: 10981 return GCCTypeClass::Void; 10982 10983 case BuiltinType::Bool: 10984 return GCCTypeClass::Bool; 10985 10986 case BuiltinType::Char_U: 10987 case BuiltinType::UChar: 10988 case BuiltinType::WChar_U: 10989 case BuiltinType::Char8: 10990 case BuiltinType::Char16: 10991 case BuiltinType::Char32: 10992 case BuiltinType::UShort: 10993 case BuiltinType::UInt: 10994 case BuiltinType::ULong: 10995 case BuiltinType::ULongLong: 10996 case BuiltinType::UInt128: 10997 return GCCTypeClass::Integer; 10998 10999 case BuiltinType::UShortAccum: 11000 case BuiltinType::UAccum: 11001 case BuiltinType::ULongAccum: 11002 case BuiltinType::UShortFract: 11003 case BuiltinType::UFract: 11004 case BuiltinType::ULongFract: 11005 case BuiltinType::SatUShortAccum: 11006 case BuiltinType::SatUAccum: 11007 case BuiltinType::SatULongAccum: 11008 case BuiltinType::SatUShortFract: 11009 case BuiltinType::SatUFract: 11010 case BuiltinType::SatULongFract: 11011 return GCCTypeClass::None; 11012 11013 case BuiltinType::NullPtr: 11014 11015 case BuiltinType::ObjCId: 11016 case BuiltinType::ObjCClass: 11017 case BuiltinType::ObjCSel: 11018 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11019 case BuiltinType::Id: 11020 #include "clang/Basic/OpenCLImageTypes.def" 11021 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11022 case BuiltinType::Id: 11023 #include "clang/Basic/OpenCLExtensionTypes.def" 11024 case BuiltinType::OCLSampler: 11025 case BuiltinType::OCLEvent: 11026 case BuiltinType::OCLClkEvent: 11027 case BuiltinType::OCLQueue: 11028 case BuiltinType::OCLReserveID: 11029 #define SVE_TYPE(Name, Id, SingletonId) \ 11030 case BuiltinType::Id: 11031 #include "clang/Basic/AArch64SVEACLETypes.def" 11032 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11033 case BuiltinType::Id: 11034 #include "clang/Basic/PPCTypes.def" 11035 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11036 #include "clang/Basic/RISCVVTypes.def" 11037 return GCCTypeClass::None; 11038 11039 case BuiltinType::Dependent: 11040 llvm_unreachable("unexpected dependent type"); 11041 }; 11042 llvm_unreachable("unexpected placeholder type"); 11043 11044 case Type::Enum: 11045 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11046 11047 case Type::Pointer: 11048 case Type::ConstantArray: 11049 case Type::VariableArray: 11050 case Type::IncompleteArray: 11051 case Type::FunctionNoProto: 11052 case Type::FunctionProto: 11053 return GCCTypeClass::Pointer; 11054 11055 case Type::MemberPointer: 11056 return CanTy->isMemberDataPointerType() 11057 ? GCCTypeClass::PointerToDataMember 11058 : GCCTypeClass::PointerToMemberFunction; 11059 11060 case Type::Complex: 11061 return GCCTypeClass::Complex; 11062 11063 case Type::Record: 11064 return CanTy->isUnionType() ? GCCTypeClass::Union 11065 : GCCTypeClass::ClassOrStruct; 11066 11067 case Type::Atomic: 11068 // GCC classifies _Atomic T the same as T. 11069 return EvaluateBuiltinClassifyType( 11070 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11071 11072 case Type::BlockPointer: 11073 case Type::Vector: 11074 case Type::ExtVector: 11075 case Type::ConstantMatrix: 11076 case Type::ObjCObject: 11077 case Type::ObjCInterface: 11078 case Type::ObjCObjectPointer: 11079 case Type::Pipe: 11080 case Type::ExtInt: 11081 // GCC classifies vectors as None. We follow its lead and classify all 11082 // other types that don't fit into the regular classification the same way. 11083 return GCCTypeClass::None; 11084 11085 case Type::LValueReference: 11086 case Type::RValueReference: 11087 llvm_unreachable("invalid type for expression"); 11088 } 11089 11090 llvm_unreachable("unexpected type class"); 11091 } 11092 11093 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11094 /// as GCC. 11095 static GCCTypeClass 11096 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11097 // If no argument was supplied, default to None. This isn't 11098 // ideal, however it is what gcc does. 11099 if (E->getNumArgs() == 0) 11100 return GCCTypeClass::None; 11101 11102 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11103 // being an ICE, but still folds it to a constant using the type of the first 11104 // argument. 11105 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11106 } 11107 11108 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11109 /// __builtin_constant_p when applied to the given pointer. 11110 /// 11111 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11112 /// or it points to the first character of a string literal. 11113 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11114 APValue::LValueBase Base = LV.getLValueBase(); 11115 if (Base.isNull()) { 11116 // A null base is acceptable. 11117 return true; 11118 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11119 if (!isa<StringLiteral>(E)) 11120 return false; 11121 return LV.getLValueOffset().isZero(); 11122 } else if (Base.is<TypeInfoLValue>()) { 11123 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11124 // evaluate to true. 11125 return true; 11126 } else { 11127 // Any other base is not constant enough for GCC. 11128 return false; 11129 } 11130 } 11131 11132 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11133 /// GCC as we can manage. 11134 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11135 // This evaluation is not permitted to have side-effects, so evaluate it in 11136 // a speculative evaluation context. 11137 SpeculativeEvaluationRAII SpeculativeEval(Info); 11138 11139 // Constant-folding is always enabled for the operand of __builtin_constant_p 11140 // (even when the enclosing evaluation context otherwise requires a strict 11141 // language-specific constant expression). 11142 FoldConstant Fold(Info, true); 11143 11144 QualType ArgType = Arg->getType(); 11145 11146 // __builtin_constant_p always has one operand. The rules which gcc follows 11147 // are not precisely documented, but are as follows: 11148 // 11149 // - If the operand is of integral, floating, complex or enumeration type, 11150 // and can be folded to a known value of that type, it returns 1. 11151 // - If the operand can be folded to a pointer to the first character 11152 // of a string literal (or such a pointer cast to an integral type) 11153 // or to a null pointer or an integer cast to a pointer, it returns 1. 11154 // 11155 // Otherwise, it returns 0. 11156 // 11157 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11158 // its support for this did not work prior to GCC 9 and is not yet well 11159 // understood. 11160 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11161 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11162 ArgType->isNullPtrType()) { 11163 APValue V; 11164 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11165 Fold.keepDiagnostics(); 11166 return false; 11167 } 11168 11169 // For a pointer (possibly cast to integer), there are special rules. 11170 if (V.getKind() == APValue::LValue) 11171 return EvaluateBuiltinConstantPForLValue(V); 11172 11173 // Otherwise, any constant value is good enough. 11174 return V.hasValue(); 11175 } 11176 11177 // Anything else isn't considered to be sufficiently constant. 11178 return false; 11179 } 11180 11181 /// Retrieves the "underlying object type" of the given expression, 11182 /// as used by __builtin_object_size. 11183 static QualType getObjectType(APValue::LValueBase B) { 11184 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11185 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11186 return VD->getType(); 11187 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11188 if (isa<CompoundLiteralExpr>(E)) 11189 return E->getType(); 11190 } else if (B.is<TypeInfoLValue>()) { 11191 return B.getTypeInfoType(); 11192 } else if (B.is<DynamicAllocLValue>()) { 11193 return B.getDynamicAllocType(); 11194 } 11195 11196 return QualType(); 11197 } 11198 11199 /// A more selective version of E->IgnoreParenCasts for 11200 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11201 /// to change the type of E. 11202 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11203 /// 11204 /// Always returns an RValue with a pointer representation. 11205 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11206 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11207 11208 auto *NoParens = E->IgnoreParens(); 11209 auto *Cast = dyn_cast<CastExpr>(NoParens); 11210 if (Cast == nullptr) 11211 return NoParens; 11212 11213 // We only conservatively allow a few kinds of casts, because this code is 11214 // inherently a simple solution that seeks to support the common case. 11215 auto CastKind = Cast->getCastKind(); 11216 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11217 CastKind != CK_AddressSpaceConversion) 11218 return NoParens; 11219 11220 auto *SubExpr = Cast->getSubExpr(); 11221 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11222 return NoParens; 11223 return ignorePointerCastsAndParens(SubExpr); 11224 } 11225 11226 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11227 /// record layout. e.g. 11228 /// struct { struct { int a, b; } fst, snd; } obj; 11229 /// obj.fst // no 11230 /// obj.snd // yes 11231 /// obj.fst.a // no 11232 /// obj.fst.b // no 11233 /// obj.snd.a // no 11234 /// obj.snd.b // yes 11235 /// 11236 /// Please note: this function is specialized for how __builtin_object_size 11237 /// views "objects". 11238 /// 11239 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11240 /// correct result, it will always return true. 11241 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11242 assert(!LVal.Designator.Invalid); 11243 11244 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11245 const RecordDecl *Parent = FD->getParent(); 11246 Invalid = Parent->isInvalidDecl(); 11247 if (Invalid || Parent->isUnion()) 11248 return true; 11249 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11250 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11251 }; 11252 11253 auto &Base = LVal.getLValueBase(); 11254 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11255 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11256 bool Invalid; 11257 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11258 return Invalid; 11259 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11260 for (auto *FD : IFD->chain()) { 11261 bool Invalid; 11262 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11263 return Invalid; 11264 } 11265 } 11266 } 11267 11268 unsigned I = 0; 11269 QualType BaseType = getType(Base); 11270 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11271 // If we don't know the array bound, conservatively assume we're looking at 11272 // the final array element. 11273 ++I; 11274 if (BaseType->isIncompleteArrayType()) 11275 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11276 else 11277 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11278 } 11279 11280 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11281 const auto &Entry = LVal.Designator.Entries[I]; 11282 if (BaseType->isArrayType()) { 11283 // Because __builtin_object_size treats arrays as objects, we can ignore 11284 // the index iff this is the last array in the Designator. 11285 if (I + 1 == E) 11286 return true; 11287 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11288 uint64_t Index = Entry.getAsArrayIndex(); 11289 if (Index + 1 != CAT->getSize()) 11290 return false; 11291 BaseType = CAT->getElementType(); 11292 } else if (BaseType->isAnyComplexType()) { 11293 const auto *CT = BaseType->castAs<ComplexType>(); 11294 uint64_t Index = Entry.getAsArrayIndex(); 11295 if (Index != 1) 11296 return false; 11297 BaseType = CT->getElementType(); 11298 } else if (auto *FD = getAsField(Entry)) { 11299 bool Invalid; 11300 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11301 return Invalid; 11302 BaseType = FD->getType(); 11303 } else { 11304 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11305 return false; 11306 } 11307 } 11308 return true; 11309 } 11310 11311 /// Tests to see if the LValue has a user-specified designator (that isn't 11312 /// necessarily valid). Note that this always returns 'true' if the LValue has 11313 /// an unsized array as its first designator entry, because there's currently no 11314 /// way to tell if the user typed *foo or foo[0]. 11315 static bool refersToCompleteObject(const LValue &LVal) { 11316 if (LVal.Designator.Invalid) 11317 return false; 11318 11319 if (!LVal.Designator.Entries.empty()) 11320 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11321 11322 if (!LVal.InvalidBase) 11323 return true; 11324 11325 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11326 // the LValueBase. 11327 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11328 return !E || !isa<MemberExpr>(E); 11329 } 11330 11331 /// Attempts to detect a user writing into a piece of memory that's impossible 11332 /// to figure out the size of by just using types. 11333 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11334 const SubobjectDesignator &Designator = LVal.Designator; 11335 // Notes: 11336 // - Users can only write off of the end when we have an invalid base. Invalid 11337 // bases imply we don't know where the memory came from. 11338 // - We used to be a bit more aggressive here; we'd only be conservative if 11339 // the array at the end was flexible, or if it had 0 or 1 elements. This 11340 // broke some common standard library extensions (PR30346), but was 11341 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11342 // with some sort of list. OTOH, it seems that GCC is always 11343 // conservative with the last element in structs (if it's an array), so our 11344 // current behavior is more compatible than an explicit list approach would 11345 // be. 11346 return LVal.InvalidBase && 11347 Designator.Entries.size() == Designator.MostDerivedPathLength && 11348 Designator.MostDerivedIsArrayElement && 11349 isDesignatorAtObjectEnd(Ctx, LVal); 11350 } 11351 11352 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11353 /// Fails if the conversion would cause loss of precision. 11354 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11355 CharUnits &Result) { 11356 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11357 if (Int.ugt(CharUnitsMax)) 11358 return false; 11359 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11360 return true; 11361 } 11362 11363 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11364 /// determine how many bytes exist from the beginning of the object to either 11365 /// the end of the current subobject, or the end of the object itself, depending 11366 /// on what the LValue looks like + the value of Type. 11367 /// 11368 /// If this returns false, the value of Result is undefined. 11369 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11370 unsigned Type, const LValue &LVal, 11371 CharUnits &EndOffset) { 11372 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11373 11374 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11375 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11376 return false; 11377 return HandleSizeof(Info, ExprLoc, Ty, Result); 11378 }; 11379 11380 // We want to evaluate the size of the entire object. This is a valid fallback 11381 // for when Type=1 and the designator is invalid, because we're asked for an 11382 // upper-bound. 11383 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11384 // Type=3 wants a lower bound, so we can't fall back to this. 11385 if (Type == 3 && !DetermineForCompleteObject) 11386 return false; 11387 11388 llvm::APInt APEndOffset; 11389 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11390 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11391 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11392 11393 if (LVal.InvalidBase) 11394 return false; 11395 11396 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11397 return CheckedHandleSizeof(BaseTy, EndOffset); 11398 } 11399 11400 // We want to evaluate the size of a subobject. 11401 const SubobjectDesignator &Designator = LVal.Designator; 11402 11403 // The following is a moderately common idiom in C: 11404 // 11405 // struct Foo { int a; char c[1]; }; 11406 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11407 // strcpy(&F->c[0], Bar); 11408 // 11409 // In order to not break too much legacy code, we need to support it. 11410 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11411 // If we can resolve this to an alloc_size call, we can hand that back, 11412 // because we know for certain how many bytes there are to write to. 11413 llvm::APInt APEndOffset; 11414 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11415 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11416 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11417 11418 // If we cannot determine the size of the initial allocation, then we can't 11419 // given an accurate upper-bound. However, we are still able to give 11420 // conservative lower-bounds for Type=3. 11421 if (Type == 1) 11422 return false; 11423 } 11424 11425 CharUnits BytesPerElem; 11426 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11427 return false; 11428 11429 // According to the GCC documentation, we want the size of the subobject 11430 // denoted by the pointer. But that's not quite right -- what we actually 11431 // want is the size of the immediately-enclosing array, if there is one. 11432 int64_t ElemsRemaining; 11433 if (Designator.MostDerivedIsArrayElement && 11434 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11435 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11436 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11437 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11438 } else { 11439 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11440 } 11441 11442 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11443 return true; 11444 } 11445 11446 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11447 /// returns true and stores the result in @p Size. 11448 /// 11449 /// If @p WasError is non-null, this will report whether the failure to evaluate 11450 /// is to be treated as an Error in IntExprEvaluator. 11451 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11452 EvalInfo &Info, uint64_t &Size) { 11453 // Determine the denoted object. 11454 LValue LVal; 11455 { 11456 // The operand of __builtin_object_size is never evaluated for side-effects. 11457 // If there are any, but we can determine the pointed-to object anyway, then 11458 // ignore the side-effects. 11459 SpeculativeEvaluationRAII SpeculativeEval(Info); 11460 IgnoreSideEffectsRAII Fold(Info); 11461 11462 if (E->isGLValue()) { 11463 // It's possible for us to be given GLValues if we're called via 11464 // Expr::tryEvaluateObjectSize. 11465 APValue RVal; 11466 if (!EvaluateAsRValue(Info, E, RVal)) 11467 return false; 11468 LVal.setFrom(Info.Ctx, RVal); 11469 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11470 /*InvalidBaseOK=*/true)) 11471 return false; 11472 } 11473 11474 // If we point to before the start of the object, there are no accessible 11475 // bytes. 11476 if (LVal.getLValueOffset().isNegative()) { 11477 Size = 0; 11478 return true; 11479 } 11480 11481 CharUnits EndOffset; 11482 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11483 return false; 11484 11485 // If we've fallen outside of the end offset, just pretend there's nothing to 11486 // write to/read from. 11487 if (EndOffset <= LVal.getLValueOffset()) 11488 Size = 0; 11489 else 11490 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11491 return true; 11492 } 11493 11494 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11495 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11496 return VisitBuiltinCallExpr(E, BuiltinOp); 11497 11498 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11499 } 11500 11501 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11502 APValue &Val, APSInt &Alignment) { 11503 QualType SrcTy = E->getArg(0)->getType(); 11504 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11505 return false; 11506 // Even though we are evaluating integer expressions we could get a pointer 11507 // argument for the __builtin_is_aligned() case. 11508 if (SrcTy->isPointerType()) { 11509 LValue Ptr; 11510 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11511 return false; 11512 Ptr.moveInto(Val); 11513 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11514 Info.FFDiag(E->getArg(0)); 11515 return false; 11516 } else { 11517 APSInt SrcInt; 11518 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11519 return false; 11520 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11521 "Bit widths must be the same"); 11522 Val = APValue(SrcInt); 11523 } 11524 assert(Val.hasValue()); 11525 return true; 11526 } 11527 11528 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11529 unsigned BuiltinOp) { 11530 switch (BuiltinOp) { 11531 default: 11532 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11533 11534 case Builtin::BI__builtin_dynamic_object_size: 11535 case Builtin::BI__builtin_object_size: { 11536 // The type was checked when we built the expression. 11537 unsigned Type = 11538 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11539 assert(Type <= 3 && "unexpected type"); 11540 11541 uint64_t Size; 11542 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11543 return Success(Size, E); 11544 11545 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11546 return Success((Type & 2) ? 0 : -1, E); 11547 11548 // Expression had no side effects, but we couldn't statically determine the 11549 // size of the referenced object. 11550 switch (Info.EvalMode) { 11551 case EvalInfo::EM_ConstantExpression: 11552 case EvalInfo::EM_ConstantFold: 11553 case EvalInfo::EM_IgnoreSideEffects: 11554 // Leave it to IR generation. 11555 return Error(E); 11556 case EvalInfo::EM_ConstantExpressionUnevaluated: 11557 // Reduce it to a constant now. 11558 return Success((Type & 2) ? 0 : -1, E); 11559 } 11560 11561 llvm_unreachable("unexpected EvalMode"); 11562 } 11563 11564 case Builtin::BI__builtin_os_log_format_buffer_size: { 11565 analyze_os_log::OSLogBufferLayout Layout; 11566 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11567 return Success(Layout.size().getQuantity(), E); 11568 } 11569 11570 case Builtin::BI__builtin_is_aligned: { 11571 APValue Src; 11572 APSInt Alignment; 11573 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11574 return false; 11575 if (Src.isLValue()) { 11576 // If we evaluated a pointer, check the minimum known alignment. 11577 LValue Ptr; 11578 Ptr.setFrom(Info.Ctx, Src); 11579 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11580 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11581 // We can return true if the known alignment at the computed offset is 11582 // greater than the requested alignment. 11583 assert(PtrAlign.isPowerOfTwo()); 11584 assert(Alignment.isPowerOf2()); 11585 if (PtrAlign.getQuantity() >= Alignment) 11586 return Success(1, E); 11587 // If the alignment is not known to be sufficient, some cases could still 11588 // be aligned at run time. However, if the requested alignment is less or 11589 // equal to the base alignment and the offset is not aligned, we know that 11590 // the run-time value can never be aligned. 11591 if (BaseAlignment.getQuantity() >= Alignment && 11592 PtrAlign.getQuantity() < Alignment) 11593 return Success(0, E); 11594 // Otherwise we can't infer whether the value is sufficiently aligned. 11595 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11596 // in cases where we can't fully evaluate the pointer. 11597 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11598 << Alignment; 11599 return false; 11600 } 11601 assert(Src.isInt()); 11602 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11603 } 11604 case Builtin::BI__builtin_align_up: { 11605 APValue Src; 11606 APSInt Alignment; 11607 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11608 return false; 11609 if (!Src.isInt()) 11610 return Error(E); 11611 APSInt AlignedVal = 11612 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11613 Src.getInt().isUnsigned()); 11614 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11615 return Success(AlignedVal, E); 11616 } 11617 case Builtin::BI__builtin_align_down: { 11618 APValue Src; 11619 APSInt Alignment; 11620 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11621 return false; 11622 if (!Src.isInt()) 11623 return Error(E); 11624 APSInt AlignedVal = 11625 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11626 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11627 return Success(AlignedVal, E); 11628 } 11629 11630 case Builtin::BI__builtin_bitreverse8: 11631 case Builtin::BI__builtin_bitreverse16: 11632 case Builtin::BI__builtin_bitreverse32: 11633 case Builtin::BI__builtin_bitreverse64: { 11634 APSInt Val; 11635 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11636 return false; 11637 11638 return Success(Val.reverseBits(), E); 11639 } 11640 11641 case Builtin::BI__builtin_bswap16: 11642 case Builtin::BI__builtin_bswap32: 11643 case Builtin::BI__builtin_bswap64: { 11644 APSInt Val; 11645 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11646 return false; 11647 11648 return Success(Val.byteSwap(), E); 11649 } 11650 11651 case Builtin::BI__builtin_classify_type: 11652 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11653 11654 case Builtin::BI__builtin_clrsb: 11655 case Builtin::BI__builtin_clrsbl: 11656 case Builtin::BI__builtin_clrsbll: { 11657 APSInt Val; 11658 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11659 return false; 11660 11661 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11662 } 11663 11664 case Builtin::BI__builtin_clz: 11665 case Builtin::BI__builtin_clzl: 11666 case Builtin::BI__builtin_clzll: 11667 case Builtin::BI__builtin_clzs: { 11668 APSInt Val; 11669 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11670 return false; 11671 if (!Val) 11672 return Error(E); 11673 11674 return Success(Val.countLeadingZeros(), E); 11675 } 11676 11677 case Builtin::BI__builtin_constant_p: { 11678 const Expr *Arg = E->getArg(0); 11679 if (EvaluateBuiltinConstantP(Info, Arg)) 11680 return Success(true, E); 11681 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11682 // Outside a constant context, eagerly evaluate to false in the presence 11683 // of side-effects in order to avoid -Wunsequenced false-positives in 11684 // a branch on __builtin_constant_p(expr). 11685 return Success(false, E); 11686 } 11687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11688 return false; 11689 } 11690 11691 case Builtin::BI__builtin_is_constant_evaluated: { 11692 const auto *Callee = Info.CurrentCall->getCallee(); 11693 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11694 (Info.CallStackDepth == 1 || 11695 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11696 Callee->getIdentifier() && 11697 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11698 // FIXME: Find a better way to avoid duplicated diagnostics. 11699 if (Info.EvalStatus.Diag) 11700 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11701 : Info.CurrentCall->CallLoc, 11702 diag::warn_is_constant_evaluated_always_true_constexpr) 11703 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11704 : "std::is_constant_evaluated"); 11705 } 11706 11707 return Success(Info.InConstantContext, E); 11708 } 11709 11710 case Builtin::BI__builtin_ctz: 11711 case Builtin::BI__builtin_ctzl: 11712 case Builtin::BI__builtin_ctzll: 11713 case Builtin::BI__builtin_ctzs: { 11714 APSInt Val; 11715 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11716 return false; 11717 if (!Val) 11718 return Error(E); 11719 11720 return Success(Val.countTrailingZeros(), E); 11721 } 11722 11723 case Builtin::BI__builtin_eh_return_data_regno: { 11724 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11725 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11726 return Success(Operand, E); 11727 } 11728 11729 case Builtin::BI__builtin_expect: 11730 case Builtin::BI__builtin_expect_with_probability: 11731 return Visit(E->getArg(0)); 11732 11733 case Builtin::BI__builtin_ffs: 11734 case Builtin::BI__builtin_ffsl: 11735 case Builtin::BI__builtin_ffsll: { 11736 APSInt Val; 11737 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11738 return false; 11739 11740 unsigned N = Val.countTrailingZeros(); 11741 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11742 } 11743 11744 case Builtin::BI__builtin_fpclassify: { 11745 APFloat Val(0.0); 11746 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11747 return false; 11748 unsigned Arg; 11749 switch (Val.getCategory()) { 11750 case APFloat::fcNaN: Arg = 0; break; 11751 case APFloat::fcInfinity: Arg = 1; break; 11752 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11753 case APFloat::fcZero: Arg = 4; break; 11754 } 11755 return Visit(E->getArg(Arg)); 11756 } 11757 11758 case Builtin::BI__builtin_isinf_sign: { 11759 APFloat Val(0.0); 11760 return EvaluateFloat(E->getArg(0), Val, Info) && 11761 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11762 } 11763 11764 case Builtin::BI__builtin_isinf: { 11765 APFloat Val(0.0); 11766 return EvaluateFloat(E->getArg(0), Val, Info) && 11767 Success(Val.isInfinity() ? 1 : 0, E); 11768 } 11769 11770 case Builtin::BI__builtin_isfinite: { 11771 APFloat Val(0.0); 11772 return EvaluateFloat(E->getArg(0), Val, Info) && 11773 Success(Val.isFinite() ? 1 : 0, E); 11774 } 11775 11776 case Builtin::BI__builtin_isnan: { 11777 APFloat Val(0.0); 11778 return EvaluateFloat(E->getArg(0), Val, Info) && 11779 Success(Val.isNaN() ? 1 : 0, E); 11780 } 11781 11782 case Builtin::BI__builtin_isnormal: { 11783 APFloat Val(0.0); 11784 return EvaluateFloat(E->getArg(0), Val, Info) && 11785 Success(Val.isNormal() ? 1 : 0, E); 11786 } 11787 11788 case Builtin::BI__builtin_parity: 11789 case Builtin::BI__builtin_parityl: 11790 case Builtin::BI__builtin_parityll: { 11791 APSInt Val; 11792 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11793 return false; 11794 11795 return Success(Val.countPopulation() % 2, E); 11796 } 11797 11798 case Builtin::BI__builtin_popcount: 11799 case Builtin::BI__builtin_popcountl: 11800 case Builtin::BI__builtin_popcountll: { 11801 APSInt Val; 11802 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11803 return false; 11804 11805 return Success(Val.countPopulation(), E); 11806 } 11807 11808 case Builtin::BI__builtin_rotateleft8: 11809 case Builtin::BI__builtin_rotateleft16: 11810 case Builtin::BI__builtin_rotateleft32: 11811 case Builtin::BI__builtin_rotateleft64: 11812 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11813 case Builtin::BI_rotl16: 11814 case Builtin::BI_rotl: 11815 case Builtin::BI_lrotl: 11816 case Builtin::BI_rotl64: { 11817 APSInt Val, Amt; 11818 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11819 !EvaluateInteger(E->getArg(1), Amt, Info)) 11820 return false; 11821 11822 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11823 } 11824 11825 case Builtin::BI__builtin_rotateright8: 11826 case Builtin::BI__builtin_rotateright16: 11827 case Builtin::BI__builtin_rotateright32: 11828 case Builtin::BI__builtin_rotateright64: 11829 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11830 case Builtin::BI_rotr16: 11831 case Builtin::BI_rotr: 11832 case Builtin::BI_lrotr: 11833 case Builtin::BI_rotr64: { 11834 APSInt Val, Amt; 11835 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11836 !EvaluateInteger(E->getArg(1), Amt, Info)) 11837 return false; 11838 11839 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11840 } 11841 11842 case Builtin::BIstrlen: 11843 case Builtin::BIwcslen: 11844 // A call to strlen is not a constant expression. 11845 if (Info.getLangOpts().CPlusPlus11) 11846 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11847 << /*isConstexpr*/0 << /*isConstructor*/0 11848 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11849 else 11850 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11851 LLVM_FALLTHROUGH; 11852 case Builtin::BI__builtin_strlen: 11853 case Builtin::BI__builtin_wcslen: { 11854 // As an extension, we support __builtin_strlen() as a constant expression, 11855 // and support folding strlen() to a constant. 11856 uint64_t StrLen; 11857 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 11858 return Success(StrLen, E); 11859 return false; 11860 } 11861 11862 case Builtin::BIstrcmp: 11863 case Builtin::BIwcscmp: 11864 case Builtin::BIstrncmp: 11865 case Builtin::BIwcsncmp: 11866 case Builtin::BImemcmp: 11867 case Builtin::BIbcmp: 11868 case Builtin::BIwmemcmp: 11869 // A call to strlen is not a constant expression. 11870 if (Info.getLangOpts().CPlusPlus11) 11871 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11872 << /*isConstexpr*/0 << /*isConstructor*/0 11873 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11874 else 11875 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11876 LLVM_FALLTHROUGH; 11877 case Builtin::BI__builtin_strcmp: 11878 case Builtin::BI__builtin_wcscmp: 11879 case Builtin::BI__builtin_strncmp: 11880 case Builtin::BI__builtin_wcsncmp: 11881 case Builtin::BI__builtin_memcmp: 11882 case Builtin::BI__builtin_bcmp: 11883 case Builtin::BI__builtin_wmemcmp: { 11884 LValue String1, String2; 11885 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11886 !EvaluatePointer(E->getArg(1), String2, Info)) 11887 return false; 11888 11889 uint64_t MaxLength = uint64_t(-1); 11890 if (BuiltinOp != Builtin::BIstrcmp && 11891 BuiltinOp != Builtin::BIwcscmp && 11892 BuiltinOp != Builtin::BI__builtin_strcmp && 11893 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11894 APSInt N; 11895 if (!EvaluateInteger(E->getArg(2), N, Info)) 11896 return false; 11897 MaxLength = N.getExtValue(); 11898 } 11899 11900 // Empty substrings compare equal by definition. 11901 if (MaxLength == 0u) 11902 return Success(0, E); 11903 11904 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11905 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11906 String1.Designator.Invalid || String2.Designator.Invalid) 11907 return false; 11908 11909 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11910 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11911 11912 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11913 BuiltinOp == Builtin::BIbcmp || 11914 BuiltinOp == Builtin::BI__builtin_memcmp || 11915 BuiltinOp == Builtin::BI__builtin_bcmp; 11916 11917 assert(IsRawByte || 11918 (Info.Ctx.hasSameUnqualifiedType( 11919 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11920 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11921 11922 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11923 // 'char8_t', but no other types. 11924 if (IsRawByte && 11925 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11926 // FIXME: Consider using our bit_cast implementation to support this. 11927 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11928 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11929 << CharTy1 << CharTy2; 11930 return false; 11931 } 11932 11933 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11934 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11935 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11936 Char1.isInt() && Char2.isInt(); 11937 }; 11938 const auto &AdvanceElems = [&] { 11939 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11940 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11941 }; 11942 11943 bool StopAtNull = 11944 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11945 BuiltinOp != Builtin::BIwmemcmp && 11946 BuiltinOp != Builtin::BI__builtin_memcmp && 11947 BuiltinOp != Builtin::BI__builtin_bcmp && 11948 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11949 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11950 BuiltinOp == Builtin::BIwcsncmp || 11951 BuiltinOp == Builtin::BIwmemcmp || 11952 BuiltinOp == Builtin::BI__builtin_wcscmp || 11953 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11954 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11955 11956 for (; MaxLength; --MaxLength) { 11957 APValue Char1, Char2; 11958 if (!ReadCurElems(Char1, Char2)) 11959 return false; 11960 if (Char1.getInt().ne(Char2.getInt())) { 11961 if (IsWide) // wmemcmp compares with wchar_t signedness. 11962 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11963 // memcmp always compares unsigned chars. 11964 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11965 } 11966 if (StopAtNull && !Char1.getInt()) 11967 return Success(0, E); 11968 assert(!(StopAtNull && !Char2.getInt())); 11969 if (!AdvanceElems()) 11970 return false; 11971 } 11972 // We hit the strncmp / memcmp limit. 11973 return Success(0, E); 11974 } 11975 11976 case Builtin::BI__atomic_always_lock_free: 11977 case Builtin::BI__atomic_is_lock_free: 11978 case Builtin::BI__c11_atomic_is_lock_free: { 11979 APSInt SizeVal; 11980 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11981 return false; 11982 11983 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11984 // of two less than or equal to the maximum inline atomic width, we know it 11985 // is lock-free. If the size isn't a power of two, or greater than the 11986 // maximum alignment where we promote atomics, we know it is not lock-free 11987 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11988 // the answer can only be determined at runtime; for example, 16-byte 11989 // atomics have lock-free implementations on some, but not all, 11990 // x86-64 processors. 11991 11992 // Check power-of-two. 11993 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11994 if (Size.isPowerOfTwo()) { 11995 // Check against inlining width. 11996 unsigned InlineWidthBits = 11997 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11998 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11999 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12000 Size == CharUnits::One() || 12001 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12002 Expr::NPC_NeverValueDependent)) 12003 // OK, we will inline appropriately-aligned operations of this size, 12004 // and _Atomic(T) is appropriately-aligned. 12005 return Success(1, E); 12006 12007 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12008 castAs<PointerType>()->getPointeeType(); 12009 if (!PointeeType->isIncompleteType() && 12010 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12011 // OK, we will inline operations on this object. 12012 return Success(1, E); 12013 } 12014 } 12015 } 12016 12017 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12018 Success(0, E) : Error(E); 12019 } 12020 case Builtin::BI__builtin_add_overflow: 12021 case Builtin::BI__builtin_sub_overflow: 12022 case Builtin::BI__builtin_mul_overflow: 12023 case Builtin::BI__builtin_sadd_overflow: 12024 case Builtin::BI__builtin_uadd_overflow: 12025 case Builtin::BI__builtin_uaddl_overflow: 12026 case Builtin::BI__builtin_uaddll_overflow: 12027 case Builtin::BI__builtin_usub_overflow: 12028 case Builtin::BI__builtin_usubl_overflow: 12029 case Builtin::BI__builtin_usubll_overflow: 12030 case Builtin::BI__builtin_umul_overflow: 12031 case Builtin::BI__builtin_umull_overflow: 12032 case Builtin::BI__builtin_umulll_overflow: 12033 case Builtin::BI__builtin_saddl_overflow: 12034 case Builtin::BI__builtin_saddll_overflow: 12035 case Builtin::BI__builtin_ssub_overflow: 12036 case Builtin::BI__builtin_ssubl_overflow: 12037 case Builtin::BI__builtin_ssubll_overflow: 12038 case Builtin::BI__builtin_smul_overflow: 12039 case Builtin::BI__builtin_smull_overflow: 12040 case Builtin::BI__builtin_smulll_overflow: { 12041 LValue ResultLValue; 12042 APSInt LHS, RHS; 12043 12044 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12045 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12046 !EvaluateInteger(E->getArg(1), RHS, Info) || 12047 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12048 return false; 12049 12050 APSInt Result; 12051 bool DidOverflow = false; 12052 12053 // If the types don't have to match, enlarge all 3 to the largest of them. 12054 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12055 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12056 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12057 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12058 ResultType->isSignedIntegerOrEnumerationType(); 12059 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12060 ResultType->isSignedIntegerOrEnumerationType(); 12061 uint64_t LHSSize = LHS.getBitWidth(); 12062 uint64_t RHSSize = RHS.getBitWidth(); 12063 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12064 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12065 12066 // Add an additional bit if the signedness isn't uniformly agreed to. We 12067 // could do this ONLY if there is a signed and an unsigned that both have 12068 // MaxBits, but the code to check that is pretty nasty. The issue will be 12069 // caught in the shrink-to-result later anyway. 12070 if (IsSigned && !AllSigned) 12071 ++MaxBits; 12072 12073 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12074 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12075 Result = APSInt(MaxBits, !IsSigned); 12076 } 12077 12078 // Find largest int. 12079 switch (BuiltinOp) { 12080 default: 12081 llvm_unreachable("Invalid value for BuiltinOp"); 12082 case Builtin::BI__builtin_add_overflow: 12083 case Builtin::BI__builtin_sadd_overflow: 12084 case Builtin::BI__builtin_saddl_overflow: 12085 case Builtin::BI__builtin_saddll_overflow: 12086 case Builtin::BI__builtin_uadd_overflow: 12087 case Builtin::BI__builtin_uaddl_overflow: 12088 case Builtin::BI__builtin_uaddll_overflow: 12089 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12090 : LHS.uadd_ov(RHS, DidOverflow); 12091 break; 12092 case Builtin::BI__builtin_sub_overflow: 12093 case Builtin::BI__builtin_ssub_overflow: 12094 case Builtin::BI__builtin_ssubl_overflow: 12095 case Builtin::BI__builtin_ssubll_overflow: 12096 case Builtin::BI__builtin_usub_overflow: 12097 case Builtin::BI__builtin_usubl_overflow: 12098 case Builtin::BI__builtin_usubll_overflow: 12099 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12100 : LHS.usub_ov(RHS, DidOverflow); 12101 break; 12102 case Builtin::BI__builtin_mul_overflow: 12103 case Builtin::BI__builtin_smul_overflow: 12104 case Builtin::BI__builtin_smull_overflow: 12105 case Builtin::BI__builtin_smulll_overflow: 12106 case Builtin::BI__builtin_umul_overflow: 12107 case Builtin::BI__builtin_umull_overflow: 12108 case Builtin::BI__builtin_umulll_overflow: 12109 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12110 : LHS.umul_ov(RHS, DidOverflow); 12111 break; 12112 } 12113 12114 // In the case where multiple sizes are allowed, truncate and see if 12115 // the values are the same. 12116 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12117 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12118 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12119 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12120 // since it will give us the behavior of a TruncOrSelf in the case where 12121 // its parameter <= its size. We previously set Result to be at least the 12122 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12123 // will work exactly like TruncOrSelf. 12124 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12125 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12126 12127 if (!APSInt::isSameValue(Temp, Result)) 12128 DidOverflow = true; 12129 Result = Temp; 12130 } 12131 12132 APValue APV{Result}; 12133 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12134 return false; 12135 return Success(DidOverflow, E); 12136 } 12137 } 12138 } 12139 12140 /// Determine whether this is a pointer past the end of the complete 12141 /// object referred to by the lvalue. 12142 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12143 const LValue &LV) { 12144 // A null pointer can be viewed as being "past the end" but we don't 12145 // choose to look at it that way here. 12146 if (!LV.getLValueBase()) 12147 return false; 12148 12149 // If the designator is valid and refers to a subobject, we're not pointing 12150 // past the end. 12151 if (!LV.getLValueDesignator().Invalid && 12152 !LV.getLValueDesignator().isOnePastTheEnd()) 12153 return false; 12154 12155 // A pointer to an incomplete type might be past-the-end if the type's size is 12156 // zero. We cannot tell because the type is incomplete. 12157 QualType Ty = getType(LV.getLValueBase()); 12158 if (Ty->isIncompleteType()) 12159 return true; 12160 12161 // We're a past-the-end pointer if we point to the byte after the object, 12162 // no matter what our type or path is. 12163 auto Size = Ctx.getTypeSizeInChars(Ty); 12164 return LV.getLValueOffset() == Size; 12165 } 12166 12167 namespace { 12168 12169 /// Data recursive integer evaluator of certain binary operators. 12170 /// 12171 /// We use a data recursive algorithm for binary operators so that we are able 12172 /// to handle extreme cases of chained binary operators without causing stack 12173 /// overflow. 12174 class DataRecursiveIntBinOpEvaluator { 12175 struct EvalResult { 12176 APValue Val; 12177 bool Failed; 12178 12179 EvalResult() : Failed(false) { } 12180 12181 void swap(EvalResult &RHS) { 12182 Val.swap(RHS.Val); 12183 Failed = RHS.Failed; 12184 RHS.Failed = false; 12185 } 12186 }; 12187 12188 struct Job { 12189 const Expr *E; 12190 EvalResult LHSResult; // meaningful only for binary operator expression. 12191 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12192 12193 Job() = default; 12194 Job(Job &&) = default; 12195 12196 void startSpeculativeEval(EvalInfo &Info) { 12197 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12198 } 12199 12200 private: 12201 SpeculativeEvaluationRAII SpecEvalRAII; 12202 }; 12203 12204 SmallVector<Job, 16> Queue; 12205 12206 IntExprEvaluator &IntEval; 12207 EvalInfo &Info; 12208 APValue &FinalResult; 12209 12210 public: 12211 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12212 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12213 12214 /// True if \param E is a binary operator that we are going to handle 12215 /// data recursively. 12216 /// We handle binary operators that are comma, logical, or that have operands 12217 /// with integral or enumeration type. 12218 static bool shouldEnqueue(const BinaryOperator *E) { 12219 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12220 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12221 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12222 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12223 } 12224 12225 bool Traverse(const BinaryOperator *E) { 12226 enqueue(E); 12227 EvalResult PrevResult; 12228 while (!Queue.empty()) 12229 process(PrevResult); 12230 12231 if (PrevResult.Failed) return false; 12232 12233 FinalResult.swap(PrevResult.Val); 12234 return true; 12235 } 12236 12237 private: 12238 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12239 return IntEval.Success(Value, E, Result); 12240 } 12241 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12242 return IntEval.Success(Value, E, Result); 12243 } 12244 bool Error(const Expr *E) { 12245 return IntEval.Error(E); 12246 } 12247 bool Error(const Expr *E, diag::kind D) { 12248 return IntEval.Error(E, D); 12249 } 12250 12251 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12252 return Info.CCEDiag(E, D); 12253 } 12254 12255 // Returns true if visiting the RHS is necessary, false otherwise. 12256 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12257 bool &SuppressRHSDiags); 12258 12259 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12260 const BinaryOperator *E, APValue &Result); 12261 12262 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12263 Result.Failed = !Evaluate(Result.Val, Info, E); 12264 if (Result.Failed) 12265 Result.Val = APValue(); 12266 } 12267 12268 void process(EvalResult &Result); 12269 12270 void enqueue(const Expr *E) { 12271 E = E->IgnoreParens(); 12272 Queue.resize(Queue.size()+1); 12273 Queue.back().E = E; 12274 Queue.back().Kind = Job::AnyExprKind; 12275 } 12276 }; 12277 12278 } 12279 12280 bool DataRecursiveIntBinOpEvaluator:: 12281 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12282 bool &SuppressRHSDiags) { 12283 if (E->getOpcode() == BO_Comma) { 12284 // Ignore LHS but note if we could not evaluate it. 12285 if (LHSResult.Failed) 12286 return Info.noteSideEffect(); 12287 return true; 12288 } 12289 12290 if (E->isLogicalOp()) { 12291 bool LHSAsBool; 12292 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12293 // We were able to evaluate the LHS, see if we can get away with not 12294 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12295 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12296 Success(LHSAsBool, E, LHSResult.Val); 12297 return false; // Ignore RHS 12298 } 12299 } else { 12300 LHSResult.Failed = true; 12301 12302 // Since we weren't able to evaluate the left hand side, it 12303 // might have had side effects. 12304 if (!Info.noteSideEffect()) 12305 return false; 12306 12307 // We can't evaluate the LHS; however, sometimes the result 12308 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12309 // Don't ignore RHS and suppress diagnostics from this arm. 12310 SuppressRHSDiags = true; 12311 } 12312 12313 return true; 12314 } 12315 12316 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12317 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12318 12319 if (LHSResult.Failed && !Info.noteFailure()) 12320 return false; // Ignore RHS; 12321 12322 return true; 12323 } 12324 12325 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12326 bool IsSub) { 12327 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12328 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12329 // offsets. 12330 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12331 CharUnits &Offset = LVal.getLValueOffset(); 12332 uint64_t Offset64 = Offset.getQuantity(); 12333 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12334 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12335 : Offset64 + Index64); 12336 } 12337 12338 bool DataRecursiveIntBinOpEvaluator:: 12339 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12340 const BinaryOperator *E, APValue &Result) { 12341 if (E->getOpcode() == BO_Comma) { 12342 if (RHSResult.Failed) 12343 return false; 12344 Result = RHSResult.Val; 12345 return true; 12346 } 12347 12348 if (E->isLogicalOp()) { 12349 bool lhsResult, rhsResult; 12350 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12351 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12352 12353 if (LHSIsOK) { 12354 if (RHSIsOK) { 12355 if (E->getOpcode() == BO_LOr) 12356 return Success(lhsResult || rhsResult, E, Result); 12357 else 12358 return Success(lhsResult && rhsResult, E, Result); 12359 } 12360 } else { 12361 if (RHSIsOK) { 12362 // We can't evaluate the LHS; however, sometimes the result 12363 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12364 if (rhsResult == (E->getOpcode() == BO_LOr)) 12365 return Success(rhsResult, E, Result); 12366 } 12367 } 12368 12369 return false; 12370 } 12371 12372 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12373 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12374 12375 if (LHSResult.Failed || RHSResult.Failed) 12376 return false; 12377 12378 const APValue &LHSVal = LHSResult.Val; 12379 const APValue &RHSVal = RHSResult.Val; 12380 12381 // Handle cases like (unsigned long)&a + 4. 12382 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12383 Result = LHSVal; 12384 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12385 return true; 12386 } 12387 12388 // Handle cases like 4 + (unsigned long)&a 12389 if (E->getOpcode() == BO_Add && 12390 RHSVal.isLValue() && LHSVal.isInt()) { 12391 Result = RHSVal; 12392 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12393 return true; 12394 } 12395 12396 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12397 // Handle (intptr_t)&&A - (intptr_t)&&B. 12398 if (!LHSVal.getLValueOffset().isZero() || 12399 !RHSVal.getLValueOffset().isZero()) 12400 return false; 12401 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12402 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12403 if (!LHSExpr || !RHSExpr) 12404 return false; 12405 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12406 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12407 if (!LHSAddrExpr || !RHSAddrExpr) 12408 return false; 12409 // Make sure both labels come from the same function. 12410 if (LHSAddrExpr->getLabel()->getDeclContext() != 12411 RHSAddrExpr->getLabel()->getDeclContext()) 12412 return false; 12413 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12414 return true; 12415 } 12416 12417 // All the remaining cases expect both operands to be an integer 12418 if (!LHSVal.isInt() || !RHSVal.isInt()) 12419 return Error(E); 12420 12421 // Set up the width and signedness manually, in case it can't be deduced 12422 // from the operation we're performing. 12423 // FIXME: Don't do this in the cases where we can deduce it. 12424 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12425 E->getType()->isUnsignedIntegerOrEnumerationType()); 12426 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12427 RHSVal.getInt(), Value)) 12428 return false; 12429 return Success(Value, E, Result); 12430 } 12431 12432 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12433 Job &job = Queue.back(); 12434 12435 switch (job.Kind) { 12436 case Job::AnyExprKind: { 12437 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12438 if (shouldEnqueue(Bop)) { 12439 job.Kind = Job::BinOpKind; 12440 enqueue(Bop->getLHS()); 12441 return; 12442 } 12443 } 12444 12445 EvaluateExpr(job.E, Result); 12446 Queue.pop_back(); 12447 return; 12448 } 12449 12450 case Job::BinOpKind: { 12451 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12452 bool SuppressRHSDiags = false; 12453 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12454 Queue.pop_back(); 12455 return; 12456 } 12457 if (SuppressRHSDiags) 12458 job.startSpeculativeEval(Info); 12459 job.LHSResult.swap(Result); 12460 job.Kind = Job::BinOpVisitedLHSKind; 12461 enqueue(Bop->getRHS()); 12462 return; 12463 } 12464 12465 case Job::BinOpVisitedLHSKind: { 12466 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12467 EvalResult RHS; 12468 RHS.swap(Result); 12469 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12470 Queue.pop_back(); 12471 return; 12472 } 12473 } 12474 12475 llvm_unreachable("Invalid Job::Kind!"); 12476 } 12477 12478 namespace { 12479 enum class CmpResult { 12480 Unequal, 12481 Less, 12482 Equal, 12483 Greater, 12484 Unordered, 12485 }; 12486 } 12487 12488 template <class SuccessCB, class AfterCB> 12489 static bool 12490 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12491 SuccessCB &&Success, AfterCB &&DoAfter) { 12492 assert(!E->isValueDependent()); 12493 assert(E->isComparisonOp() && "expected comparison operator"); 12494 assert((E->getOpcode() == BO_Cmp || 12495 E->getType()->isIntegralOrEnumerationType()) && 12496 "unsupported binary expression evaluation"); 12497 auto Error = [&](const Expr *E) { 12498 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12499 return false; 12500 }; 12501 12502 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12503 bool IsEquality = E->isEqualityOp(); 12504 12505 QualType LHSTy = E->getLHS()->getType(); 12506 QualType RHSTy = E->getRHS()->getType(); 12507 12508 if (LHSTy->isIntegralOrEnumerationType() && 12509 RHSTy->isIntegralOrEnumerationType()) { 12510 APSInt LHS, RHS; 12511 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12512 if (!LHSOK && !Info.noteFailure()) 12513 return false; 12514 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12515 return false; 12516 if (LHS < RHS) 12517 return Success(CmpResult::Less, E); 12518 if (LHS > RHS) 12519 return Success(CmpResult::Greater, E); 12520 return Success(CmpResult::Equal, E); 12521 } 12522 12523 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12524 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12525 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12526 12527 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12528 if (!LHSOK && !Info.noteFailure()) 12529 return false; 12530 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12531 return false; 12532 if (LHSFX < RHSFX) 12533 return Success(CmpResult::Less, E); 12534 if (LHSFX > RHSFX) 12535 return Success(CmpResult::Greater, E); 12536 return Success(CmpResult::Equal, E); 12537 } 12538 12539 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12540 ComplexValue LHS, RHS; 12541 bool LHSOK; 12542 if (E->isAssignmentOp()) { 12543 LValue LV; 12544 EvaluateLValue(E->getLHS(), LV, Info); 12545 LHSOK = false; 12546 } else if (LHSTy->isRealFloatingType()) { 12547 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12548 if (LHSOK) { 12549 LHS.makeComplexFloat(); 12550 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12551 } 12552 } else { 12553 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12554 } 12555 if (!LHSOK && !Info.noteFailure()) 12556 return false; 12557 12558 if (E->getRHS()->getType()->isRealFloatingType()) { 12559 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12560 return false; 12561 RHS.makeComplexFloat(); 12562 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12563 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12564 return false; 12565 12566 if (LHS.isComplexFloat()) { 12567 APFloat::cmpResult CR_r = 12568 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12569 APFloat::cmpResult CR_i = 12570 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12571 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12572 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12573 } else { 12574 assert(IsEquality && "invalid complex comparison"); 12575 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12576 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12577 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12578 } 12579 } 12580 12581 if (LHSTy->isRealFloatingType() && 12582 RHSTy->isRealFloatingType()) { 12583 APFloat RHS(0.0), LHS(0.0); 12584 12585 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12586 if (!LHSOK && !Info.noteFailure()) 12587 return false; 12588 12589 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12590 return false; 12591 12592 assert(E->isComparisonOp() && "Invalid binary operator!"); 12593 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12594 if (!Info.InConstantContext && 12595 APFloatCmpResult == APFloat::cmpUnordered && 12596 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12597 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12598 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12599 return false; 12600 } 12601 auto GetCmpRes = [&]() { 12602 switch (APFloatCmpResult) { 12603 case APFloat::cmpEqual: 12604 return CmpResult::Equal; 12605 case APFloat::cmpLessThan: 12606 return CmpResult::Less; 12607 case APFloat::cmpGreaterThan: 12608 return CmpResult::Greater; 12609 case APFloat::cmpUnordered: 12610 return CmpResult::Unordered; 12611 } 12612 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12613 }; 12614 return Success(GetCmpRes(), E); 12615 } 12616 12617 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12618 LValue LHSValue, RHSValue; 12619 12620 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12621 if (!LHSOK && !Info.noteFailure()) 12622 return false; 12623 12624 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12625 return false; 12626 12627 // Reject differing bases from the normal codepath; we special-case 12628 // comparisons to null. 12629 if (!HasSameBase(LHSValue, RHSValue)) { 12630 // Inequalities and subtractions between unrelated pointers have 12631 // unspecified or undefined behavior. 12632 if (!IsEquality) { 12633 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12634 return false; 12635 } 12636 // A constant address may compare equal to the address of a symbol. 12637 // The one exception is that address of an object cannot compare equal 12638 // to a null pointer constant. 12639 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12640 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12641 return Error(E); 12642 // It's implementation-defined whether distinct literals will have 12643 // distinct addresses. In clang, the result of such a comparison is 12644 // unspecified, so it is not a constant expression. However, we do know 12645 // that the address of a literal will be non-null. 12646 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12647 LHSValue.Base && RHSValue.Base) 12648 return Error(E); 12649 // We can't tell whether weak symbols will end up pointing to the same 12650 // object. 12651 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12652 return Error(E); 12653 // We can't compare the address of the start of one object with the 12654 // past-the-end address of another object, per C++ DR1652. 12655 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12656 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12657 (RHSValue.Base && RHSValue.Offset.isZero() && 12658 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12659 return Error(E); 12660 // We can't tell whether an object is at the same address as another 12661 // zero sized object. 12662 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12663 (LHSValue.Base && isZeroSized(RHSValue))) 12664 return Error(E); 12665 return Success(CmpResult::Unequal, E); 12666 } 12667 12668 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12669 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12670 12671 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12672 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12673 12674 // C++11 [expr.rel]p3: 12675 // Pointers to void (after pointer conversions) can be compared, with a 12676 // result defined as follows: If both pointers represent the same 12677 // address or are both the null pointer value, the result is true if the 12678 // operator is <= or >= and false otherwise; otherwise the result is 12679 // unspecified. 12680 // We interpret this as applying to pointers to *cv* void. 12681 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12682 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12683 12684 // C++11 [expr.rel]p2: 12685 // - If two pointers point to non-static data members of the same object, 12686 // or to subobjects or array elements fo such members, recursively, the 12687 // pointer to the later declared member compares greater provided the 12688 // two members have the same access control and provided their class is 12689 // not a union. 12690 // [...] 12691 // - Otherwise pointer comparisons are unspecified. 12692 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12693 bool WasArrayIndex; 12694 unsigned Mismatch = FindDesignatorMismatch( 12695 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12696 // At the point where the designators diverge, the comparison has a 12697 // specified value if: 12698 // - we are comparing array indices 12699 // - we are comparing fields of a union, or fields with the same access 12700 // Otherwise, the result is unspecified and thus the comparison is not a 12701 // constant expression. 12702 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12703 Mismatch < RHSDesignator.Entries.size()) { 12704 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12705 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12706 if (!LF && !RF) 12707 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12708 else if (!LF) 12709 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12710 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12711 << RF->getParent() << RF; 12712 else if (!RF) 12713 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12714 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12715 << LF->getParent() << LF; 12716 else if (!LF->getParent()->isUnion() && 12717 LF->getAccess() != RF->getAccess()) 12718 Info.CCEDiag(E, 12719 diag::note_constexpr_pointer_comparison_differing_access) 12720 << LF << LF->getAccess() << RF << RF->getAccess() 12721 << LF->getParent(); 12722 } 12723 } 12724 12725 // The comparison here must be unsigned, and performed with the same 12726 // width as the pointer. 12727 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12728 uint64_t CompareLHS = LHSOffset.getQuantity(); 12729 uint64_t CompareRHS = RHSOffset.getQuantity(); 12730 assert(PtrSize <= 64 && "Unexpected pointer width"); 12731 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12732 CompareLHS &= Mask; 12733 CompareRHS &= Mask; 12734 12735 // If there is a base and this is a relational operator, we can only 12736 // compare pointers within the object in question; otherwise, the result 12737 // depends on where the object is located in memory. 12738 if (!LHSValue.Base.isNull() && IsRelational) { 12739 QualType BaseTy = getType(LHSValue.Base); 12740 if (BaseTy->isIncompleteType()) 12741 return Error(E); 12742 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12743 uint64_t OffsetLimit = Size.getQuantity(); 12744 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12745 return Error(E); 12746 } 12747 12748 if (CompareLHS < CompareRHS) 12749 return Success(CmpResult::Less, E); 12750 if (CompareLHS > CompareRHS) 12751 return Success(CmpResult::Greater, E); 12752 return Success(CmpResult::Equal, E); 12753 } 12754 12755 if (LHSTy->isMemberPointerType()) { 12756 assert(IsEquality && "unexpected member pointer operation"); 12757 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12758 12759 MemberPtr LHSValue, RHSValue; 12760 12761 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12762 if (!LHSOK && !Info.noteFailure()) 12763 return false; 12764 12765 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12766 return false; 12767 12768 // C++11 [expr.eq]p2: 12769 // If both operands are null, they compare equal. Otherwise if only one is 12770 // null, they compare unequal. 12771 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12772 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12773 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12774 } 12775 12776 // Otherwise if either is a pointer to a virtual member function, the 12777 // result is unspecified. 12778 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12779 if (MD->isVirtual()) 12780 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12781 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12782 if (MD->isVirtual()) 12783 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12784 12785 // Otherwise they compare equal if and only if they would refer to the 12786 // same member of the same most derived object or the same subobject if 12787 // they were dereferenced with a hypothetical object of the associated 12788 // class type. 12789 bool Equal = LHSValue == RHSValue; 12790 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12791 } 12792 12793 if (LHSTy->isNullPtrType()) { 12794 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12795 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12796 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12797 // are compared, the result is true of the operator is <=, >= or ==, and 12798 // false otherwise. 12799 return Success(CmpResult::Equal, E); 12800 } 12801 12802 return DoAfter(); 12803 } 12804 12805 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12806 if (!CheckLiteralType(Info, E)) 12807 return false; 12808 12809 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12810 ComparisonCategoryResult CCR; 12811 switch (CR) { 12812 case CmpResult::Unequal: 12813 llvm_unreachable("should never produce Unequal for three-way comparison"); 12814 case CmpResult::Less: 12815 CCR = ComparisonCategoryResult::Less; 12816 break; 12817 case CmpResult::Equal: 12818 CCR = ComparisonCategoryResult::Equal; 12819 break; 12820 case CmpResult::Greater: 12821 CCR = ComparisonCategoryResult::Greater; 12822 break; 12823 case CmpResult::Unordered: 12824 CCR = ComparisonCategoryResult::Unordered; 12825 break; 12826 } 12827 // Evaluation succeeded. Lookup the information for the comparison category 12828 // type and fetch the VarDecl for the result. 12829 const ComparisonCategoryInfo &CmpInfo = 12830 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12831 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12832 // Check and evaluate the result as a constant expression. 12833 LValue LV; 12834 LV.set(VD); 12835 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12836 return false; 12837 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12838 ConstantExprKind::Normal); 12839 }; 12840 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12841 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12842 }); 12843 } 12844 12845 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12846 // We don't support assignment in C. C++ assignments don't get here because 12847 // assignment is an lvalue in C++. 12848 if (E->isAssignmentOp()) { 12849 Error(E); 12850 if (!Info.noteFailure()) 12851 return false; 12852 } 12853 12854 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12855 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12856 12857 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12858 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12859 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12860 12861 if (E->isComparisonOp()) { 12862 // Evaluate builtin binary comparisons by evaluating them as three-way 12863 // comparisons and then translating the result. 12864 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12865 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12866 "should only produce Unequal for equality comparisons"); 12867 bool IsEqual = CR == CmpResult::Equal, 12868 IsLess = CR == CmpResult::Less, 12869 IsGreater = CR == CmpResult::Greater; 12870 auto Op = E->getOpcode(); 12871 switch (Op) { 12872 default: 12873 llvm_unreachable("unsupported binary operator"); 12874 case BO_EQ: 12875 case BO_NE: 12876 return Success(IsEqual == (Op == BO_EQ), E); 12877 case BO_LT: 12878 return Success(IsLess, E); 12879 case BO_GT: 12880 return Success(IsGreater, E); 12881 case BO_LE: 12882 return Success(IsEqual || IsLess, E); 12883 case BO_GE: 12884 return Success(IsEqual || IsGreater, E); 12885 } 12886 }; 12887 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12888 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12889 }); 12890 } 12891 12892 QualType LHSTy = E->getLHS()->getType(); 12893 QualType RHSTy = E->getRHS()->getType(); 12894 12895 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12896 E->getOpcode() == BO_Sub) { 12897 LValue LHSValue, RHSValue; 12898 12899 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12900 if (!LHSOK && !Info.noteFailure()) 12901 return false; 12902 12903 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12904 return false; 12905 12906 // Reject differing bases from the normal codepath; we special-case 12907 // comparisons to null. 12908 if (!HasSameBase(LHSValue, RHSValue)) { 12909 // Handle &&A - &&B. 12910 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12911 return Error(E); 12912 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12913 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12914 if (!LHSExpr || !RHSExpr) 12915 return Error(E); 12916 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12917 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12918 if (!LHSAddrExpr || !RHSAddrExpr) 12919 return Error(E); 12920 // Make sure both labels come from the same function. 12921 if (LHSAddrExpr->getLabel()->getDeclContext() != 12922 RHSAddrExpr->getLabel()->getDeclContext()) 12923 return Error(E); 12924 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12925 } 12926 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12927 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12928 12929 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12930 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12931 12932 // C++11 [expr.add]p6: 12933 // Unless both pointers point to elements of the same array object, or 12934 // one past the last element of the array object, the behavior is 12935 // undefined. 12936 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12937 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12938 RHSDesignator)) 12939 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12940 12941 QualType Type = E->getLHS()->getType(); 12942 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12943 12944 CharUnits ElementSize; 12945 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12946 return false; 12947 12948 // As an extension, a type may have zero size (empty struct or union in 12949 // C, array of zero length). Pointer subtraction in such cases has 12950 // undefined behavior, so is not constant. 12951 if (ElementSize.isZero()) { 12952 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12953 << ElementType; 12954 return false; 12955 } 12956 12957 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12958 // and produce incorrect results when it overflows. Such behavior 12959 // appears to be non-conforming, but is common, so perhaps we should 12960 // assume the standard intended for such cases to be undefined behavior 12961 // and check for them. 12962 12963 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12964 // overflow in the final conversion to ptrdiff_t. 12965 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12966 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12967 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12968 false); 12969 APSInt TrueResult = (LHS - RHS) / ElemSize; 12970 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12971 12972 if (Result.extend(65) != TrueResult && 12973 !HandleOverflow(Info, E, TrueResult, E->getType())) 12974 return false; 12975 return Success(Result, E); 12976 } 12977 12978 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12979 } 12980 12981 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12982 /// a result as the expression's type. 12983 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12984 const UnaryExprOrTypeTraitExpr *E) { 12985 switch(E->getKind()) { 12986 case UETT_PreferredAlignOf: 12987 case UETT_AlignOf: { 12988 if (E->isArgumentType()) 12989 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12990 E); 12991 else 12992 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12993 E); 12994 } 12995 12996 case UETT_VecStep: { 12997 QualType Ty = E->getTypeOfArgument(); 12998 12999 if (Ty->isVectorType()) { 13000 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13001 13002 // The vec_step built-in functions that take a 3-component 13003 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13004 if (n == 3) 13005 n = 4; 13006 13007 return Success(n, E); 13008 } else 13009 return Success(1, E); 13010 } 13011 13012 case UETT_SizeOf: { 13013 QualType SrcTy = E->getTypeOfArgument(); 13014 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13015 // the result is the size of the referenced type." 13016 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13017 SrcTy = Ref->getPointeeType(); 13018 13019 CharUnits Sizeof; 13020 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13021 return false; 13022 return Success(Sizeof, E); 13023 } 13024 case UETT_OpenMPRequiredSimdAlign: 13025 assert(E->isArgumentType()); 13026 return Success( 13027 Info.Ctx.toCharUnitsFromBits( 13028 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13029 .getQuantity(), 13030 E); 13031 } 13032 13033 llvm_unreachable("unknown expr/type trait"); 13034 } 13035 13036 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13037 CharUnits Result; 13038 unsigned n = OOE->getNumComponents(); 13039 if (n == 0) 13040 return Error(OOE); 13041 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13042 for (unsigned i = 0; i != n; ++i) { 13043 OffsetOfNode ON = OOE->getComponent(i); 13044 switch (ON.getKind()) { 13045 case OffsetOfNode::Array: { 13046 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13047 APSInt IdxResult; 13048 if (!EvaluateInteger(Idx, IdxResult, Info)) 13049 return false; 13050 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13051 if (!AT) 13052 return Error(OOE); 13053 CurrentType = AT->getElementType(); 13054 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13055 Result += IdxResult.getSExtValue() * ElementSize; 13056 break; 13057 } 13058 13059 case OffsetOfNode::Field: { 13060 FieldDecl *MemberDecl = ON.getField(); 13061 const RecordType *RT = CurrentType->getAs<RecordType>(); 13062 if (!RT) 13063 return Error(OOE); 13064 RecordDecl *RD = RT->getDecl(); 13065 if (RD->isInvalidDecl()) return false; 13066 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13067 unsigned i = MemberDecl->getFieldIndex(); 13068 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13069 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13070 CurrentType = MemberDecl->getType().getNonReferenceType(); 13071 break; 13072 } 13073 13074 case OffsetOfNode::Identifier: 13075 llvm_unreachable("dependent __builtin_offsetof"); 13076 13077 case OffsetOfNode::Base: { 13078 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13079 if (BaseSpec->isVirtual()) 13080 return Error(OOE); 13081 13082 // Find the layout of the class whose base we are looking into. 13083 const RecordType *RT = CurrentType->getAs<RecordType>(); 13084 if (!RT) 13085 return Error(OOE); 13086 RecordDecl *RD = RT->getDecl(); 13087 if (RD->isInvalidDecl()) return false; 13088 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13089 13090 // Find the base class itself. 13091 CurrentType = BaseSpec->getType(); 13092 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13093 if (!BaseRT) 13094 return Error(OOE); 13095 13096 // Add the offset to the base. 13097 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13098 break; 13099 } 13100 } 13101 } 13102 return Success(Result, OOE); 13103 } 13104 13105 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13106 switch (E->getOpcode()) { 13107 default: 13108 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13109 // See C99 6.6p3. 13110 return Error(E); 13111 case UO_Extension: 13112 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13113 // If so, we could clear the diagnostic ID. 13114 return Visit(E->getSubExpr()); 13115 case UO_Plus: 13116 // The result is just the value. 13117 return Visit(E->getSubExpr()); 13118 case UO_Minus: { 13119 if (!Visit(E->getSubExpr())) 13120 return false; 13121 if (!Result.isInt()) return Error(E); 13122 const APSInt &Value = Result.getInt(); 13123 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13124 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13125 E->getType())) 13126 return false; 13127 return Success(-Value, E); 13128 } 13129 case UO_Not: { 13130 if (!Visit(E->getSubExpr())) 13131 return false; 13132 if (!Result.isInt()) return Error(E); 13133 return Success(~Result.getInt(), E); 13134 } 13135 case UO_LNot: { 13136 bool bres; 13137 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13138 return false; 13139 return Success(!bres, E); 13140 } 13141 } 13142 } 13143 13144 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13145 /// result type is integer. 13146 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13147 const Expr *SubExpr = E->getSubExpr(); 13148 QualType DestType = E->getType(); 13149 QualType SrcType = SubExpr->getType(); 13150 13151 switch (E->getCastKind()) { 13152 case CK_BaseToDerived: 13153 case CK_DerivedToBase: 13154 case CK_UncheckedDerivedToBase: 13155 case CK_Dynamic: 13156 case CK_ToUnion: 13157 case CK_ArrayToPointerDecay: 13158 case CK_FunctionToPointerDecay: 13159 case CK_NullToPointer: 13160 case CK_NullToMemberPointer: 13161 case CK_BaseToDerivedMemberPointer: 13162 case CK_DerivedToBaseMemberPointer: 13163 case CK_ReinterpretMemberPointer: 13164 case CK_ConstructorConversion: 13165 case CK_IntegralToPointer: 13166 case CK_ToVoid: 13167 case CK_VectorSplat: 13168 case CK_IntegralToFloating: 13169 case CK_FloatingCast: 13170 case CK_CPointerToObjCPointerCast: 13171 case CK_BlockPointerToObjCPointerCast: 13172 case CK_AnyPointerToBlockPointerCast: 13173 case CK_ObjCObjectLValueCast: 13174 case CK_FloatingRealToComplex: 13175 case CK_FloatingComplexToReal: 13176 case CK_FloatingComplexCast: 13177 case CK_FloatingComplexToIntegralComplex: 13178 case CK_IntegralRealToComplex: 13179 case CK_IntegralComplexCast: 13180 case CK_IntegralComplexToFloatingComplex: 13181 case CK_BuiltinFnToFnPtr: 13182 case CK_ZeroToOCLOpaqueType: 13183 case CK_NonAtomicToAtomic: 13184 case CK_AddressSpaceConversion: 13185 case CK_IntToOCLSampler: 13186 case CK_FloatingToFixedPoint: 13187 case CK_FixedPointToFloating: 13188 case CK_FixedPointCast: 13189 case CK_IntegralToFixedPoint: 13190 case CK_MatrixCast: 13191 llvm_unreachable("invalid cast kind for integral value"); 13192 13193 case CK_BitCast: 13194 case CK_Dependent: 13195 case CK_LValueBitCast: 13196 case CK_ARCProduceObject: 13197 case CK_ARCConsumeObject: 13198 case CK_ARCReclaimReturnedObject: 13199 case CK_ARCExtendBlockObject: 13200 case CK_CopyAndAutoreleaseBlockObject: 13201 return Error(E); 13202 13203 case CK_UserDefinedConversion: 13204 case CK_LValueToRValue: 13205 case CK_AtomicToNonAtomic: 13206 case CK_NoOp: 13207 case CK_LValueToRValueBitCast: 13208 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13209 13210 case CK_MemberPointerToBoolean: 13211 case CK_PointerToBoolean: 13212 case CK_IntegralToBoolean: 13213 case CK_FloatingToBoolean: 13214 case CK_BooleanToSignedIntegral: 13215 case CK_FloatingComplexToBoolean: 13216 case CK_IntegralComplexToBoolean: { 13217 bool BoolResult; 13218 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13219 return false; 13220 uint64_t IntResult = BoolResult; 13221 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13222 IntResult = (uint64_t)-1; 13223 return Success(IntResult, E); 13224 } 13225 13226 case CK_FixedPointToIntegral: { 13227 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13228 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13229 return false; 13230 bool Overflowed; 13231 llvm::APSInt Result = Src.convertToInt( 13232 Info.Ctx.getIntWidth(DestType), 13233 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13234 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13235 return false; 13236 return Success(Result, E); 13237 } 13238 13239 case CK_FixedPointToBoolean: { 13240 // Unsigned padding does not affect this. 13241 APValue Val; 13242 if (!Evaluate(Val, Info, SubExpr)) 13243 return false; 13244 return Success(Val.getFixedPoint().getBoolValue(), E); 13245 } 13246 13247 case CK_IntegralCast: { 13248 if (!Visit(SubExpr)) 13249 return false; 13250 13251 if (!Result.isInt()) { 13252 // Allow casts of address-of-label differences if they are no-ops 13253 // or narrowing. (The narrowing case isn't actually guaranteed to 13254 // be constant-evaluatable except in some narrow cases which are hard 13255 // to detect here. We let it through on the assumption the user knows 13256 // what they are doing.) 13257 if (Result.isAddrLabelDiff()) 13258 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13259 // Only allow casts of lvalues if they are lossless. 13260 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13261 } 13262 13263 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13264 Result.getInt()), E); 13265 } 13266 13267 case CK_PointerToIntegral: { 13268 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13269 13270 LValue LV; 13271 if (!EvaluatePointer(SubExpr, LV, Info)) 13272 return false; 13273 13274 if (LV.getLValueBase()) { 13275 // Only allow based lvalue casts if they are lossless. 13276 // FIXME: Allow a larger integer size than the pointer size, and allow 13277 // narrowing back down to pointer width in subsequent integral casts. 13278 // FIXME: Check integer type's active bits, not its type size. 13279 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13280 return Error(E); 13281 13282 LV.Designator.setInvalid(); 13283 LV.moveInto(Result); 13284 return true; 13285 } 13286 13287 APSInt AsInt; 13288 APValue V; 13289 LV.moveInto(V); 13290 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13291 llvm_unreachable("Can't cast this!"); 13292 13293 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13294 } 13295 13296 case CK_IntegralComplexToReal: { 13297 ComplexValue C; 13298 if (!EvaluateComplex(SubExpr, C, Info)) 13299 return false; 13300 return Success(C.getComplexIntReal(), E); 13301 } 13302 13303 case CK_FloatingToIntegral: { 13304 APFloat F(0.0); 13305 if (!EvaluateFloat(SubExpr, F, Info)) 13306 return false; 13307 13308 APSInt Value; 13309 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13310 return false; 13311 return Success(Value, E); 13312 } 13313 } 13314 13315 llvm_unreachable("unknown cast resulting in integral value"); 13316 } 13317 13318 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13319 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13320 ComplexValue LV; 13321 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13322 return false; 13323 if (!LV.isComplexInt()) 13324 return Error(E); 13325 return Success(LV.getComplexIntReal(), E); 13326 } 13327 13328 return Visit(E->getSubExpr()); 13329 } 13330 13331 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13332 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13333 ComplexValue LV; 13334 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13335 return false; 13336 if (!LV.isComplexInt()) 13337 return Error(E); 13338 return Success(LV.getComplexIntImag(), E); 13339 } 13340 13341 VisitIgnoredValue(E->getSubExpr()); 13342 return Success(0, E); 13343 } 13344 13345 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13346 return Success(E->getPackLength(), E); 13347 } 13348 13349 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13350 return Success(E->getValue(), E); 13351 } 13352 13353 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13354 const ConceptSpecializationExpr *E) { 13355 return Success(E->isSatisfied(), E); 13356 } 13357 13358 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13359 return Success(E->isSatisfied(), E); 13360 } 13361 13362 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13363 switch (E->getOpcode()) { 13364 default: 13365 // Invalid unary operators 13366 return Error(E); 13367 case UO_Plus: 13368 // The result is just the value. 13369 return Visit(E->getSubExpr()); 13370 case UO_Minus: { 13371 if (!Visit(E->getSubExpr())) return false; 13372 if (!Result.isFixedPoint()) 13373 return Error(E); 13374 bool Overflowed; 13375 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13376 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13377 return false; 13378 return Success(Negated, E); 13379 } 13380 case UO_LNot: { 13381 bool bres; 13382 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13383 return false; 13384 return Success(!bres, E); 13385 } 13386 } 13387 } 13388 13389 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13390 const Expr *SubExpr = E->getSubExpr(); 13391 QualType DestType = E->getType(); 13392 assert(DestType->isFixedPointType() && 13393 "Expected destination type to be a fixed point type"); 13394 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13395 13396 switch (E->getCastKind()) { 13397 case CK_FixedPointCast: { 13398 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13399 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13400 return false; 13401 bool Overflowed; 13402 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13403 if (Overflowed) { 13404 if (Info.checkingForUndefinedBehavior()) 13405 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13406 diag::warn_fixedpoint_constant_overflow) 13407 << Result.toString() << E->getType(); 13408 if (!HandleOverflow(Info, E, Result, E->getType())) 13409 return false; 13410 } 13411 return Success(Result, E); 13412 } 13413 case CK_IntegralToFixedPoint: { 13414 APSInt Src; 13415 if (!EvaluateInteger(SubExpr, Src, Info)) 13416 return false; 13417 13418 bool Overflowed; 13419 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13420 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13421 13422 if (Overflowed) { 13423 if (Info.checkingForUndefinedBehavior()) 13424 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13425 diag::warn_fixedpoint_constant_overflow) 13426 << IntResult.toString() << E->getType(); 13427 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13428 return false; 13429 } 13430 13431 return Success(IntResult, E); 13432 } 13433 case CK_FloatingToFixedPoint: { 13434 APFloat Src(0.0); 13435 if (!EvaluateFloat(SubExpr, Src, Info)) 13436 return false; 13437 13438 bool Overflowed; 13439 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13440 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13441 13442 if (Overflowed) { 13443 if (Info.checkingForUndefinedBehavior()) 13444 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13445 diag::warn_fixedpoint_constant_overflow) 13446 << Result.toString() << E->getType(); 13447 if (!HandleOverflow(Info, E, Result, E->getType())) 13448 return false; 13449 } 13450 13451 return Success(Result, E); 13452 } 13453 case CK_NoOp: 13454 case CK_LValueToRValue: 13455 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13456 default: 13457 return Error(E); 13458 } 13459 } 13460 13461 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13462 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13463 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13464 13465 const Expr *LHS = E->getLHS(); 13466 const Expr *RHS = E->getRHS(); 13467 FixedPointSemantics ResultFXSema = 13468 Info.Ctx.getFixedPointSemantics(E->getType()); 13469 13470 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13471 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13472 return false; 13473 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13474 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13475 return false; 13476 13477 bool OpOverflow = false, ConversionOverflow = false; 13478 APFixedPoint Result(LHSFX.getSemantics()); 13479 switch (E->getOpcode()) { 13480 case BO_Add: { 13481 Result = LHSFX.add(RHSFX, &OpOverflow) 13482 .convert(ResultFXSema, &ConversionOverflow); 13483 break; 13484 } 13485 case BO_Sub: { 13486 Result = LHSFX.sub(RHSFX, &OpOverflow) 13487 .convert(ResultFXSema, &ConversionOverflow); 13488 break; 13489 } 13490 case BO_Mul: { 13491 Result = LHSFX.mul(RHSFX, &OpOverflow) 13492 .convert(ResultFXSema, &ConversionOverflow); 13493 break; 13494 } 13495 case BO_Div: { 13496 if (RHSFX.getValue() == 0) { 13497 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13498 return false; 13499 } 13500 Result = LHSFX.div(RHSFX, &OpOverflow) 13501 .convert(ResultFXSema, &ConversionOverflow); 13502 break; 13503 } 13504 case BO_Shl: 13505 case BO_Shr: { 13506 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13507 llvm::APSInt RHSVal = RHSFX.getValue(); 13508 13509 unsigned ShiftBW = 13510 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13511 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13512 // Embedded-C 4.1.6.2.2: 13513 // The right operand must be nonnegative and less than the total number 13514 // of (nonpadding) bits of the fixed-point operand ... 13515 if (RHSVal.isNegative()) 13516 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13517 else if (Amt != RHSVal) 13518 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13519 << RHSVal << E->getType() << ShiftBW; 13520 13521 if (E->getOpcode() == BO_Shl) 13522 Result = LHSFX.shl(Amt, &OpOverflow); 13523 else 13524 Result = LHSFX.shr(Amt, &OpOverflow); 13525 break; 13526 } 13527 default: 13528 return false; 13529 } 13530 if (OpOverflow || ConversionOverflow) { 13531 if (Info.checkingForUndefinedBehavior()) 13532 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13533 diag::warn_fixedpoint_constant_overflow) 13534 << Result.toString() << E->getType(); 13535 if (!HandleOverflow(Info, E, Result, E->getType())) 13536 return false; 13537 } 13538 return Success(Result, E); 13539 } 13540 13541 //===----------------------------------------------------------------------===// 13542 // Float Evaluation 13543 //===----------------------------------------------------------------------===// 13544 13545 namespace { 13546 class FloatExprEvaluator 13547 : public ExprEvaluatorBase<FloatExprEvaluator> { 13548 APFloat &Result; 13549 public: 13550 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13551 : ExprEvaluatorBaseTy(info), Result(result) {} 13552 13553 bool Success(const APValue &V, const Expr *e) { 13554 Result = V.getFloat(); 13555 return true; 13556 } 13557 13558 bool ZeroInitialization(const Expr *E) { 13559 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13560 return true; 13561 } 13562 13563 bool VisitCallExpr(const CallExpr *E); 13564 13565 bool VisitUnaryOperator(const UnaryOperator *E); 13566 bool VisitBinaryOperator(const BinaryOperator *E); 13567 bool VisitFloatingLiteral(const FloatingLiteral *E); 13568 bool VisitCastExpr(const CastExpr *E); 13569 13570 bool VisitUnaryReal(const UnaryOperator *E); 13571 bool VisitUnaryImag(const UnaryOperator *E); 13572 13573 // FIXME: Missing: array subscript of vector, member of vector 13574 }; 13575 } // end anonymous namespace 13576 13577 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13578 assert(!E->isValueDependent()); 13579 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13580 return FloatExprEvaluator(Info, Result).Visit(E); 13581 } 13582 13583 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13584 QualType ResultTy, 13585 const Expr *Arg, 13586 bool SNaN, 13587 llvm::APFloat &Result) { 13588 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13589 if (!S) return false; 13590 13591 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13592 13593 llvm::APInt fill; 13594 13595 // Treat empty strings as if they were zero. 13596 if (S->getString().empty()) 13597 fill = llvm::APInt(32, 0); 13598 else if (S->getString().getAsInteger(0, fill)) 13599 return false; 13600 13601 if (Context.getTargetInfo().isNan2008()) { 13602 if (SNaN) 13603 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13604 else 13605 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13606 } else { 13607 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13608 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13609 // a different encoding to what became a standard in 2008, and for pre- 13610 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13611 // sNaN. This is now known as "legacy NaN" encoding. 13612 if (SNaN) 13613 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13614 else 13615 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13616 } 13617 13618 return true; 13619 } 13620 13621 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13622 switch (E->getBuiltinCallee()) { 13623 default: 13624 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13625 13626 case Builtin::BI__builtin_huge_val: 13627 case Builtin::BI__builtin_huge_valf: 13628 case Builtin::BI__builtin_huge_vall: 13629 case Builtin::BI__builtin_huge_valf128: 13630 case Builtin::BI__builtin_inf: 13631 case Builtin::BI__builtin_inff: 13632 case Builtin::BI__builtin_infl: 13633 case Builtin::BI__builtin_inff128: { 13634 const llvm::fltSemantics &Sem = 13635 Info.Ctx.getFloatTypeSemantics(E->getType()); 13636 Result = llvm::APFloat::getInf(Sem); 13637 return true; 13638 } 13639 13640 case Builtin::BI__builtin_nans: 13641 case Builtin::BI__builtin_nansf: 13642 case Builtin::BI__builtin_nansl: 13643 case Builtin::BI__builtin_nansf128: 13644 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13645 true, Result)) 13646 return Error(E); 13647 return true; 13648 13649 case Builtin::BI__builtin_nan: 13650 case Builtin::BI__builtin_nanf: 13651 case Builtin::BI__builtin_nanl: 13652 case Builtin::BI__builtin_nanf128: 13653 // If this is __builtin_nan() turn this into a nan, otherwise we 13654 // can't constant fold it. 13655 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13656 false, Result)) 13657 return Error(E); 13658 return true; 13659 13660 case Builtin::BI__builtin_fabs: 13661 case Builtin::BI__builtin_fabsf: 13662 case Builtin::BI__builtin_fabsl: 13663 case Builtin::BI__builtin_fabsf128: 13664 // The C standard says "fabs raises no floating-point exceptions, 13665 // even if x is a signaling NaN. The returned value is independent of 13666 // the current rounding direction mode." Therefore constant folding can 13667 // proceed without regard to the floating point settings. 13668 // Reference, WG14 N2478 F.10.4.3 13669 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13670 return false; 13671 13672 if (Result.isNegative()) 13673 Result.changeSign(); 13674 return true; 13675 13676 case Builtin::BI__arithmetic_fence: 13677 return EvaluateFloat(E->getArg(0), Result, Info); 13678 13679 // FIXME: Builtin::BI__builtin_powi 13680 // FIXME: Builtin::BI__builtin_powif 13681 // FIXME: Builtin::BI__builtin_powil 13682 13683 case Builtin::BI__builtin_copysign: 13684 case Builtin::BI__builtin_copysignf: 13685 case Builtin::BI__builtin_copysignl: 13686 case Builtin::BI__builtin_copysignf128: { 13687 APFloat RHS(0.); 13688 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13689 !EvaluateFloat(E->getArg(1), RHS, Info)) 13690 return false; 13691 Result.copySign(RHS); 13692 return true; 13693 } 13694 } 13695 } 13696 13697 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13698 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13699 ComplexValue CV; 13700 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13701 return false; 13702 Result = CV.FloatReal; 13703 return true; 13704 } 13705 13706 return Visit(E->getSubExpr()); 13707 } 13708 13709 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13710 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13711 ComplexValue CV; 13712 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13713 return false; 13714 Result = CV.FloatImag; 13715 return true; 13716 } 13717 13718 VisitIgnoredValue(E->getSubExpr()); 13719 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13720 Result = llvm::APFloat::getZero(Sem); 13721 return true; 13722 } 13723 13724 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13725 switch (E->getOpcode()) { 13726 default: return Error(E); 13727 case UO_Plus: 13728 return EvaluateFloat(E->getSubExpr(), Result, Info); 13729 case UO_Minus: 13730 // In C standard, WG14 N2478 F.3 p4 13731 // "the unary - raises no floating point exceptions, 13732 // even if the operand is signalling." 13733 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13734 return false; 13735 Result.changeSign(); 13736 return true; 13737 } 13738 } 13739 13740 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13741 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13742 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13743 13744 APFloat RHS(0.0); 13745 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13746 if (!LHSOK && !Info.noteFailure()) 13747 return false; 13748 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13749 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13750 } 13751 13752 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13753 Result = E->getValue(); 13754 return true; 13755 } 13756 13757 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13758 const Expr* SubExpr = E->getSubExpr(); 13759 13760 switch (E->getCastKind()) { 13761 default: 13762 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13763 13764 case CK_IntegralToFloating: { 13765 APSInt IntResult; 13766 const FPOptions FPO = E->getFPFeaturesInEffect( 13767 Info.Ctx.getLangOpts()); 13768 return EvaluateInteger(SubExpr, IntResult, Info) && 13769 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13770 IntResult, E->getType(), Result); 13771 } 13772 13773 case CK_FixedPointToFloating: { 13774 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13775 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13776 return false; 13777 Result = 13778 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13779 return true; 13780 } 13781 13782 case CK_FloatingCast: { 13783 if (!Visit(SubExpr)) 13784 return false; 13785 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13786 Result); 13787 } 13788 13789 case CK_FloatingComplexToReal: { 13790 ComplexValue V; 13791 if (!EvaluateComplex(SubExpr, V, Info)) 13792 return false; 13793 Result = V.getComplexFloatReal(); 13794 return true; 13795 } 13796 } 13797 } 13798 13799 //===----------------------------------------------------------------------===// 13800 // Complex Evaluation (for float and integer) 13801 //===----------------------------------------------------------------------===// 13802 13803 namespace { 13804 class ComplexExprEvaluator 13805 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13806 ComplexValue &Result; 13807 13808 public: 13809 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13810 : ExprEvaluatorBaseTy(info), Result(Result) {} 13811 13812 bool Success(const APValue &V, const Expr *e) { 13813 Result.setFrom(V); 13814 return true; 13815 } 13816 13817 bool ZeroInitialization(const Expr *E); 13818 13819 //===--------------------------------------------------------------------===// 13820 // Visitor Methods 13821 //===--------------------------------------------------------------------===// 13822 13823 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13824 bool VisitCastExpr(const CastExpr *E); 13825 bool VisitBinaryOperator(const BinaryOperator *E); 13826 bool VisitUnaryOperator(const UnaryOperator *E); 13827 bool VisitInitListExpr(const InitListExpr *E); 13828 bool VisitCallExpr(const CallExpr *E); 13829 }; 13830 } // end anonymous namespace 13831 13832 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13833 EvalInfo &Info) { 13834 assert(!E->isValueDependent()); 13835 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 13836 return ComplexExprEvaluator(Info, Result).Visit(E); 13837 } 13838 13839 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13840 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13841 if (ElemTy->isRealFloatingType()) { 13842 Result.makeComplexFloat(); 13843 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13844 Result.FloatReal = Zero; 13845 Result.FloatImag = Zero; 13846 } else { 13847 Result.makeComplexInt(); 13848 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13849 Result.IntReal = Zero; 13850 Result.IntImag = Zero; 13851 } 13852 return true; 13853 } 13854 13855 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13856 const Expr* SubExpr = E->getSubExpr(); 13857 13858 if (SubExpr->getType()->isRealFloatingType()) { 13859 Result.makeComplexFloat(); 13860 APFloat &Imag = Result.FloatImag; 13861 if (!EvaluateFloat(SubExpr, Imag, Info)) 13862 return false; 13863 13864 Result.FloatReal = APFloat(Imag.getSemantics()); 13865 return true; 13866 } else { 13867 assert(SubExpr->getType()->isIntegerType() && 13868 "Unexpected imaginary literal."); 13869 13870 Result.makeComplexInt(); 13871 APSInt &Imag = Result.IntImag; 13872 if (!EvaluateInteger(SubExpr, Imag, Info)) 13873 return false; 13874 13875 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13876 return true; 13877 } 13878 } 13879 13880 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13881 13882 switch (E->getCastKind()) { 13883 case CK_BitCast: 13884 case CK_BaseToDerived: 13885 case CK_DerivedToBase: 13886 case CK_UncheckedDerivedToBase: 13887 case CK_Dynamic: 13888 case CK_ToUnion: 13889 case CK_ArrayToPointerDecay: 13890 case CK_FunctionToPointerDecay: 13891 case CK_NullToPointer: 13892 case CK_NullToMemberPointer: 13893 case CK_BaseToDerivedMemberPointer: 13894 case CK_DerivedToBaseMemberPointer: 13895 case CK_MemberPointerToBoolean: 13896 case CK_ReinterpretMemberPointer: 13897 case CK_ConstructorConversion: 13898 case CK_IntegralToPointer: 13899 case CK_PointerToIntegral: 13900 case CK_PointerToBoolean: 13901 case CK_ToVoid: 13902 case CK_VectorSplat: 13903 case CK_IntegralCast: 13904 case CK_BooleanToSignedIntegral: 13905 case CK_IntegralToBoolean: 13906 case CK_IntegralToFloating: 13907 case CK_FloatingToIntegral: 13908 case CK_FloatingToBoolean: 13909 case CK_FloatingCast: 13910 case CK_CPointerToObjCPointerCast: 13911 case CK_BlockPointerToObjCPointerCast: 13912 case CK_AnyPointerToBlockPointerCast: 13913 case CK_ObjCObjectLValueCast: 13914 case CK_FloatingComplexToReal: 13915 case CK_FloatingComplexToBoolean: 13916 case CK_IntegralComplexToReal: 13917 case CK_IntegralComplexToBoolean: 13918 case CK_ARCProduceObject: 13919 case CK_ARCConsumeObject: 13920 case CK_ARCReclaimReturnedObject: 13921 case CK_ARCExtendBlockObject: 13922 case CK_CopyAndAutoreleaseBlockObject: 13923 case CK_BuiltinFnToFnPtr: 13924 case CK_ZeroToOCLOpaqueType: 13925 case CK_NonAtomicToAtomic: 13926 case CK_AddressSpaceConversion: 13927 case CK_IntToOCLSampler: 13928 case CK_FloatingToFixedPoint: 13929 case CK_FixedPointToFloating: 13930 case CK_FixedPointCast: 13931 case CK_FixedPointToBoolean: 13932 case CK_FixedPointToIntegral: 13933 case CK_IntegralToFixedPoint: 13934 case CK_MatrixCast: 13935 llvm_unreachable("invalid cast kind for complex value"); 13936 13937 case CK_LValueToRValue: 13938 case CK_AtomicToNonAtomic: 13939 case CK_NoOp: 13940 case CK_LValueToRValueBitCast: 13941 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13942 13943 case CK_Dependent: 13944 case CK_LValueBitCast: 13945 case CK_UserDefinedConversion: 13946 return Error(E); 13947 13948 case CK_FloatingRealToComplex: { 13949 APFloat &Real = Result.FloatReal; 13950 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13951 return false; 13952 13953 Result.makeComplexFloat(); 13954 Result.FloatImag = APFloat(Real.getSemantics()); 13955 return true; 13956 } 13957 13958 case CK_FloatingComplexCast: { 13959 if (!Visit(E->getSubExpr())) 13960 return false; 13961 13962 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13963 QualType From 13964 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13965 13966 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13967 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13968 } 13969 13970 case CK_FloatingComplexToIntegralComplex: { 13971 if (!Visit(E->getSubExpr())) 13972 return false; 13973 13974 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13975 QualType From 13976 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13977 Result.makeComplexInt(); 13978 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13979 To, Result.IntReal) && 13980 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13981 To, Result.IntImag); 13982 } 13983 13984 case CK_IntegralRealToComplex: { 13985 APSInt &Real = Result.IntReal; 13986 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13987 return false; 13988 13989 Result.makeComplexInt(); 13990 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13991 return true; 13992 } 13993 13994 case CK_IntegralComplexCast: { 13995 if (!Visit(E->getSubExpr())) 13996 return false; 13997 13998 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13999 QualType From 14000 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14001 14002 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14003 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14004 return true; 14005 } 14006 14007 case CK_IntegralComplexToFloatingComplex: { 14008 if (!Visit(E->getSubExpr())) 14009 return false; 14010 14011 const FPOptions FPO = E->getFPFeaturesInEffect( 14012 Info.Ctx.getLangOpts()); 14013 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14014 QualType From 14015 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14016 Result.makeComplexFloat(); 14017 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14018 To, Result.FloatReal) && 14019 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14020 To, Result.FloatImag); 14021 } 14022 } 14023 14024 llvm_unreachable("unknown cast resulting in complex value"); 14025 } 14026 14027 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14028 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14029 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14030 14031 // Track whether the LHS or RHS is real at the type system level. When this is 14032 // the case we can simplify our evaluation strategy. 14033 bool LHSReal = false, RHSReal = false; 14034 14035 bool LHSOK; 14036 if (E->getLHS()->getType()->isRealFloatingType()) { 14037 LHSReal = true; 14038 APFloat &Real = Result.FloatReal; 14039 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14040 if (LHSOK) { 14041 Result.makeComplexFloat(); 14042 Result.FloatImag = APFloat(Real.getSemantics()); 14043 } 14044 } else { 14045 LHSOK = Visit(E->getLHS()); 14046 } 14047 if (!LHSOK && !Info.noteFailure()) 14048 return false; 14049 14050 ComplexValue RHS; 14051 if (E->getRHS()->getType()->isRealFloatingType()) { 14052 RHSReal = true; 14053 APFloat &Real = RHS.FloatReal; 14054 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14055 return false; 14056 RHS.makeComplexFloat(); 14057 RHS.FloatImag = APFloat(Real.getSemantics()); 14058 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14059 return false; 14060 14061 assert(!(LHSReal && RHSReal) && 14062 "Cannot have both operands of a complex operation be real."); 14063 switch (E->getOpcode()) { 14064 default: return Error(E); 14065 case BO_Add: 14066 if (Result.isComplexFloat()) { 14067 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14068 APFloat::rmNearestTiesToEven); 14069 if (LHSReal) 14070 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14071 else if (!RHSReal) 14072 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14073 APFloat::rmNearestTiesToEven); 14074 } else { 14075 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14076 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14077 } 14078 break; 14079 case BO_Sub: 14080 if (Result.isComplexFloat()) { 14081 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14082 APFloat::rmNearestTiesToEven); 14083 if (LHSReal) { 14084 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14085 Result.getComplexFloatImag().changeSign(); 14086 } else if (!RHSReal) { 14087 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14088 APFloat::rmNearestTiesToEven); 14089 } 14090 } else { 14091 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14092 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14093 } 14094 break; 14095 case BO_Mul: 14096 if (Result.isComplexFloat()) { 14097 // This is an implementation of complex multiplication according to the 14098 // constraints laid out in C11 Annex G. The implementation uses the 14099 // following naming scheme: 14100 // (a + ib) * (c + id) 14101 ComplexValue LHS = Result; 14102 APFloat &A = LHS.getComplexFloatReal(); 14103 APFloat &B = LHS.getComplexFloatImag(); 14104 APFloat &C = RHS.getComplexFloatReal(); 14105 APFloat &D = RHS.getComplexFloatImag(); 14106 APFloat &ResR = Result.getComplexFloatReal(); 14107 APFloat &ResI = Result.getComplexFloatImag(); 14108 if (LHSReal) { 14109 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14110 ResR = A * C; 14111 ResI = A * D; 14112 } else if (RHSReal) { 14113 ResR = C * A; 14114 ResI = C * B; 14115 } else { 14116 // In the fully general case, we need to handle NaNs and infinities 14117 // robustly. 14118 APFloat AC = A * C; 14119 APFloat BD = B * D; 14120 APFloat AD = A * D; 14121 APFloat BC = B * C; 14122 ResR = AC - BD; 14123 ResI = AD + BC; 14124 if (ResR.isNaN() && ResI.isNaN()) { 14125 bool Recalc = false; 14126 if (A.isInfinity() || B.isInfinity()) { 14127 A = APFloat::copySign( 14128 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14129 B = APFloat::copySign( 14130 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14131 if (C.isNaN()) 14132 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14133 if (D.isNaN()) 14134 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14135 Recalc = true; 14136 } 14137 if (C.isInfinity() || D.isInfinity()) { 14138 C = APFloat::copySign( 14139 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14140 D = APFloat::copySign( 14141 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14142 if (A.isNaN()) 14143 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14144 if (B.isNaN()) 14145 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14146 Recalc = true; 14147 } 14148 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14149 AD.isInfinity() || BC.isInfinity())) { 14150 if (A.isNaN()) 14151 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14152 if (B.isNaN()) 14153 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14154 if (C.isNaN()) 14155 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14156 if (D.isNaN()) 14157 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14158 Recalc = true; 14159 } 14160 if (Recalc) { 14161 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14162 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14163 } 14164 } 14165 } 14166 } else { 14167 ComplexValue LHS = Result; 14168 Result.getComplexIntReal() = 14169 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14170 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14171 Result.getComplexIntImag() = 14172 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14173 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14174 } 14175 break; 14176 case BO_Div: 14177 if (Result.isComplexFloat()) { 14178 // This is an implementation of complex division according to the 14179 // constraints laid out in C11 Annex G. The implementation uses the 14180 // following naming scheme: 14181 // (a + ib) / (c + id) 14182 ComplexValue LHS = Result; 14183 APFloat &A = LHS.getComplexFloatReal(); 14184 APFloat &B = LHS.getComplexFloatImag(); 14185 APFloat &C = RHS.getComplexFloatReal(); 14186 APFloat &D = RHS.getComplexFloatImag(); 14187 APFloat &ResR = Result.getComplexFloatReal(); 14188 APFloat &ResI = Result.getComplexFloatImag(); 14189 if (RHSReal) { 14190 ResR = A / C; 14191 ResI = B / C; 14192 } else { 14193 if (LHSReal) { 14194 // No real optimizations we can do here, stub out with zero. 14195 B = APFloat::getZero(A.getSemantics()); 14196 } 14197 int DenomLogB = 0; 14198 APFloat MaxCD = maxnum(abs(C), abs(D)); 14199 if (MaxCD.isFinite()) { 14200 DenomLogB = ilogb(MaxCD); 14201 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14202 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14203 } 14204 APFloat Denom = C * C + D * D; 14205 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14206 APFloat::rmNearestTiesToEven); 14207 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14208 APFloat::rmNearestTiesToEven); 14209 if (ResR.isNaN() && ResI.isNaN()) { 14210 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14211 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14212 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14213 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14214 D.isFinite()) { 14215 A = APFloat::copySign( 14216 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14217 B = APFloat::copySign( 14218 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14219 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14220 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14221 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14222 C = APFloat::copySign( 14223 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14224 D = APFloat::copySign( 14225 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14226 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14227 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14228 } 14229 } 14230 } 14231 } else { 14232 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14233 return Error(E, diag::note_expr_divide_by_zero); 14234 14235 ComplexValue LHS = Result; 14236 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14237 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14238 Result.getComplexIntReal() = 14239 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14240 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14241 Result.getComplexIntImag() = 14242 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14243 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14244 } 14245 break; 14246 } 14247 14248 return true; 14249 } 14250 14251 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14252 // Get the operand value into 'Result'. 14253 if (!Visit(E->getSubExpr())) 14254 return false; 14255 14256 switch (E->getOpcode()) { 14257 default: 14258 return Error(E); 14259 case UO_Extension: 14260 return true; 14261 case UO_Plus: 14262 // The result is always just the subexpr. 14263 return true; 14264 case UO_Minus: 14265 if (Result.isComplexFloat()) { 14266 Result.getComplexFloatReal().changeSign(); 14267 Result.getComplexFloatImag().changeSign(); 14268 } 14269 else { 14270 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14271 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14272 } 14273 return true; 14274 case UO_Not: 14275 if (Result.isComplexFloat()) 14276 Result.getComplexFloatImag().changeSign(); 14277 else 14278 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14279 return true; 14280 } 14281 } 14282 14283 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14284 if (E->getNumInits() == 2) { 14285 if (E->getType()->isComplexType()) { 14286 Result.makeComplexFloat(); 14287 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14288 return false; 14289 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14290 return false; 14291 } else { 14292 Result.makeComplexInt(); 14293 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14294 return false; 14295 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14296 return false; 14297 } 14298 return true; 14299 } 14300 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14301 } 14302 14303 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14304 switch (E->getBuiltinCallee()) { 14305 case Builtin::BI__builtin_complex: 14306 Result.makeComplexFloat(); 14307 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14308 return false; 14309 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14310 return false; 14311 return true; 14312 14313 default: 14314 break; 14315 } 14316 14317 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14318 } 14319 14320 //===----------------------------------------------------------------------===// 14321 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14322 // implicit conversion. 14323 //===----------------------------------------------------------------------===// 14324 14325 namespace { 14326 class AtomicExprEvaluator : 14327 public ExprEvaluatorBase<AtomicExprEvaluator> { 14328 const LValue *This; 14329 APValue &Result; 14330 public: 14331 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14332 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14333 14334 bool Success(const APValue &V, const Expr *E) { 14335 Result = V; 14336 return true; 14337 } 14338 14339 bool ZeroInitialization(const Expr *E) { 14340 ImplicitValueInitExpr VIE( 14341 E->getType()->castAs<AtomicType>()->getValueType()); 14342 // For atomic-qualified class (and array) types in C++, initialize the 14343 // _Atomic-wrapped subobject directly, in-place. 14344 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14345 : Evaluate(Result, Info, &VIE); 14346 } 14347 14348 bool VisitCastExpr(const CastExpr *E) { 14349 switch (E->getCastKind()) { 14350 default: 14351 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14352 case CK_NonAtomicToAtomic: 14353 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14354 : Evaluate(Result, Info, E->getSubExpr()); 14355 } 14356 } 14357 }; 14358 } // end anonymous namespace 14359 14360 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14361 EvalInfo &Info) { 14362 assert(!E->isValueDependent()); 14363 assert(E->isPRValue() && E->getType()->isAtomicType()); 14364 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14365 } 14366 14367 //===----------------------------------------------------------------------===// 14368 // Void expression evaluation, primarily for a cast to void on the LHS of a 14369 // comma operator 14370 //===----------------------------------------------------------------------===// 14371 14372 namespace { 14373 class VoidExprEvaluator 14374 : public ExprEvaluatorBase<VoidExprEvaluator> { 14375 public: 14376 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14377 14378 bool Success(const APValue &V, const Expr *e) { return true; } 14379 14380 bool ZeroInitialization(const Expr *E) { return true; } 14381 14382 bool VisitCastExpr(const CastExpr *E) { 14383 switch (E->getCastKind()) { 14384 default: 14385 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14386 case CK_ToVoid: 14387 VisitIgnoredValue(E->getSubExpr()); 14388 return true; 14389 } 14390 } 14391 14392 bool VisitCallExpr(const CallExpr *E) { 14393 switch (E->getBuiltinCallee()) { 14394 case Builtin::BI__assume: 14395 case Builtin::BI__builtin_assume: 14396 // The argument is not evaluated! 14397 return true; 14398 14399 case Builtin::BI__builtin_operator_delete: 14400 return HandleOperatorDeleteCall(Info, E); 14401 14402 default: 14403 break; 14404 } 14405 14406 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14407 } 14408 14409 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14410 }; 14411 } // end anonymous namespace 14412 14413 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14414 // We cannot speculatively evaluate a delete expression. 14415 if (Info.SpeculativeEvaluationDepth) 14416 return false; 14417 14418 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14419 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14420 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14421 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14422 return false; 14423 } 14424 14425 const Expr *Arg = E->getArgument(); 14426 14427 LValue Pointer; 14428 if (!EvaluatePointer(Arg, Pointer, Info)) 14429 return false; 14430 if (Pointer.Designator.Invalid) 14431 return false; 14432 14433 // Deleting a null pointer has no effect. 14434 if (Pointer.isNullPointer()) { 14435 // This is the only case where we need to produce an extension warning: 14436 // the only other way we can succeed is if we find a dynamic allocation, 14437 // and we will have warned when we allocated it in that case. 14438 if (!Info.getLangOpts().CPlusPlus20) 14439 Info.CCEDiag(E, diag::note_constexpr_new); 14440 return true; 14441 } 14442 14443 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14444 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14445 if (!Alloc) 14446 return false; 14447 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14448 14449 // For the non-array case, the designator must be empty if the static type 14450 // does not have a virtual destructor. 14451 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14452 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14453 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14454 << Arg->getType()->getPointeeType() << AllocType; 14455 return false; 14456 } 14457 14458 // For a class type with a virtual destructor, the selected operator delete 14459 // is the one looked up when building the destructor. 14460 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14461 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14462 if (VirtualDelete && 14463 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14464 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14465 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14466 return false; 14467 } 14468 } 14469 14470 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14471 (*Alloc)->Value, AllocType)) 14472 return false; 14473 14474 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14475 // The element was already erased. This means the destructor call also 14476 // deleted the object. 14477 // FIXME: This probably results in undefined behavior before we get this 14478 // far, and should be diagnosed elsewhere first. 14479 Info.FFDiag(E, diag::note_constexpr_double_delete); 14480 return false; 14481 } 14482 14483 return true; 14484 } 14485 14486 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14487 assert(!E->isValueDependent()); 14488 assert(E->isPRValue() && E->getType()->isVoidType()); 14489 return VoidExprEvaluator(Info).Visit(E); 14490 } 14491 14492 //===----------------------------------------------------------------------===// 14493 // Top level Expr::EvaluateAsRValue method. 14494 //===----------------------------------------------------------------------===// 14495 14496 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14497 assert(!E->isValueDependent()); 14498 // In C, function designators are not lvalues, but we evaluate them as if they 14499 // are. 14500 QualType T = E->getType(); 14501 if (E->isGLValue() || T->isFunctionType()) { 14502 LValue LV; 14503 if (!EvaluateLValue(E, LV, Info)) 14504 return false; 14505 LV.moveInto(Result); 14506 } else if (T->isVectorType()) { 14507 if (!EvaluateVector(E, Result, Info)) 14508 return false; 14509 } else if (T->isIntegralOrEnumerationType()) { 14510 if (!IntExprEvaluator(Info, Result).Visit(E)) 14511 return false; 14512 } else if (T->hasPointerRepresentation()) { 14513 LValue LV; 14514 if (!EvaluatePointer(E, LV, Info)) 14515 return false; 14516 LV.moveInto(Result); 14517 } else if (T->isRealFloatingType()) { 14518 llvm::APFloat F(0.0); 14519 if (!EvaluateFloat(E, F, Info)) 14520 return false; 14521 Result = APValue(F); 14522 } else if (T->isAnyComplexType()) { 14523 ComplexValue C; 14524 if (!EvaluateComplex(E, C, Info)) 14525 return false; 14526 C.moveInto(Result); 14527 } else if (T->isFixedPointType()) { 14528 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14529 } else if (T->isMemberPointerType()) { 14530 MemberPtr P; 14531 if (!EvaluateMemberPointer(E, P, Info)) 14532 return false; 14533 P.moveInto(Result); 14534 return true; 14535 } else if (T->isArrayType()) { 14536 LValue LV; 14537 APValue &Value = 14538 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14539 if (!EvaluateArray(E, LV, Value, Info)) 14540 return false; 14541 Result = Value; 14542 } else if (T->isRecordType()) { 14543 LValue LV; 14544 APValue &Value = 14545 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14546 if (!EvaluateRecord(E, LV, Value, Info)) 14547 return false; 14548 Result = Value; 14549 } else if (T->isVoidType()) { 14550 if (!Info.getLangOpts().CPlusPlus11) 14551 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14552 << E->getType(); 14553 if (!EvaluateVoid(E, Info)) 14554 return false; 14555 } else if (T->isAtomicType()) { 14556 QualType Unqual = T.getAtomicUnqualifiedType(); 14557 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14558 LValue LV; 14559 APValue &Value = Info.CurrentCall->createTemporary( 14560 E, Unqual, ScopeKind::FullExpression, LV); 14561 if (!EvaluateAtomic(E, &LV, Value, Info)) 14562 return false; 14563 } else { 14564 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14565 return false; 14566 } 14567 } else if (Info.getLangOpts().CPlusPlus11) { 14568 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14569 return false; 14570 } else { 14571 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14572 return false; 14573 } 14574 14575 return true; 14576 } 14577 14578 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14579 /// cases, the in-place evaluation is essential, since later initializers for 14580 /// an object can indirectly refer to subobjects which were initialized earlier. 14581 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14582 const Expr *E, bool AllowNonLiteralTypes) { 14583 assert(!E->isValueDependent()); 14584 14585 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14586 return false; 14587 14588 if (E->isPRValue()) { 14589 // Evaluate arrays and record types in-place, so that later initializers can 14590 // refer to earlier-initialized members of the object. 14591 QualType T = E->getType(); 14592 if (T->isArrayType()) 14593 return EvaluateArray(E, This, Result, Info); 14594 else if (T->isRecordType()) 14595 return EvaluateRecord(E, This, Result, Info); 14596 else if (T->isAtomicType()) { 14597 QualType Unqual = T.getAtomicUnqualifiedType(); 14598 if (Unqual->isArrayType() || Unqual->isRecordType()) 14599 return EvaluateAtomic(E, &This, Result, Info); 14600 } 14601 } 14602 14603 // For any other type, in-place evaluation is unimportant. 14604 return Evaluate(Result, Info, E); 14605 } 14606 14607 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14608 /// lvalue-to-rvalue cast if it is an lvalue. 14609 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14610 assert(!E->isValueDependent()); 14611 if (Info.EnableNewConstInterp) { 14612 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14613 return false; 14614 } else { 14615 if (E->getType().isNull()) 14616 return false; 14617 14618 if (!CheckLiteralType(Info, E)) 14619 return false; 14620 14621 if (!::Evaluate(Result, Info, E)) 14622 return false; 14623 14624 if (E->isGLValue()) { 14625 LValue LV; 14626 LV.setFrom(Info.Ctx, Result); 14627 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14628 return false; 14629 } 14630 } 14631 14632 // Check this core constant expression is a constant expression. 14633 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14634 ConstantExprKind::Normal) && 14635 CheckMemoryLeaks(Info); 14636 } 14637 14638 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14639 const ASTContext &Ctx, bool &IsConst) { 14640 // Fast-path evaluations of integer literals, since we sometimes see files 14641 // containing vast quantities of these. 14642 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14643 Result.Val = APValue(APSInt(L->getValue(), 14644 L->getType()->isUnsignedIntegerType())); 14645 IsConst = true; 14646 return true; 14647 } 14648 14649 // This case should be rare, but we need to check it before we check on 14650 // the type below. 14651 if (Exp->getType().isNull()) { 14652 IsConst = false; 14653 return true; 14654 } 14655 14656 // FIXME: Evaluating values of large array and record types can cause 14657 // performance problems. Only do so in C++11 for now. 14658 if (Exp->isPRValue() && 14659 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14660 !Ctx.getLangOpts().CPlusPlus11) { 14661 IsConst = false; 14662 return true; 14663 } 14664 return false; 14665 } 14666 14667 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14668 Expr::SideEffectsKind SEK) { 14669 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14670 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14671 } 14672 14673 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14674 const ASTContext &Ctx, EvalInfo &Info) { 14675 assert(!E->isValueDependent()); 14676 bool IsConst; 14677 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14678 return IsConst; 14679 14680 return EvaluateAsRValue(Info, E, Result.Val); 14681 } 14682 14683 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14684 const ASTContext &Ctx, 14685 Expr::SideEffectsKind AllowSideEffects, 14686 EvalInfo &Info) { 14687 assert(!E->isValueDependent()); 14688 if (!E->getType()->isIntegralOrEnumerationType()) 14689 return false; 14690 14691 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14692 !ExprResult.Val.isInt() || 14693 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14694 return false; 14695 14696 return true; 14697 } 14698 14699 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14700 const ASTContext &Ctx, 14701 Expr::SideEffectsKind AllowSideEffects, 14702 EvalInfo &Info) { 14703 assert(!E->isValueDependent()); 14704 if (!E->getType()->isFixedPointType()) 14705 return false; 14706 14707 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14708 return false; 14709 14710 if (!ExprResult.Val.isFixedPoint() || 14711 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14712 return false; 14713 14714 return true; 14715 } 14716 14717 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14718 /// any crazy technique (that has nothing to do with language standards) that 14719 /// we want to. If this function returns true, it returns the folded constant 14720 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14721 /// will be applied to the result. 14722 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14723 bool InConstantContext) const { 14724 assert(!isValueDependent() && 14725 "Expression evaluator can't be called on a dependent expression."); 14726 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14727 Info.InConstantContext = InConstantContext; 14728 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14729 } 14730 14731 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14732 bool InConstantContext) const { 14733 assert(!isValueDependent() && 14734 "Expression evaluator can't be called on a dependent expression."); 14735 EvalResult Scratch; 14736 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14737 HandleConversionToBool(Scratch.Val, Result); 14738 } 14739 14740 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14741 SideEffectsKind AllowSideEffects, 14742 bool InConstantContext) const { 14743 assert(!isValueDependent() && 14744 "Expression evaluator can't be called on a dependent expression."); 14745 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14746 Info.InConstantContext = InConstantContext; 14747 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14748 } 14749 14750 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14751 SideEffectsKind AllowSideEffects, 14752 bool InConstantContext) const { 14753 assert(!isValueDependent() && 14754 "Expression evaluator can't be called on a dependent expression."); 14755 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14756 Info.InConstantContext = InConstantContext; 14757 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14758 } 14759 14760 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14761 SideEffectsKind AllowSideEffects, 14762 bool InConstantContext) const { 14763 assert(!isValueDependent() && 14764 "Expression evaluator can't be called on a dependent expression."); 14765 14766 if (!getType()->isRealFloatingType()) 14767 return false; 14768 14769 EvalResult ExprResult; 14770 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14771 !ExprResult.Val.isFloat() || 14772 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14773 return false; 14774 14775 Result = ExprResult.Val.getFloat(); 14776 return true; 14777 } 14778 14779 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14780 bool InConstantContext) const { 14781 assert(!isValueDependent() && 14782 "Expression evaluator can't be called on a dependent expression."); 14783 14784 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14785 Info.InConstantContext = InConstantContext; 14786 LValue LV; 14787 CheckedTemporaries CheckedTemps; 14788 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14789 Result.HasSideEffects || 14790 !CheckLValueConstantExpression(Info, getExprLoc(), 14791 Ctx.getLValueReferenceType(getType()), LV, 14792 ConstantExprKind::Normal, CheckedTemps)) 14793 return false; 14794 14795 LV.moveInto(Result.Val); 14796 return true; 14797 } 14798 14799 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14800 APValue DestroyedValue, QualType Type, 14801 SourceLocation Loc, Expr::EvalStatus &EStatus, 14802 bool IsConstantDestruction) { 14803 EvalInfo Info(Ctx, EStatus, 14804 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14805 : EvalInfo::EM_ConstantFold); 14806 Info.setEvaluatingDecl(Base, DestroyedValue, 14807 EvalInfo::EvaluatingDeclKind::Dtor); 14808 Info.InConstantContext = IsConstantDestruction; 14809 14810 LValue LVal; 14811 LVal.set(Base); 14812 14813 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14814 EStatus.HasSideEffects) 14815 return false; 14816 14817 if (!Info.discardCleanups()) 14818 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14819 14820 return true; 14821 } 14822 14823 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14824 ConstantExprKind Kind) const { 14825 assert(!isValueDependent() && 14826 "Expression evaluator can't be called on a dependent expression."); 14827 14828 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14829 EvalInfo Info(Ctx, Result, EM); 14830 Info.InConstantContext = true; 14831 14832 // The type of the object we're initializing is 'const T' for a class NTTP. 14833 QualType T = getType(); 14834 if (Kind == ConstantExprKind::ClassTemplateArgument) 14835 T.addConst(); 14836 14837 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14838 // represent the result of the evaluation. CheckConstantExpression ensures 14839 // this doesn't escape. 14840 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14841 APValue::LValueBase Base(&BaseMTE); 14842 14843 Info.setEvaluatingDecl(Base, Result.Val); 14844 LValue LVal; 14845 LVal.set(Base); 14846 14847 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14848 return false; 14849 14850 if (!Info.discardCleanups()) 14851 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14852 14853 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14854 Result.Val, Kind)) 14855 return false; 14856 if (!CheckMemoryLeaks(Info)) 14857 return false; 14858 14859 // If this is a class template argument, it's required to have constant 14860 // destruction too. 14861 if (Kind == ConstantExprKind::ClassTemplateArgument && 14862 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 14863 true) || 14864 Result.HasSideEffects)) { 14865 // FIXME: Prefix a note to indicate that the problem is lack of constant 14866 // destruction. 14867 return false; 14868 } 14869 14870 return true; 14871 } 14872 14873 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14874 const VarDecl *VD, 14875 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14876 bool IsConstantInitialization) const { 14877 assert(!isValueDependent() && 14878 "Expression evaluator can't be called on a dependent expression."); 14879 14880 // FIXME: Evaluating initializers for large array and record types can cause 14881 // performance problems. Only do so in C++11 for now. 14882 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14883 !Ctx.getLangOpts().CPlusPlus11) 14884 return false; 14885 14886 Expr::EvalStatus EStatus; 14887 EStatus.Diag = &Notes; 14888 14889 EvalInfo Info(Ctx, EStatus, 14890 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14891 ? EvalInfo::EM_ConstantExpression 14892 : EvalInfo::EM_ConstantFold); 14893 Info.setEvaluatingDecl(VD, Value); 14894 Info.InConstantContext = IsConstantInitialization; 14895 14896 SourceLocation DeclLoc = VD->getLocation(); 14897 QualType DeclTy = VD->getType(); 14898 14899 if (Info.EnableNewConstInterp) { 14900 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14901 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14902 return false; 14903 } else { 14904 LValue LVal; 14905 LVal.set(VD); 14906 14907 if (!EvaluateInPlace(Value, Info, LVal, this, 14908 /*AllowNonLiteralTypes=*/true) || 14909 EStatus.HasSideEffects) 14910 return false; 14911 14912 // At this point, any lifetime-extended temporaries are completely 14913 // initialized. 14914 Info.performLifetimeExtension(); 14915 14916 if (!Info.discardCleanups()) 14917 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14918 } 14919 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14920 ConstantExprKind::Normal) && 14921 CheckMemoryLeaks(Info); 14922 } 14923 14924 bool VarDecl::evaluateDestruction( 14925 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14926 Expr::EvalStatus EStatus; 14927 EStatus.Diag = &Notes; 14928 14929 // Only treat the destruction as constant destruction if we formally have 14930 // constant initialization (or are usable in a constant expression). 14931 bool IsConstantDestruction = hasConstantInitialization(); 14932 14933 // Make a copy of the value for the destructor to mutate, if we know it. 14934 // Otherwise, treat the value as default-initialized; if the destructor works 14935 // anyway, then the destruction is constant (and must be essentially empty). 14936 APValue DestroyedValue; 14937 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14938 DestroyedValue = *getEvaluatedValue(); 14939 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14940 return false; 14941 14942 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14943 getType(), getLocation(), EStatus, 14944 IsConstantDestruction) || 14945 EStatus.HasSideEffects) 14946 return false; 14947 14948 ensureEvaluatedStmt()->HasConstantDestruction = true; 14949 return true; 14950 } 14951 14952 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14953 /// constant folded, but discard the result. 14954 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14955 assert(!isValueDependent() && 14956 "Expression evaluator can't be called on a dependent expression."); 14957 14958 EvalResult Result; 14959 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14960 !hasUnacceptableSideEffect(Result, SEK); 14961 } 14962 14963 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14964 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14965 assert(!isValueDependent() && 14966 "Expression evaluator can't be called on a dependent expression."); 14967 14968 EvalResult EVResult; 14969 EVResult.Diag = Diag; 14970 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14971 Info.InConstantContext = true; 14972 14973 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14974 (void)Result; 14975 assert(Result && "Could not evaluate expression"); 14976 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14977 14978 return EVResult.Val.getInt(); 14979 } 14980 14981 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14982 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14983 assert(!isValueDependent() && 14984 "Expression evaluator can't be called on a dependent expression."); 14985 14986 EvalResult EVResult; 14987 EVResult.Diag = Diag; 14988 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14989 Info.InConstantContext = true; 14990 Info.CheckingForUndefinedBehavior = true; 14991 14992 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14993 (void)Result; 14994 assert(Result && "Could not evaluate expression"); 14995 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14996 14997 return EVResult.Val.getInt(); 14998 } 14999 15000 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15001 assert(!isValueDependent() && 15002 "Expression evaluator can't be called on a dependent expression."); 15003 15004 bool IsConst; 15005 EvalResult EVResult; 15006 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15007 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15008 Info.CheckingForUndefinedBehavior = true; 15009 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15010 } 15011 } 15012 15013 bool Expr::EvalResult::isGlobalLValue() const { 15014 assert(Val.isLValue()); 15015 return IsGlobalLValue(Val.getLValueBase()); 15016 } 15017 15018 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15019 /// an integer constant expression. 15020 15021 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15022 /// comma, etc 15023 15024 // CheckICE - This function does the fundamental ICE checking: the returned 15025 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15026 // and a (possibly null) SourceLocation indicating the location of the problem. 15027 // 15028 // Note that to reduce code duplication, this helper does no evaluation 15029 // itself; the caller checks whether the expression is evaluatable, and 15030 // in the rare cases where CheckICE actually cares about the evaluated 15031 // value, it calls into Evaluate. 15032 15033 namespace { 15034 15035 enum ICEKind { 15036 /// This expression is an ICE. 15037 IK_ICE, 15038 /// This expression is not an ICE, but if it isn't evaluated, it's 15039 /// a legal subexpression for an ICE. This return value is used to handle 15040 /// the comma operator in C99 mode, and non-constant subexpressions. 15041 IK_ICEIfUnevaluated, 15042 /// This expression is not an ICE, and is not a legal subexpression for one. 15043 IK_NotICE 15044 }; 15045 15046 struct ICEDiag { 15047 ICEKind Kind; 15048 SourceLocation Loc; 15049 15050 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15051 }; 15052 15053 } 15054 15055 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15056 15057 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15058 15059 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15060 Expr::EvalResult EVResult; 15061 Expr::EvalStatus Status; 15062 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15063 15064 Info.InConstantContext = true; 15065 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15066 !EVResult.Val.isInt()) 15067 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15068 15069 return NoDiag(); 15070 } 15071 15072 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15073 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15074 if (!E->getType()->isIntegralOrEnumerationType()) 15075 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15076 15077 switch (E->getStmtClass()) { 15078 #define ABSTRACT_STMT(Node) 15079 #define STMT(Node, Base) case Expr::Node##Class: 15080 #define EXPR(Node, Base) 15081 #include "clang/AST/StmtNodes.inc" 15082 case Expr::PredefinedExprClass: 15083 case Expr::FloatingLiteralClass: 15084 case Expr::ImaginaryLiteralClass: 15085 case Expr::StringLiteralClass: 15086 case Expr::ArraySubscriptExprClass: 15087 case Expr::MatrixSubscriptExprClass: 15088 case Expr::OMPArraySectionExprClass: 15089 case Expr::OMPArrayShapingExprClass: 15090 case Expr::OMPIteratorExprClass: 15091 case Expr::MemberExprClass: 15092 case Expr::CompoundAssignOperatorClass: 15093 case Expr::CompoundLiteralExprClass: 15094 case Expr::ExtVectorElementExprClass: 15095 case Expr::DesignatedInitExprClass: 15096 case Expr::ArrayInitLoopExprClass: 15097 case Expr::ArrayInitIndexExprClass: 15098 case Expr::NoInitExprClass: 15099 case Expr::DesignatedInitUpdateExprClass: 15100 case Expr::ImplicitValueInitExprClass: 15101 case Expr::ParenListExprClass: 15102 case Expr::VAArgExprClass: 15103 case Expr::AddrLabelExprClass: 15104 case Expr::StmtExprClass: 15105 case Expr::CXXMemberCallExprClass: 15106 case Expr::CUDAKernelCallExprClass: 15107 case Expr::CXXAddrspaceCastExprClass: 15108 case Expr::CXXDynamicCastExprClass: 15109 case Expr::CXXTypeidExprClass: 15110 case Expr::CXXUuidofExprClass: 15111 case Expr::MSPropertyRefExprClass: 15112 case Expr::MSPropertySubscriptExprClass: 15113 case Expr::CXXNullPtrLiteralExprClass: 15114 case Expr::UserDefinedLiteralClass: 15115 case Expr::CXXThisExprClass: 15116 case Expr::CXXThrowExprClass: 15117 case Expr::CXXNewExprClass: 15118 case Expr::CXXDeleteExprClass: 15119 case Expr::CXXPseudoDestructorExprClass: 15120 case Expr::UnresolvedLookupExprClass: 15121 case Expr::TypoExprClass: 15122 case Expr::RecoveryExprClass: 15123 case Expr::DependentScopeDeclRefExprClass: 15124 case Expr::CXXConstructExprClass: 15125 case Expr::CXXInheritedCtorInitExprClass: 15126 case Expr::CXXStdInitializerListExprClass: 15127 case Expr::CXXBindTemporaryExprClass: 15128 case Expr::ExprWithCleanupsClass: 15129 case Expr::CXXTemporaryObjectExprClass: 15130 case Expr::CXXUnresolvedConstructExprClass: 15131 case Expr::CXXDependentScopeMemberExprClass: 15132 case Expr::UnresolvedMemberExprClass: 15133 case Expr::ObjCStringLiteralClass: 15134 case Expr::ObjCBoxedExprClass: 15135 case Expr::ObjCArrayLiteralClass: 15136 case Expr::ObjCDictionaryLiteralClass: 15137 case Expr::ObjCEncodeExprClass: 15138 case Expr::ObjCMessageExprClass: 15139 case Expr::ObjCSelectorExprClass: 15140 case Expr::ObjCProtocolExprClass: 15141 case Expr::ObjCIvarRefExprClass: 15142 case Expr::ObjCPropertyRefExprClass: 15143 case Expr::ObjCSubscriptRefExprClass: 15144 case Expr::ObjCIsaExprClass: 15145 case Expr::ObjCAvailabilityCheckExprClass: 15146 case Expr::ShuffleVectorExprClass: 15147 case Expr::ConvertVectorExprClass: 15148 case Expr::BlockExprClass: 15149 case Expr::NoStmtClass: 15150 case Expr::OpaqueValueExprClass: 15151 case Expr::PackExpansionExprClass: 15152 case Expr::SubstNonTypeTemplateParmPackExprClass: 15153 case Expr::FunctionParmPackExprClass: 15154 case Expr::AsTypeExprClass: 15155 case Expr::ObjCIndirectCopyRestoreExprClass: 15156 case Expr::MaterializeTemporaryExprClass: 15157 case Expr::PseudoObjectExprClass: 15158 case Expr::AtomicExprClass: 15159 case Expr::LambdaExprClass: 15160 case Expr::CXXFoldExprClass: 15161 case Expr::CoawaitExprClass: 15162 case Expr::DependentCoawaitExprClass: 15163 case Expr::CoyieldExprClass: 15164 case Expr::SYCLUniqueStableNameExprClass: 15165 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15166 15167 case Expr::InitListExprClass: { 15168 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15169 // form "T x = { a };" is equivalent to "T x = a;". 15170 // Unless we're initializing a reference, T is a scalar as it is known to be 15171 // of integral or enumeration type. 15172 if (E->isPRValue()) 15173 if (cast<InitListExpr>(E)->getNumInits() == 1) 15174 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15175 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15176 } 15177 15178 case Expr::SizeOfPackExprClass: 15179 case Expr::GNUNullExprClass: 15180 case Expr::SourceLocExprClass: 15181 return NoDiag(); 15182 15183 case Expr::SubstNonTypeTemplateParmExprClass: 15184 return 15185 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15186 15187 case Expr::ConstantExprClass: 15188 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15189 15190 case Expr::ParenExprClass: 15191 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15192 case Expr::GenericSelectionExprClass: 15193 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15194 case Expr::IntegerLiteralClass: 15195 case Expr::FixedPointLiteralClass: 15196 case Expr::CharacterLiteralClass: 15197 case Expr::ObjCBoolLiteralExprClass: 15198 case Expr::CXXBoolLiteralExprClass: 15199 case Expr::CXXScalarValueInitExprClass: 15200 case Expr::TypeTraitExprClass: 15201 case Expr::ConceptSpecializationExprClass: 15202 case Expr::RequiresExprClass: 15203 case Expr::ArrayTypeTraitExprClass: 15204 case Expr::ExpressionTraitExprClass: 15205 case Expr::CXXNoexceptExprClass: 15206 return NoDiag(); 15207 case Expr::CallExprClass: 15208 case Expr::CXXOperatorCallExprClass: { 15209 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15210 // constant expressions, but they can never be ICEs because an ICE cannot 15211 // contain an operand of (pointer to) function type. 15212 const CallExpr *CE = cast<CallExpr>(E); 15213 if (CE->getBuiltinCallee()) 15214 return CheckEvalInICE(E, Ctx); 15215 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15216 } 15217 case Expr::CXXRewrittenBinaryOperatorClass: 15218 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15219 Ctx); 15220 case Expr::DeclRefExprClass: { 15221 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15222 if (isa<EnumConstantDecl>(D)) 15223 return NoDiag(); 15224 15225 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15226 // integer variables in constant expressions: 15227 // 15228 // C++ 7.1.5.1p2 15229 // A variable of non-volatile const-qualified integral or enumeration 15230 // type initialized by an ICE can be used in ICEs. 15231 // 15232 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15233 // that mode, use of reference variables should not be allowed. 15234 const VarDecl *VD = dyn_cast<VarDecl>(D); 15235 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15236 !VD->getType()->isReferenceType()) 15237 return NoDiag(); 15238 15239 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15240 } 15241 case Expr::UnaryOperatorClass: { 15242 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15243 switch (Exp->getOpcode()) { 15244 case UO_PostInc: 15245 case UO_PostDec: 15246 case UO_PreInc: 15247 case UO_PreDec: 15248 case UO_AddrOf: 15249 case UO_Deref: 15250 case UO_Coawait: 15251 // C99 6.6/3 allows increment and decrement within unevaluated 15252 // subexpressions of constant expressions, but they can never be ICEs 15253 // because an ICE cannot contain an lvalue operand. 15254 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15255 case UO_Extension: 15256 case UO_LNot: 15257 case UO_Plus: 15258 case UO_Minus: 15259 case UO_Not: 15260 case UO_Real: 15261 case UO_Imag: 15262 return CheckICE(Exp->getSubExpr(), Ctx); 15263 } 15264 llvm_unreachable("invalid unary operator class"); 15265 } 15266 case Expr::OffsetOfExprClass: { 15267 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15268 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15269 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15270 // compliance: we should warn earlier for offsetof expressions with 15271 // array subscripts that aren't ICEs, and if the array subscripts 15272 // are ICEs, the value of the offsetof must be an integer constant. 15273 return CheckEvalInICE(E, Ctx); 15274 } 15275 case Expr::UnaryExprOrTypeTraitExprClass: { 15276 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15277 if ((Exp->getKind() == UETT_SizeOf) && 15278 Exp->getTypeOfArgument()->isVariableArrayType()) 15279 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15280 return NoDiag(); 15281 } 15282 case Expr::BinaryOperatorClass: { 15283 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15284 switch (Exp->getOpcode()) { 15285 case BO_PtrMemD: 15286 case BO_PtrMemI: 15287 case BO_Assign: 15288 case BO_MulAssign: 15289 case BO_DivAssign: 15290 case BO_RemAssign: 15291 case BO_AddAssign: 15292 case BO_SubAssign: 15293 case BO_ShlAssign: 15294 case BO_ShrAssign: 15295 case BO_AndAssign: 15296 case BO_XorAssign: 15297 case BO_OrAssign: 15298 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15299 // constant expressions, but they can never be ICEs because an ICE cannot 15300 // contain an lvalue operand. 15301 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15302 15303 case BO_Mul: 15304 case BO_Div: 15305 case BO_Rem: 15306 case BO_Add: 15307 case BO_Sub: 15308 case BO_Shl: 15309 case BO_Shr: 15310 case BO_LT: 15311 case BO_GT: 15312 case BO_LE: 15313 case BO_GE: 15314 case BO_EQ: 15315 case BO_NE: 15316 case BO_And: 15317 case BO_Xor: 15318 case BO_Or: 15319 case BO_Comma: 15320 case BO_Cmp: { 15321 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15322 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15323 if (Exp->getOpcode() == BO_Div || 15324 Exp->getOpcode() == BO_Rem) { 15325 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15326 // we don't evaluate one. 15327 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15328 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15329 if (REval == 0) 15330 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15331 if (REval.isSigned() && REval.isAllOnes()) { 15332 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15333 if (LEval.isMinSignedValue()) 15334 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15335 } 15336 } 15337 } 15338 if (Exp->getOpcode() == BO_Comma) { 15339 if (Ctx.getLangOpts().C99) { 15340 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15341 // if it isn't evaluated. 15342 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15343 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15344 } else { 15345 // In both C89 and C++, commas in ICEs are illegal. 15346 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15347 } 15348 } 15349 return Worst(LHSResult, RHSResult); 15350 } 15351 case BO_LAnd: 15352 case BO_LOr: { 15353 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15354 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15355 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15356 // Rare case where the RHS has a comma "side-effect"; we need 15357 // to actually check the condition to see whether the side 15358 // with the comma is evaluated. 15359 if ((Exp->getOpcode() == BO_LAnd) != 15360 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15361 return RHSResult; 15362 return NoDiag(); 15363 } 15364 15365 return Worst(LHSResult, RHSResult); 15366 } 15367 } 15368 llvm_unreachable("invalid binary operator kind"); 15369 } 15370 case Expr::ImplicitCastExprClass: 15371 case Expr::CStyleCastExprClass: 15372 case Expr::CXXFunctionalCastExprClass: 15373 case Expr::CXXStaticCastExprClass: 15374 case Expr::CXXReinterpretCastExprClass: 15375 case Expr::CXXConstCastExprClass: 15376 case Expr::ObjCBridgedCastExprClass: { 15377 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15378 if (isa<ExplicitCastExpr>(E)) { 15379 if (const FloatingLiteral *FL 15380 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15381 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15382 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15383 APSInt IgnoredVal(DestWidth, !DestSigned); 15384 bool Ignored; 15385 // If the value does not fit in the destination type, the behavior is 15386 // undefined, so we are not required to treat it as a constant 15387 // expression. 15388 if (FL->getValue().convertToInteger(IgnoredVal, 15389 llvm::APFloat::rmTowardZero, 15390 &Ignored) & APFloat::opInvalidOp) 15391 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15392 return NoDiag(); 15393 } 15394 } 15395 switch (cast<CastExpr>(E)->getCastKind()) { 15396 case CK_LValueToRValue: 15397 case CK_AtomicToNonAtomic: 15398 case CK_NonAtomicToAtomic: 15399 case CK_NoOp: 15400 case CK_IntegralToBoolean: 15401 case CK_IntegralCast: 15402 return CheckICE(SubExpr, Ctx); 15403 default: 15404 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15405 } 15406 } 15407 case Expr::BinaryConditionalOperatorClass: { 15408 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15409 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15410 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15411 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15412 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15413 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15414 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15415 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15416 return FalseResult; 15417 } 15418 case Expr::ConditionalOperatorClass: { 15419 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15420 // If the condition (ignoring parens) is a __builtin_constant_p call, 15421 // then only the true side is actually considered in an integer constant 15422 // expression, and it is fully evaluated. This is an important GNU 15423 // extension. See GCC PR38377 for discussion. 15424 if (const CallExpr *CallCE 15425 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15426 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15427 return CheckEvalInICE(E, Ctx); 15428 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15429 if (CondResult.Kind == IK_NotICE) 15430 return CondResult; 15431 15432 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15433 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15434 15435 if (TrueResult.Kind == IK_NotICE) 15436 return TrueResult; 15437 if (FalseResult.Kind == IK_NotICE) 15438 return FalseResult; 15439 if (CondResult.Kind == IK_ICEIfUnevaluated) 15440 return CondResult; 15441 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15442 return NoDiag(); 15443 // Rare case where the diagnostics depend on which side is evaluated 15444 // Note that if we get here, CondResult is 0, and at least one of 15445 // TrueResult and FalseResult is non-zero. 15446 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15447 return FalseResult; 15448 return TrueResult; 15449 } 15450 case Expr::CXXDefaultArgExprClass: 15451 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15452 case Expr::CXXDefaultInitExprClass: 15453 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15454 case Expr::ChooseExprClass: { 15455 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15456 } 15457 case Expr::BuiltinBitCastExprClass: { 15458 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15459 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15460 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15461 } 15462 } 15463 15464 llvm_unreachable("Invalid StmtClass!"); 15465 } 15466 15467 /// Evaluate an expression as a C++11 integral constant expression. 15468 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15469 const Expr *E, 15470 llvm::APSInt *Value, 15471 SourceLocation *Loc) { 15472 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15473 if (Loc) *Loc = E->getExprLoc(); 15474 return false; 15475 } 15476 15477 APValue Result; 15478 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15479 return false; 15480 15481 if (!Result.isInt()) { 15482 if (Loc) *Loc = E->getExprLoc(); 15483 return false; 15484 } 15485 15486 if (Value) *Value = Result.getInt(); 15487 return true; 15488 } 15489 15490 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15491 SourceLocation *Loc) const { 15492 assert(!isValueDependent() && 15493 "Expression evaluator can't be called on a dependent expression."); 15494 15495 if (Ctx.getLangOpts().CPlusPlus11) 15496 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15497 15498 ICEDiag D = CheckICE(this, Ctx); 15499 if (D.Kind != IK_ICE) { 15500 if (Loc) *Loc = D.Loc; 15501 return false; 15502 } 15503 return true; 15504 } 15505 15506 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15507 SourceLocation *Loc, 15508 bool isEvaluated) const { 15509 if (isValueDependent()) { 15510 // Expression evaluator can't succeed on a dependent expression. 15511 return None; 15512 } 15513 15514 APSInt Value; 15515 15516 if (Ctx.getLangOpts().CPlusPlus11) { 15517 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15518 return Value; 15519 return None; 15520 } 15521 15522 if (!isIntegerConstantExpr(Ctx, Loc)) 15523 return None; 15524 15525 // The only possible side-effects here are due to UB discovered in the 15526 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15527 // required to treat the expression as an ICE, so we produce the folded 15528 // value. 15529 EvalResult ExprResult; 15530 Expr::EvalStatus Status; 15531 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15532 Info.InConstantContext = true; 15533 15534 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15535 llvm_unreachable("ICE cannot be evaluated!"); 15536 15537 return ExprResult.Val.getInt(); 15538 } 15539 15540 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15541 assert(!isValueDependent() && 15542 "Expression evaluator can't be called on a dependent expression."); 15543 15544 return CheckICE(this, Ctx).Kind == IK_ICE; 15545 } 15546 15547 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15548 SourceLocation *Loc) const { 15549 assert(!isValueDependent() && 15550 "Expression evaluator can't be called on a dependent expression."); 15551 15552 // We support this checking in C++98 mode in order to diagnose compatibility 15553 // issues. 15554 assert(Ctx.getLangOpts().CPlusPlus); 15555 15556 // Build evaluation settings. 15557 Expr::EvalStatus Status; 15558 SmallVector<PartialDiagnosticAt, 8> Diags; 15559 Status.Diag = &Diags; 15560 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15561 15562 APValue Scratch; 15563 bool IsConstExpr = 15564 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15565 // FIXME: We don't produce a diagnostic for this, but the callers that 15566 // call us on arbitrary full-expressions should generally not care. 15567 Info.discardCleanups() && !Status.HasSideEffects; 15568 15569 if (!Diags.empty()) { 15570 IsConstExpr = false; 15571 if (Loc) *Loc = Diags[0].first; 15572 } else if (!IsConstExpr) { 15573 // FIXME: This shouldn't happen. 15574 if (Loc) *Loc = getExprLoc(); 15575 } 15576 15577 return IsConstExpr; 15578 } 15579 15580 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15581 const FunctionDecl *Callee, 15582 ArrayRef<const Expr*> Args, 15583 const Expr *This) const { 15584 assert(!isValueDependent() && 15585 "Expression evaluator can't be called on a dependent expression."); 15586 15587 Expr::EvalStatus Status; 15588 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15589 Info.InConstantContext = true; 15590 15591 LValue ThisVal; 15592 const LValue *ThisPtr = nullptr; 15593 if (This) { 15594 #ifndef NDEBUG 15595 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15596 assert(MD && "Don't provide `this` for non-methods."); 15597 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15598 #endif 15599 if (!This->isValueDependent() && 15600 EvaluateObjectArgument(Info, This, ThisVal) && 15601 !Info.EvalStatus.HasSideEffects) 15602 ThisPtr = &ThisVal; 15603 15604 // Ignore any side-effects from a failed evaluation. This is safe because 15605 // they can't interfere with any other argument evaluation. 15606 Info.EvalStatus.HasSideEffects = false; 15607 } 15608 15609 CallRef Call = Info.CurrentCall->createCall(Callee); 15610 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15611 I != E; ++I) { 15612 unsigned Idx = I - Args.begin(); 15613 if (Idx >= Callee->getNumParams()) 15614 break; 15615 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15616 if ((*I)->isValueDependent() || 15617 !EvaluateCallArg(PVD, *I, Call, Info) || 15618 Info.EvalStatus.HasSideEffects) { 15619 // If evaluation fails, throw away the argument entirely. 15620 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15621 *Slot = APValue(); 15622 } 15623 15624 // Ignore any side-effects from a failed evaluation. This is safe because 15625 // they can't interfere with any other argument evaluation. 15626 Info.EvalStatus.HasSideEffects = false; 15627 } 15628 15629 // Parameter cleanups happen in the caller and are not part of this 15630 // evaluation. 15631 Info.discardCleanups(); 15632 Info.EvalStatus.HasSideEffects = false; 15633 15634 // Build fake call to Callee. 15635 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15636 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15637 FullExpressionRAII Scope(Info); 15638 return Evaluate(Value, Info, this) && Scope.destroy() && 15639 !Info.EvalStatus.HasSideEffects; 15640 } 15641 15642 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15643 SmallVectorImpl< 15644 PartialDiagnosticAt> &Diags) { 15645 // FIXME: It would be useful to check constexpr function templates, but at the 15646 // moment the constant expression evaluator cannot cope with the non-rigorous 15647 // ASTs which we build for dependent expressions. 15648 if (FD->isDependentContext()) 15649 return true; 15650 15651 Expr::EvalStatus Status; 15652 Status.Diag = &Diags; 15653 15654 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15655 Info.InConstantContext = true; 15656 Info.CheckingPotentialConstantExpression = true; 15657 15658 // The constexpr VM attempts to compile all methods to bytecode here. 15659 if (Info.EnableNewConstInterp) { 15660 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15661 return Diags.empty(); 15662 } 15663 15664 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15665 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15666 15667 // Fabricate an arbitrary expression on the stack and pretend that it 15668 // is a temporary being used as the 'this' pointer. 15669 LValue This; 15670 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15671 This.set({&VIE, Info.CurrentCall->Index}); 15672 15673 ArrayRef<const Expr*> Args; 15674 15675 APValue Scratch; 15676 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15677 // Evaluate the call as a constant initializer, to allow the construction 15678 // of objects of non-literal types. 15679 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15680 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15681 } else { 15682 SourceLocation Loc = FD->getLocation(); 15683 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15684 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15685 } 15686 15687 return Diags.empty(); 15688 } 15689 15690 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15691 const FunctionDecl *FD, 15692 SmallVectorImpl< 15693 PartialDiagnosticAt> &Diags) { 15694 assert(!E->isValueDependent() && 15695 "Expression evaluator can't be called on a dependent expression."); 15696 15697 Expr::EvalStatus Status; 15698 Status.Diag = &Diags; 15699 15700 EvalInfo Info(FD->getASTContext(), Status, 15701 EvalInfo::EM_ConstantExpressionUnevaluated); 15702 Info.InConstantContext = true; 15703 Info.CheckingPotentialConstantExpression = true; 15704 15705 // Fabricate a call stack frame to give the arguments a plausible cover story. 15706 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15707 15708 APValue ResultScratch; 15709 Evaluate(ResultScratch, Info, E); 15710 return Diags.empty(); 15711 } 15712 15713 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15714 unsigned Type) const { 15715 if (!getType()->isPointerType()) 15716 return false; 15717 15718 Expr::EvalStatus Status; 15719 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15720 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15721 } 15722 15723 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15724 EvalInfo &Info) { 15725 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15726 return false; 15727 15728 LValue String; 15729 15730 if (!EvaluatePointer(E, String, Info)) 15731 return false; 15732 15733 QualType CharTy = E->getType()->getPointeeType(); 15734 15735 // Fast path: if it's a string literal, search the string value. 15736 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15737 String.getLValueBase().dyn_cast<const Expr *>())) { 15738 StringRef Str = S->getBytes(); 15739 int64_t Off = String.Offset.getQuantity(); 15740 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15741 S->getCharByteWidth() == 1 && 15742 // FIXME: Add fast-path for wchar_t too. 15743 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 15744 Str = Str.substr(Off); 15745 15746 StringRef::size_type Pos = Str.find(0); 15747 if (Pos != StringRef::npos) 15748 Str = Str.substr(0, Pos); 15749 15750 Result = Str.size(); 15751 return true; 15752 } 15753 15754 // Fall through to slow path. 15755 } 15756 15757 // Slow path: scan the bytes of the string looking for the terminating 0. 15758 for (uint64_t Strlen = 0; /**/; ++Strlen) { 15759 APValue Char; 15760 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 15761 !Char.isInt()) 15762 return false; 15763 if (!Char.getInt()) { 15764 Result = Strlen; 15765 return true; 15766 } 15767 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 15768 return false; 15769 } 15770 } 15771 15772 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 15773 Expr::EvalStatus Status; 15774 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15775 return EvaluateBuiltinStrLen(this, Result, Info); 15776 } 15777