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->isRValue()) 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 const FunctionDecl *Callee = CE->getDirectCallee(); 112 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 113 } 114 115 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 116 /// This will look through a single cast. 117 /// 118 /// Returns null if we couldn't unwrap a function with alloc_size. 119 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 120 if (!E->getType()->isPointerType()) 121 return nullptr; 122 123 E = E->IgnoreParens(); 124 // If we're doing a variable assignment from e.g. malloc(N), there will 125 // probably be a cast of some kind. In exotic cases, we might also see a 126 // top-level ExprWithCleanups. Ignore them either way. 127 if (const auto *FE = dyn_cast<FullExpr>(E)) 128 E = FE->getSubExpr()->IgnoreParens(); 129 130 if (const auto *Cast = dyn_cast<CastExpr>(E)) 131 E = Cast->getSubExpr()->IgnoreParens(); 132 133 if (const auto *CE = dyn_cast<CallExpr>(E)) 134 return getAllocSizeAttr(CE) ? CE : nullptr; 135 return nullptr; 136 } 137 138 /// Determines whether or not the given Base contains a call to a function 139 /// with the alloc_size attribute. 140 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 141 const auto *E = Base.dyn_cast<const Expr *>(); 142 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 143 } 144 145 /// Determines whether the given kind of constant expression is only ever 146 /// used for name mangling. If so, it's permitted to reference things that we 147 /// can't generate code for (in particular, dllimported functions). 148 static bool isForManglingOnly(ConstantExprKind Kind) { 149 switch (Kind) { 150 case ConstantExprKind::Normal: 151 case ConstantExprKind::ClassTemplateArgument: 152 case ConstantExprKind::ImmediateInvocation: 153 // Note that non-type template arguments of class type are emitted as 154 // template parameter objects. 155 return false; 156 157 case ConstantExprKind::NonClassTemplateArgument: 158 return true; 159 } 160 llvm_unreachable("unknown ConstantExprKind"); 161 } 162 163 static bool isTemplateArgument(ConstantExprKind Kind) { 164 switch (Kind) { 165 case ConstantExprKind::Normal: 166 case ConstantExprKind::ImmediateInvocation: 167 return false; 168 169 case ConstantExprKind::ClassTemplateArgument: 170 case ConstantExprKind::NonClassTemplateArgument: 171 return true; 172 } 173 llvm_unreachable("unknown ConstantExprKind"); 174 } 175 176 /// The bound to claim that an array of unknown bound has. 177 /// The value in MostDerivedArraySize is undefined in this case. So, set it 178 /// to an arbitrary value that's likely to loudly break things if it's used. 179 static const uint64_t AssumedSizeForUnsizedArray = 180 std::numeric_limits<uint64_t>::max() / 2; 181 182 /// Determines if an LValue with the given LValueBase will have an unsized 183 /// array in its designator. 184 /// Find the path length and type of the most-derived subobject in the given 185 /// path, and find the size of the containing array, if any. 186 static unsigned 187 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 188 ArrayRef<APValue::LValuePathEntry> Path, 189 uint64_t &ArraySize, QualType &Type, bool &IsArray, 190 bool &FirstEntryIsUnsizedArray) { 191 // This only accepts LValueBases from APValues, and APValues don't support 192 // arrays that lack size info. 193 assert(!isBaseAnAllocSizeCall(Base) && 194 "Unsized arrays shouldn't appear here"); 195 unsigned MostDerivedLength = 0; 196 Type = getType(Base); 197 198 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 199 if (Type->isArrayType()) { 200 const ArrayType *AT = Ctx.getAsArrayType(Type); 201 Type = AT->getElementType(); 202 MostDerivedLength = I + 1; 203 IsArray = true; 204 205 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 206 ArraySize = CAT->getSize().getZExtValue(); 207 } else { 208 assert(I == 0 && "unexpected unsized array designator"); 209 FirstEntryIsUnsizedArray = true; 210 ArraySize = AssumedSizeForUnsizedArray; 211 } 212 } else if (Type->isAnyComplexType()) { 213 const ComplexType *CT = Type->castAs<ComplexType>(); 214 Type = CT->getElementType(); 215 ArraySize = 2; 216 MostDerivedLength = I + 1; 217 IsArray = true; 218 } else if (const FieldDecl *FD = getAsField(Path[I])) { 219 Type = FD->getType(); 220 ArraySize = 0; 221 MostDerivedLength = I + 1; 222 IsArray = false; 223 } else { 224 // Path[I] describes a base class. 225 ArraySize = 0; 226 IsArray = false; 227 } 228 } 229 return MostDerivedLength; 230 } 231 232 /// A path from a glvalue to a subobject of that glvalue. 233 struct SubobjectDesignator { 234 /// True if the subobject was named in a manner not supported by C++11. Such 235 /// lvalues can still be folded, but they are not core constant expressions 236 /// and we cannot perform lvalue-to-rvalue conversions on them. 237 unsigned Invalid : 1; 238 239 /// Is this a pointer one past the end of an object? 240 unsigned IsOnePastTheEnd : 1; 241 242 /// Indicator of whether the first entry is an unsized array. 243 unsigned FirstEntryIsAnUnsizedArray : 1; 244 245 /// Indicator of whether the most-derived object is an array element. 246 unsigned MostDerivedIsArrayElement : 1; 247 248 /// The length of the path to the most-derived object of which this is a 249 /// subobject. 250 unsigned MostDerivedPathLength : 28; 251 252 /// The size of the array of which the most-derived object is an element. 253 /// This will always be 0 if the most-derived object is not an array 254 /// element. 0 is not an indicator of whether or not the most-derived object 255 /// is an array, however, because 0-length arrays are allowed. 256 /// 257 /// If the current array is an unsized array, the value of this is 258 /// undefined. 259 uint64_t MostDerivedArraySize; 260 261 /// The type of the most derived object referred to by this address. 262 QualType MostDerivedType; 263 264 typedef APValue::LValuePathEntry PathEntry; 265 266 /// The entries on the path from the glvalue to the designated subobject. 267 SmallVector<PathEntry, 8> Entries; 268 269 SubobjectDesignator() : Invalid(true) {} 270 271 explicit SubobjectDesignator(QualType T) 272 : Invalid(false), IsOnePastTheEnd(false), 273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 274 MostDerivedPathLength(0), MostDerivedArraySize(0), 275 MostDerivedType(T) {} 276 277 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 278 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 280 MostDerivedPathLength(0), MostDerivedArraySize(0) { 281 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 282 if (!Invalid) { 283 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 284 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 285 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 286 if (V.getLValueBase()) { 287 bool IsArray = false; 288 bool FirstIsUnsizedArray = false; 289 MostDerivedPathLength = findMostDerivedSubobject( 290 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 291 MostDerivedType, IsArray, FirstIsUnsizedArray); 292 MostDerivedIsArrayElement = IsArray; 293 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 294 } 295 } 296 } 297 298 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 299 unsigned NewLength) { 300 if (Invalid) 301 return; 302 303 assert(Base && "cannot truncate path for null pointer"); 304 assert(NewLength <= Entries.size() && "not a truncation"); 305 306 if (NewLength == Entries.size()) 307 return; 308 Entries.resize(NewLength); 309 310 bool IsArray = false; 311 bool FirstIsUnsizedArray = false; 312 MostDerivedPathLength = findMostDerivedSubobject( 313 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 314 FirstIsUnsizedArray); 315 MostDerivedIsArrayElement = IsArray; 316 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 317 } 318 319 void setInvalid() { 320 Invalid = true; 321 Entries.clear(); 322 } 323 324 /// Determine whether the most derived subobject is an array without a 325 /// known bound. 326 bool isMostDerivedAnUnsizedArray() const { 327 assert(!Invalid && "Calling this makes no sense on invalid designators"); 328 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 329 } 330 331 /// Determine what the most derived array's size is. Results in an assertion 332 /// failure if the most derived array lacks a size. 333 uint64_t getMostDerivedArraySize() const { 334 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 335 return MostDerivedArraySize; 336 } 337 338 /// Determine whether this is a one-past-the-end pointer. 339 bool isOnePastTheEnd() const { 340 assert(!Invalid); 341 if (IsOnePastTheEnd) 342 return true; 343 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 344 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 345 MostDerivedArraySize) 346 return true; 347 return false; 348 } 349 350 /// Get the range of valid index adjustments in the form 351 /// {maximum value that can be subtracted from this pointer, 352 /// maximum value that can be added to this pointer} 353 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 354 if (Invalid || isMostDerivedAnUnsizedArray()) 355 return {0, 0}; 356 357 // [expr.add]p4: For the purposes of these operators, a pointer to a 358 // nonarray object behaves the same as a pointer to the first element of 359 // an array of length one with the type of the object as its element type. 360 bool IsArray = MostDerivedPathLength == Entries.size() && 361 MostDerivedIsArrayElement; 362 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 363 : (uint64_t)IsOnePastTheEnd; 364 uint64_t ArraySize = 365 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 366 return {ArrayIndex, ArraySize - ArrayIndex}; 367 } 368 369 /// Check that this refers to a valid subobject. 370 bool isValidSubobject() const { 371 if (Invalid) 372 return false; 373 return !isOnePastTheEnd(); 374 } 375 /// Check that this refers to a valid subobject, and if not, produce a 376 /// relevant diagnostic and set the designator as invalid. 377 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 378 379 /// Get the type of the designated object. 380 QualType getType(ASTContext &Ctx) const { 381 assert(!Invalid && "invalid designator has no subobject type"); 382 return MostDerivedPathLength == Entries.size() 383 ? MostDerivedType 384 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 385 } 386 387 /// Update this designator to refer to the first element within this array. 388 void addArrayUnchecked(const ConstantArrayType *CAT) { 389 Entries.push_back(PathEntry::ArrayIndex(0)); 390 391 // This is a most-derived object. 392 MostDerivedType = CAT->getElementType(); 393 MostDerivedIsArrayElement = true; 394 MostDerivedArraySize = CAT->getSize().getZExtValue(); 395 MostDerivedPathLength = Entries.size(); 396 } 397 /// Update this designator to refer to the first element within the array of 398 /// elements of type T. This is an array of unknown size. 399 void addUnsizedArrayUnchecked(QualType ElemTy) { 400 Entries.push_back(PathEntry::ArrayIndex(0)); 401 402 MostDerivedType = ElemTy; 403 MostDerivedIsArrayElement = true; 404 // The value in MostDerivedArraySize is undefined in this case. So, set it 405 // to an arbitrary value that's likely to loudly break things if it's 406 // used. 407 MostDerivedArraySize = AssumedSizeForUnsizedArray; 408 MostDerivedPathLength = Entries.size(); 409 } 410 /// Update this designator to refer to the given base or member of this 411 /// object. 412 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 413 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 414 415 // If this isn't a base class, it's a new most-derived object. 416 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 417 MostDerivedType = FD->getType(); 418 MostDerivedIsArrayElement = false; 419 MostDerivedArraySize = 0; 420 MostDerivedPathLength = Entries.size(); 421 } 422 } 423 /// Update this designator to refer to the given complex component. 424 void addComplexUnchecked(QualType EltTy, bool Imag) { 425 Entries.push_back(PathEntry::ArrayIndex(Imag)); 426 427 // This is technically a most-derived object, though in practice this 428 // is unlikely to matter. 429 MostDerivedType = EltTy; 430 MostDerivedIsArrayElement = true; 431 MostDerivedArraySize = 2; 432 MostDerivedPathLength = Entries.size(); 433 } 434 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 435 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 436 const APSInt &N); 437 /// Add N to the address of this subobject. 438 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 439 if (Invalid || !N) return; 440 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 441 if (isMostDerivedAnUnsizedArray()) { 442 diagnoseUnsizedArrayPointerArithmetic(Info, E); 443 // Can't verify -- trust that the user is doing the right thing (or if 444 // not, trust that the caller will catch the bad behavior). 445 // FIXME: Should we reject if this overflows, at least? 446 Entries.back() = PathEntry::ArrayIndex( 447 Entries.back().getAsArrayIndex() + TruncatedN); 448 return; 449 } 450 451 // [expr.add]p4: For the purposes of these operators, a pointer to a 452 // nonarray object behaves the same as a pointer to the first element of 453 // an array of length one with the type of the object as its element type. 454 bool IsArray = MostDerivedPathLength == Entries.size() && 455 MostDerivedIsArrayElement; 456 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 457 : (uint64_t)IsOnePastTheEnd; 458 uint64_t ArraySize = 459 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 460 461 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 462 // Calculate the actual index in a wide enough type, so we can include 463 // it in the note. 464 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 465 (llvm::APInt&)N += ArrayIndex; 466 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 467 diagnosePointerArithmetic(Info, E, N); 468 setInvalid(); 469 return; 470 } 471 472 ArrayIndex += TruncatedN; 473 assert(ArrayIndex <= ArraySize && 474 "bounds check succeeded for out-of-bounds index"); 475 476 if (IsArray) 477 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 478 else 479 IsOnePastTheEnd = (ArrayIndex != 0); 480 } 481 }; 482 483 /// A scope at the end of which an object can need to be destroyed. 484 enum class ScopeKind { 485 Block, 486 FullExpression, 487 Call 488 }; 489 490 /// A reference to a particular call and its arguments. 491 struct CallRef { 492 CallRef() : OrigCallee(), CallIndex(0), Version() {} 493 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 494 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 495 496 explicit operator bool() const { return OrigCallee; } 497 498 /// Get the parameter that the caller initialized, corresponding to the 499 /// given parameter in the callee. 500 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 501 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 502 : PVD; 503 } 504 505 /// The callee at the point where the arguments were evaluated. This might 506 /// be different from the actual callee (a different redeclaration, or a 507 /// virtual override), but this function's parameters are the ones that 508 /// appear in the parameter map. 509 const FunctionDecl *OrigCallee; 510 /// The call index of the frame that holds the argument values. 511 unsigned CallIndex; 512 /// The version of the parameters corresponding to this call. 513 unsigned Version; 514 }; 515 516 /// A stack frame in the constexpr call stack. 517 class CallStackFrame : public interp::Frame { 518 public: 519 EvalInfo &Info; 520 521 /// Parent - The caller of this stack frame. 522 CallStackFrame *Caller; 523 524 /// Callee - The function which was called. 525 const FunctionDecl *Callee; 526 527 /// This - The binding for the this pointer in this call, if any. 528 const LValue *This; 529 530 /// Information on how to find the arguments to this call. Our arguments 531 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 532 /// key and this value as the version. 533 CallRef Arguments; 534 535 /// Source location information about the default argument or default 536 /// initializer expression we're evaluating, if any. 537 CurrentSourceLocExprScope CurSourceLocExprScope; 538 539 // Note that we intentionally use std::map here so that references to 540 // values are stable. 541 typedef std::pair<const void *, unsigned> MapKeyTy; 542 typedef std::map<MapKeyTy, APValue> MapTy; 543 /// Temporaries - Temporary lvalues materialized within this stack frame. 544 MapTy Temporaries; 545 546 /// CallLoc - The location of the call expression for this call. 547 SourceLocation CallLoc; 548 549 /// Index - The call index of this call. 550 unsigned Index; 551 552 /// The stack of integers for tracking version numbers for temporaries. 553 SmallVector<unsigned, 2> TempVersionStack = {1}; 554 unsigned CurTempVersion = TempVersionStack.back(); 555 556 unsigned getTempVersion() const { return TempVersionStack.back(); } 557 558 void pushTempVersion() { 559 TempVersionStack.push_back(++CurTempVersion); 560 } 561 562 void popTempVersion() { 563 TempVersionStack.pop_back(); 564 } 565 566 CallRef createCall(const FunctionDecl *Callee) { 567 return {Callee, Index, ++CurTempVersion}; 568 } 569 570 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 571 // on the overall stack usage of deeply-recursing constexpr evaluations. 572 // (We should cache this map rather than recomputing it repeatedly.) 573 // But let's try this and see how it goes; we can look into caching the map 574 // as a later change. 575 576 /// LambdaCaptureFields - Mapping from captured variables/this to 577 /// corresponding data members in the closure class. 578 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 579 FieldDecl *LambdaThisCaptureField; 580 581 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 582 const FunctionDecl *Callee, const LValue *This, 583 CallRef Arguments); 584 ~CallStackFrame(); 585 586 // Return the temporary for Key whose version number is Version. 587 APValue *getTemporary(const void *Key, unsigned Version) { 588 MapKeyTy KV(Key, Version); 589 auto LB = Temporaries.lower_bound(KV); 590 if (LB != Temporaries.end() && LB->first == KV) 591 return &LB->second; 592 // Pair (Key,Version) wasn't found in the map. Check that no elements 593 // in the map have 'Key' as their key. 594 assert((LB == Temporaries.end() || LB->first.first != Key) && 595 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 596 "Element with key 'Key' found in map"); 597 return nullptr; 598 } 599 600 // Return the current temporary for Key in the map. 601 APValue *getCurrentTemporary(const void *Key) { 602 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 603 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 604 return &std::prev(UB)->second; 605 return nullptr; 606 } 607 608 // Return the version number of the current temporary for Key. 609 unsigned getCurrentTemporaryVersion(const void *Key) const { 610 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 611 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 612 return std::prev(UB)->first.second; 613 return 0; 614 } 615 616 /// Allocate storage for an object of type T in this stack frame. 617 /// Populates LV with a handle to the created object. Key identifies 618 /// the temporary within the stack frame, and must not be reused without 619 /// bumping the temporary version number. 620 template<typename KeyT> 621 APValue &createTemporary(const KeyT *Key, QualType T, 622 ScopeKind Scope, LValue &LV); 623 624 /// Allocate storage for a parameter of a function call made in this frame. 625 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 626 627 void describe(llvm::raw_ostream &OS) override; 628 629 Frame *getCaller() const override { return Caller; } 630 SourceLocation getCallLocation() const override { return CallLoc; } 631 const FunctionDecl *getCallee() const override { return Callee; } 632 633 bool isStdFunction() const { 634 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 635 if (DC->isStdNamespace()) 636 return true; 637 return false; 638 } 639 640 private: 641 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 642 ScopeKind Scope); 643 }; 644 645 /// Temporarily override 'this'. 646 class ThisOverrideRAII { 647 public: 648 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 649 : Frame(Frame), OldThis(Frame.This) { 650 if (Enable) 651 Frame.This = NewThis; 652 } 653 ~ThisOverrideRAII() { 654 Frame.This = OldThis; 655 } 656 private: 657 CallStackFrame &Frame; 658 const LValue *OldThis; 659 }; 660 } 661 662 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 663 const LValue &This, QualType ThisType); 664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 665 APValue::LValueBase LVBase, APValue &Value, 666 QualType T); 667 668 namespace { 669 /// A cleanup, and a flag indicating whether it is lifetime-extended. 670 class Cleanup { 671 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 672 APValue::LValueBase Base; 673 QualType T; 674 675 public: 676 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 677 ScopeKind Scope) 678 : Value(Val, Scope), Base(Base), T(T) {} 679 680 /// Determine whether this cleanup should be performed at the end of the 681 /// given kind of scope. 682 bool isDestroyedAtEndOf(ScopeKind K) const { 683 return (int)Value.getInt() >= (int)K; 684 } 685 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 686 if (RunDestructors) { 687 SourceLocation Loc; 688 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 689 Loc = VD->getLocation(); 690 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 691 Loc = E->getExprLoc(); 692 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 693 } 694 *Value.getPointer() = APValue(); 695 return true; 696 } 697 698 bool hasSideEffect() { 699 return T.isDestructedType(); 700 } 701 }; 702 703 /// A reference to an object whose construction we are currently evaluating. 704 struct ObjectUnderConstruction { 705 APValue::LValueBase Base; 706 ArrayRef<APValue::LValuePathEntry> Path; 707 friend bool operator==(const ObjectUnderConstruction &LHS, 708 const ObjectUnderConstruction &RHS) { 709 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 710 } 711 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 712 return llvm::hash_combine(Obj.Base, Obj.Path); 713 } 714 }; 715 enum class ConstructionPhase { 716 None, 717 Bases, 718 AfterBases, 719 AfterFields, 720 Destroying, 721 DestroyingBases 722 }; 723 } 724 725 namespace llvm { 726 template<> struct DenseMapInfo<ObjectUnderConstruction> { 727 using Base = DenseMapInfo<APValue::LValueBase>; 728 static ObjectUnderConstruction getEmptyKey() { 729 return {Base::getEmptyKey(), {}}; } 730 static ObjectUnderConstruction getTombstoneKey() { 731 return {Base::getTombstoneKey(), {}}; 732 } 733 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 734 return hash_value(Object); 735 } 736 static bool isEqual(const ObjectUnderConstruction &LHS, 737 const ObjectUnderConstruction &RHS) { 738 return LHS == RHS; 739 } 740 }; 741 } 742 743 namespace { 744 /// A dynamically-allocated heap object. 745 struct DynAlloc { 746 /// The value of this heap-allocated object. 747 APValue Value; 748 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 749 /// or a CallExpr (the latter is for direct calls to operator new inside 750 /// std::allocator<T>::allocate). 751 const Expr *AllocExpr = nullptr; 752 753 enum Kind { 754 New, 755 ArrayNew, 756 StdAllocator 757 }; 758 759 /// Get the kind of the allocation. This must match between allocation 760 /// and deallocation. 761 Kind getKind() const { 762 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 763 return NE->isArray() ? ArrayNew : New; 764 assert(isa<CallExpr>(AllocExpr)); 765 return StdAllocator; 766 } 767 }; 768 769 struct DynAllocOrder { 770 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 771 return L.getIndex() < R.getIndex(); 772 } 773 }; 774 775 /// EvalInfo - This is a private struct used by the evaluator to capture 776 /// information about a subexpression as it is folded. It retains information 777 /// about the AST context, but also maintains information about the folded 778 /// expression. 779 /// 780 /// If an expression could be evaluated, it is still possible it is not a C 781 /// "integer constant expression" or constant expression. If not, this struct 782 /// captures information about how and why not. 783 /// 784 /// One bit of information passed *into* the request for constant folding 785 /// indicates whether the subexpression is "evaluated" or not according to C 786 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 787 /// evaluate the expression regardless of what the RHS is, but C only allows 788 /// certain things in certain situations. 789 class EvalInfo : public interp::State { 790 public: 791 ASTContext &Ctx; 792 793 /// EvalStatus - Contains information about the evaluation. 794 Expr::EvalStatus &EvalStatus; 795 796 /// CurrentCall - The top of the constexpr call stack. 797 CallStackFrame *CurrentCall; 798 799 /// CallStackDepth - The number of calls in the call stack right now. 800 unsigned CallStackDepth; 801 802 /// NextCallIndex - The next call index to assign. 803 unsigned NextCallIndex; 804 805 /// StepsLeft - The remaining number of evaluation steps we're permitted 806 /// to perform. This is essentially a limit for the number of statements 807 /// we will evaluate. 808 unsigned StepsLeft; 809 810 /// Enable the experimental new constant interpreter. If an expression is 811 /// not supported by the interpreter, an error is triggered. 812 bool EnableNewConstInterp; 813 814 /// BottomFrame - The frame in which evaluation started. This must be 815 /// initialized after CurrentCall and CallStackDepth. 816 CallStackFrame BottomFrame; 817 818 /// A stack of values whose lifetimes end at the end of some surrounding 819 /// evaluation frame. 820 llvm::SmallVector<Cleanup, 16> CleanupStack; 821 822 /// EvaluatingDecl - This is the declaration whose initializer is being 823 /// evaluated, if any. 824 APValue::LValueBase EvaluatingDecl; 825 826 enum class EvaluatingDeclKind { 827 None, 828 /// We're evaluating the construction of EvaluatingDecl. 829 Ctor, 830 /// We're evaluating the destruction of EvaluatingDecl. 831 Dtor, 832 }; 833 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 834 835 /// EvaluatingDeclValue - This is the value being constructed for the 836 /// declaration whose initializer is being evaluated, if any. 837 APValue *EvaluatingDeclValue; 838 839 /// Set of objects that are currently being constructed. 840 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 841 ObjectsUnderConstruction; 842 843 /// Current heap allocations, along with the location where each was 844 /// allocated. We use std::map here because we need stable addresses 845 /// for the stored APValues. 846 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 847 848 /// The number of heap allocations performed so far in this evaluation. 849 unsigned NumHeapAllocs = 0; 850 851 struct EvaluatingConstructorRAII { 852 EvalInfo &EI; 853 ObjectUnderConstruction Object; 854 bool DidInsert; 855 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 856 bool HasBases) 857 : EI(EI), Object(Object) { 858 DidInsert = 859 EI.ObjectsUnderConstruction 860 .insert({Object, HasBases ? ConstructionPhase::Bases 861 : ConstructionPhase::AfterBases}) 862 .second; 863 } 864 void finishedConstructingBases() { 865 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 866 } 867 void finishedConstructingFields() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 869 } 870 ~EvaluatingConstructorRAII() { 871 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 872 } 873 }; 874 875 struct EvaluatingDestructorRAII { 876 EvalInfo &EI; 877 ObjectUnderConstruction Object; 878 bool DidInsert; 879 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 880 : EI(EI), Object(Object) { 881 DidInsert = EI.ObjectsUnderConstruction 882 .insert({Object, ConstructionPhase::Destroying}) 883 .second; 884 } 885 void startedDestroyingBases() { 886 EI.ObjectsUnderConstruction[Object] = 887 ConstructionPhase::DestroyingBases; 888 } 889 ~EvaluatingDestructorRAII() { 890 if (DidInsert) 891 EI.ObjectsUnderConstruction.erase(Object); 892 } 893 }; 894 895 ConstructionPhase 896 isEvaluatingCtorDtor(APValue::LValueBase Base, 897 ArrayRef<APValue::LValuePathEntry> Path) { 898 return ObjectsUnderConstruction.lookup({Base, Path}); 899 } 900 901 /// If we're currently speculatively evaluating, the outermost call stack 902 /// depth at which we can mutate state, otherwise 0. 903 unsigned SpeculativeEvaluationDepth = 0; 904 905 /// The current array initialization index, if we're performing array 906 /// initialization. 907 uint64_t ArrayInitIndex = -1; 908 909 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 910 /// notes attached to it will also be stored, otherwise they will not be. 911 bool HasActiveDiagnostic; 912 913 /// Have we emitted a diagnostic explaining why we couldn't constant 914 /// fold (not just why it's not strictly a constant expression)? 915 bool HasFoldFailureDiagnostic; 916 917 /// Whether or not we're in a context where the front end requires a 918 /// constant value. 919 bool InConstantContext; 920 921 /// Whether we're checking that an expression is a potential constant 922 /// expression. If so, do not fail on constructs that could become constant 923 /// later on (such as a use of an undefined global). 924 bool CheckingPotentialConstantExpression = false; 925 926 /// Whether we're checking for an expression that has undefined behavior. 927 /// If so, we will produce warnings if we encounter an operation that is 928 /// always undefined. 929 /// 930 /// Note that we still need to evaluate the expression normally when this 931 /// is set; this is used when evaluating ICEs in C. 932 bool CheckingForUndefinedBehavior = false; 933 934 enum EvaluationMode { 935 /// Evaluate as a constant expression. Stop if we find that the expression 936 /// is not a constant expression. 937 EM_ConstantExpression, 938 939 /// Evaluate as a constant expression. Stop if we find that the expression 940 /// is not a constant expression. Some expressions can be retried in the 941 /// optimizer if we don't constant fold them here, but in an unevaluated 942 /// context we try to fold them immediately since the optimizer never 943 /// gets a chance to look at it. 944 EM_ConstantExpressionUnevaluated, 945 946 /// Fold the expression to a constant. Stop if we hit a side-effect that 947 /// we can't model. 948 EM_ConstantFold, 949 950 /// Evaluate in any way we know how. Don't worry about side-effects that 951 /// can't be modeled. 952 EM_IgnoreSideEffects, 953 } EvalMode; 954 955 /// Are we checking whether the expression is a potential constant 956 /// expression? 957 bool checkingPotentialConstantExpression() const override { 958 return CheckingPotentialConstantExpression; 959 } 960 961 /// Are we checking an expression for overflow? 962 // FIXME: We should check for any kind of undefined or suspicious behavior 963 // in such constructs, not just overflow. 964 bool checkingForUndefinedBehavior() const override { 965 return CheckingForUndefinedBehavior; 966 } 967 968 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 969 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 970 CallStackDepth(0), NextCallIndex(1), 971 StepsLeft(C.getLangOpts().ConstexprStepLimit), 972 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 973 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 974 EvaluatingDecl((const ValueDecl *)nullptr), 975 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 976 HasFoldFailureDiagnostic(false), InConstantContext(false), 977 EvalMode(Mode) {} 978 979 ~EvalInfo() { 980 discardCleanups(); 981 } 982 983 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 984 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 985 EvaluatingDecl = Base; 986 IsEvaluatingDecl = EDK; 987 EvaluatingDeclValue = &Value; 988 } 989 990 bool CheckCallLimit(SourceLocation Loc) { 991 // Don't perform any constexpr calls (other than the call we're checking) 992 // when checking a potential constant expression. 993 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 994 return false; 995 if (NextCallIndex == 0) { 996 // NextCallIndex has wrapped around. 997 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 998 return false; 999 } 1000 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1001 return true; 1002 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1003 << getLangOpts().ConstexprCallDepth; 1004 return false; 1005 } 1006 1007 std::pair<CallStackFrame *, unsigned> 1008 getCallFrameAndDepth(unsigned CallIndex) { 1009 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1010 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1011 // be null in this loop. 1012 unsigned Depth = CallStackDepth; 1013 CallStackFrame *Frame = CurrentCall; 1014 while (Frame->Index > CallIndex) { 1015 Frame = Frame->Caller; 1016 --Depth; 1017 } 1018 if (Frame->Index == CallIndex) 1019 return {Frame, Depth}; 1020 return {nullptr, 0}; 1021 } 1022 1023 bool nextStep(const Stmt *S) { 1024 if (!StepsLeft) { 1025 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1026 return false; 1027 } 1028 --StepsLeft; 1029 return true; 1030 } 1031 1032 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1033 1034 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1035 Optional<DynAlloc*> Result; 1036 auto It = HeapAllocs.find(DA); 1037 if (It != HeapAllocs.end()) 1038 Result = &It->second; 1039 return Result; 1040 } 1041 1042 /// Get the allocated storage for the given parameter of the given call. 1043 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1044 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1045 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1046 : nullptr; 1047 } 1048 1049 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1050 struct StdAllocatorCaller { 1051 unsigned FrameIndex; 1052 QualType ElemType; 1053 explicit operator bool() const { return FrameIndex != 0; }; 1054 }; 1055 1056 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1057 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1058 Call = Call->Caller) { 1059 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1060 if (!MD) 1061 continue; 1062 const IdentifierInfo *FnII = MD->getIdentifier(); 1063 if (!FnII || !FnII->isStr(FnName)) 1064 continue; 1065 1066 const auto *CTSD = 1067 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1068 if (!CTSD) 1069 continue; 1070 1071 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1072 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1073 if (CTSD->isInStdNamespace() && ClassII && 1074 ClassII->isStr("allocator") && TAL.size() >= 1 && 1075 TAL[0].getKind() == TemplateArgument::Type) 1076 return {Call->Index, TAL[0].getAsType()}; 1077 } 1078 1079 return {}; 1080 } 1081 1082 void performLifetimeExtension() { 1083 // Disable the cleanups for lifetime-extended temporaries. 1084 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1085 CleanupStack.end(), 1086 [](Cleanup &C) { 1087 return !C.isDestroyedAtEndOf( 1088 ScopeKind::FullExpression); 1089 }), 1090 CleanupStack.end()); 1091 } 1092 1093 /// Throw away any remaining cleanups at the end of evaluation. If any 1094 /// cleanups would have had a side-effect, note that as an unmodeled 1095 /// side-effect and return false. Otherwise, return true. 1096 bool discardCleanups() { 1097 for (Cleanup &C : CleanupStack) { 1098 if (C.hasSideEffect() && !noteSideEffect()) { 1099 CleanupStack.clear(); 1100 return false; 1101 } 1102 } 1103 CleanupStack.clear(); 1104 return true; 1105 } 1106 1107 private: 1108 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1109 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1110 1111 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1112 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1113 1114 void setFoldFailureDiagnostic(bool Flag) override { 1115 HasFoldFailureDiagnostic = Flag; 1116 } 1117 1118 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1119 1120 ASTContext &getCtx() const override { return Ctx; } 1121 1122 // If we have a prior diagnostic, it will be noting that the expression 1123 // isn't a constant expression. This diagnostic is more important, 1124 // unless we require this evaluation to produce a constant expression. 1125 // 1126 // FIXME: We might want to show both diagnostics to the user in 1127 // EM_ConstantFold mode. 1128 bool hasPriorDiagnostic() override { 1129 if (!EvalStatus.Diag->empty()) { 1130 switch (EvalMode) { 1131 case EM_ConstantFold: 1132 case EM_IgnoreSideEffects: 1133 if (!HasFoldFailureDiagnostic) 1134 break; 1135 // We've already failed to fold something. Keep that diagnostic. 1136 LLVM_FALLTHROUGH; 1137 case EM_ConstantExpression: 1138 case EM_ConstantExpressionUnevaluated: 1139 setActiveDiagnostic(false); 1140 return true; 1141 } 1142 } 1143 return false; 1144 } 1145 1146 unsigned getCallStackDepth() override { return CallStackDepth; } 1147 1148 public: 1149 /// Should we continue evaluation after encountering a side-effect that we 1150 /// couldn't model? 1151 bool keepEvaluatingAfterSideEffect() { 1152 switch (EvalMode) { 1153 case EM_IgnoreSideEffects: 1154 return true; 1155 1156 case EM_ConstantExpression: 1157 case EM_ConstantExpressionUnevaluated: 1158 case EM_ConstantFold: 1159 // By default, assume any side effect might be valid in some other 1160 // evaluation of this expression from a different context. 1161 return checkingPotentialConstantExpression() || 1162 checkingForUndefinedBehavior(); 1163 } 1164 llvm_unreachable("Missed EvalMode case"); 1165 } 1166 1167 /// Note that we have had a side-effect, and determine whether we should 1168 /// keep evaluating. 1169 bool noteSideEffect() { 1170 EvalStatus.HasSideEffects = true; 1171 return keepEvaluatingAfterSideEffect(); 1172 } 1173 1174 /// Should we continue evaluation after encountering undefined behavior? 1175 bool keepEvaluatingAfterUndefinedBehavior() { 1176 switch (EvalMode) { 1177 case EM_IgnoreSideEffects: 1178 case EM_ConstantFold: 1179 return true; 1180 1181 case EM_ConstantExpression: 1182 case EM_ConstantExpressionUnevaluated: 1183 return checkingForUndefinedBehavior(); 1184 } 1185 llvm_unreachable("Missed EvalMode case"); 1186 } 1187 1188 /// Note that we hit something that was technically undefined behavior, but 1189 /// that we can evaluate past it (such as signed overflow or floating-point 1190 /// division by zero.) 1191 bool noteUndefinedBehavior() override { 1192 EvalStatus.HasUndefinedBehavior = true; 1193 return keepEvaluatingAfterUndefinedBehavior(); 1194 } 1195 1196 /// Should we continue evaluation as much as possible after encountering a 1197 /// construct which can't be reduced to a value? 1198 bool keepEvaluatingAfterFailure() const override { 1199 if (!StepsLeft) 1200 return false; 1201 1202 switch (EvalMode) { 1203 case EM_ConstantExpression: 1204 case EM_ConstantExpressionUnevaluated: 1205 case EM_ConstantFold: 1206 case EM_IgnoreSideEffects: 1207 return checkingPotentialConstantExpression() || 1208 checkingForUndefinedBehavior(); 1209 } 1210 llvm_unreachable("Missed EvalMode case"); 1211 } 1212 1213 /// Notes that we failed to evaluate an expression that other expressions 1214 /// directly depend on, and determine if we should keep evaluating. This 1215 /// should only be called if we actually intend to keep evaluating. 1216 /// 1217 /// Call noteSideEffect() instead if we may be able to ignore the value that 1218 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1219 /// 1220 /// (Foo(), 1) // use noteSideEffect 1221 /// (Foo() || true) // use noteSideEffect 1222 /// Foo() + 1 // use noteFailure 1223 LLVM_NODISCARD bool noteFailure() { 1224 // Failure when evaluating some expression often means there is some 1225 // subexpression whose evaluation was skipped. Therefore, (because we 1226 // don't track whether we skipped an expression when unwinding after an 1227 // evaluation failure) every evaluation failure that bubbles up from a 1228 // subexpression implies that a side-effect has potentially happened. We 1229 // skip setting the HasSideEffects flag to true until we decide to 1230 // continue evaluating after that point, which happens here. 1231 bool KeepGoing = keepEvaluatingAfterFailure(); 1232 EvalStatus.HasSideEffects |= KeepGoing; 1233 return KeepGoing; 1234 } 1235 1236 class ArrayInitLoopIndex { 1237 EvalInfo &Info; 1238 uint64_t OuterIndex; 1239 1240 public: 1241 ArrayInitLoopIndex(EvalInfo &Info) 1242 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1243 Info.ArrayInitIndex = 0; 1244 } 1245 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1246 1247 operator uint64_t&() { return Info.ArrayInitIndex; } 1248 }; 1249 }; 1250 1251 /// Object used to treat all foldable expressions as constant expressions. 1252 struct FoldConstant { 1253 EvalInfo &Info; 1254 bool Enabled; 1255 bool HadNoPriorDiags; 1256 EvalInfo::EvaluationMode OldMode; 1257 1258 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1259 : Info(Info), 1260 Enabled(Enabled), 1261 HadNoPriorDiags(Info.EvalStatus.Diag && 1262 Info.EvalStatus.Diag->empty() && 1263 !Info.EvalStatus.HasSideEffects), 1264 OldMode(Info.EvalMode) { 1265 if (Enabled) 1266 Info.EvalMode = EvalInfo::EM_ConstantFold; 1267 } 1268 void keepDiagnostics() { Enabled = false; } 1269 ~FoldConstant() { 1270 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1271 !Info.EvalStatus.HasSideEffects) 1272 Info.EvalStatus.Diag->clear(); 1273 Info.EvalMode = OldMode; 1274 } 1275 }; 1276 1277 /// RAII object used to set the current evaluation mode to ignore 1278 /// side-effects. 1279 struct IgnoreSideEffectsRAII { 1280 EvalInfo &Info; 1281 EvalInfo::EvaluationMode OldMode; 1282 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1283 : Info(Info), OldMode(Info.EvalMode) { 1284 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1285 } 1286 1287 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1288 }; 1289 1290 /// RAII object used to optionally suppress diagnostics and side-effects from 1291 /// a speculative evaluation. 1292 class SpeculativeEvaluationRAII { 1293 EvalInfo *Info = nullptr; 1294 Expr::EvalStatus OldStatus; 1295 unsigned OldSpeculativeEvaluationDepth; 1296 1297 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1298 Info = Other.Info; 1299 OldStatus = Other.OldStatus; 1300 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1301 Other.Info = nullptr; 1302 } 1303 1304 void maybeRestoreState() { 1305 if (!Info) 1306 return; 1307 1308 Info->EvalStatus = OldStatus; 1309 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1310 } 1311 1312 public: 1313 SpeculativeEvaluationRAII() = default; 1314 1315 SpeculativeEvaluationRAII( 1316 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1317 : Info(&Info), OldStatus(Info.EvalStatus), 1318 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1319 Info.EvalStatus.Diag = NewDiag; 1320 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1321 } 1322 1323 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1324 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1325 moveFromAndCancel(std::move(Other)); 1326 } 1327 1328 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1329 maybeRestoreState(); 1330 moveFromAndCancel(std::move(Other)); 1331 return *this; 1332 } 1333 1334 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1335 }; 1336 1337 /// RAII object wrapping a full-expression or block scope, and handling 1338 /// the ending of the lifetime of temporaries created within it. 1339 template<ScopeKind Kind> 1340 class ScopeRAII { 1341 EvalInfo &Info; 1342 unsigned OldStackSize; 1343 public: 1344 ScopeRAII(EvalInfo &Info) 1345 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1346 // Push a new temporary version. This is needed to distinguish between 1347 // temporaries created in different iterations of a loop. 1348 Info.CurrentCall->pushTempVersion(); 1349 } 1350 bool destroy(bool RunDestructors = true) { 1351 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1352 OldStackSize = -1U; 1353 return OK; 1354 } 1355 ~ScopeRAII() { 1356 if (OldStackSize != -1U) 1357 destroy(false); 1358 // Body moved to a static method to encourage the compiler to inline away 1359 // instances of this class. 1360 Info.CurrentCall->popTempVersion(); 1361 } 1362 private: 1363 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1364 unsigned OldStackSize) { 1365 assert(OldStackSize <= Info.CleanupStack.size() && 1366 "running cleanups out of order?"); 1367 1368 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1369 // for a full-expression scope. 1370 bool Success = true; 1371 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1372 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1373 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1374 Success = false; 1375 break; 1376 } 1377 } 1378 } 1379 1380 // Compact any retained cleanups. 1381 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1382 if (Kind != ScopeKind::Block) 1383 NewEnd = 1384 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1385 return C.isDestroyedAtEndOf(Kind); 1386 }); 1387 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1388 return Success; 1389 } 1390 }; 1391 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1392 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1393 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1394 } 1395 1396 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1397 CheckSubobjectKind CSK) { 1398 if (Invalid) 1399 return false; 1400 if (isOnePastTheEnd()) { 1401 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1402 << CSK; 1403 setInvalid(); 1404 return false; 1405 } 1406 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1407 // must actually be at least one array element; even a VLA cannot have a 1408 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1409 return true; 1410 } 1411 1412 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1413 const Expr *E) { 1414 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1415 // Do not set the designator as invalid: we can represent this situation, 1416 // and correct handling of __builtin_object_size requires us to do so. 1417 } 1418 1419 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1420 const Expr *E, 1421 const APSInt &N) { 1422 // If we're complaining, we must be able to statically determine the size of 1423 // the most derived array. 1424 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1425 Info.CCEDiag(E, diag::note_constexpr_array_index) 1426 << N << /*array*/ 0 1427 << static_cast<unsigned>(getMostDerivedArraySize()); 1428 else 1429 Info.CCEDiag(E, diag::note_constexpr_array_index) 1430 << N << /*non-array*/ 1; 1431 setInvalid(); 1432 } 1433 1434 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1435 const FunctionDecl *Callee, const LValue *This, 1436 CallRef Call) 1437 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1438 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1439 Info.CurrentCall = this; 1440 ++Info.CallStackDepth; 1441 } 1442 1443 CallStackFrame::~CallStackFrame() { 1444 assert(Info.CurrentCall == this && "calls retired out of order"); 1445 --Info.CallStackDepth; 1446 Info.CurrentCall = Caller; 1447 } 1448 1449 static bool isRead(AccessKinds AK) { 1450 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1451 } 1452 1453 static bool isModification(AccessKinds AK) { 1454 switch (AK) { 1455 case AK_Read: 1456 case AK_ReadObjectRepresentation: 1457 case AK_MemberCall: 1458 case AK_DynamicCast: 1459 case AK_TypeId: 1460 return false; 1461 case AK_Assign: 1462 case AK_Increment: 1463 case AK_Decrement: 1464 case AK_Construct: 1465 case AK_Destroy: 1466 return true; 1467 } 1468 llvm_unreachable("unknown access kind"); 1469 } 1470 1471 static bool isAnyAccess(AccessKinds AK) { 1472 return isRead(AK) || isModification(AK); 1473 } 1474 1475 /// Is this an access per the C++ definition? 1476 static bool isFormalAccess(AccessKinds AK) { 1477 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1478 } 1479 1480 /// Is this kind of axcess valid on an indeterminate object value? 1481 static bool isValidIndeterminateAccess(AccessKinds AK) { 1482 switch (AK) { 1483 case AK_Read: 1484 case AK_Increment: 1485 case AK_Decrement: 1486 // These need the object's value. 1487 return false; 1488 1489 case AK_ReadObjectRepresentation: 1490 case AK_Assign: 1491 case AK_Construct: 1492 case AK_Destroy: 1493 // Construction and destruction don't need the value. 1494 return true; 1495 1496 case AK_MemberCall: 1497 case AK_DynamicCast: 1498 case AK_TypeId: 1499 // These aren't really meaningful on scalars. 1500 return true; 1501 } 1502 llvm_unreachable("unknown access kind"); 1503 } 1504 1505 namespace { 1506 struct ComplexValue { 1507 private: 1508 bool IsInt; 1509 1510 public: 1511 APSInt IntReal, IntImag; 1512 APFloat FloatReal, FloatImag; 1513 1514 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1515 1516 void makeComplexFloat() { IsInt = false; } 1517 bool isComplexFloat() const { return !IsInt; } 1518 APFloat &getComplexFloatReal() { return FloatReal; } 1519 APFloat &getComplexFloatImag() { return FloatImag; } 1520 1521 void makeComplexInt() { IsInt = true; } 1522 bool isComplexInt() const { return IsInt; } 1523 APSInt &getComplexIntReal() { return IntReal; } 1524 APSInt &getComplexIntImag() { return IntImag; } 1525 1526 void moveInto(APValue &v) const { 1527 if (isComplexFloat()) 1528 v = APValue(FloatReal, FloatImag); 1529 else 1530 v = APValue(IntReal, IntImag); 1531 } 1532 void setFrom(const APValue &v) { 1533 assert(v.isComplexFloat() || v.isComplexInt()); 1534 if (v.isComplexFloat()) { 1535 makeComplexFloat(); 1536 FloatReal = v.getComplexFloatReal(); 1537 FloatImag = v.getComplexFloatImag(); 1538 } else { 1539 makeComplexInt(); 1540 IntReal = v.getComplexIntReal(); 1541 IntImag = v.getComplexIntImag(); 1542 } 1543 } 1544 }; 1545 1546 struct LValue { 1547 APValue::LValueBase Base; 1548 CharUnits Offset; 1549 SubobjectDesignator Designator; 1550 bool IsNullPtr : 1; 1551 bool InvalidBase : 1; 1552 1553 const APValue::LValueBase getLValueBase() const { return Base; } 1554 CharUnits &getLValueOffset() { return Offset; } 1555 const CharUnits &getLValueOffset() const { return Offset; } 1556 SubobjectDesignator &getLValueDesignator() { return Designator; } 1557 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1558 bool isNullPointer() const { return IsNullPtr;} 1559 1560 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1561 unsigned getLValueVersion() const { return Base.getVersion(); } 1562 1563 void moveInto(APValue &V) const { 1564 if (Designator.Invalid) 1565 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1566 else { 1567 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1568 V = APValue(Base, Offset, Designator.Entries, 1569 Designator.IsOnePastTheEnd, IsNullPtr); 1570 } 1571 } 1572 void setFrom(ASTContext &Ctx, const APValue &V) { 1573 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1574 Base = V.getLValueBase(); 1575 Offset = V.getLValueOffset(); 1576 InvalidBase = false; 1577 Designator = SubobjectDesignator(Ctx, V); 1578 IsNullPtr = V.isNullPointer(); 1579 } 1580 1581 void set(APValue::LValueBase B, bool BInvalid = false) { 1582 #ifndef NDEBUG 1583 // We only allow a few types of invalid bases. Enforce that here. 1584 if (BInvalid) { 1585 const auto *E = B.get<const Expr *>(); 1586 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1587 "Unexpected type of invalid base"); 1588 } 1589 #endif 1590 1591 Base = B; 1592 Offset = CharUnits::fromQuantity(0); 1593 InvalidBase = BInvalid; 1594 Designator = SubobjectDesignator(getType(B)); 1595 IsNullPtr = false; 1596 } 1597 1598 void setNull(ASTContext &Ctx, QualType PointerTy) { 1599 Base = (const ValueDecl *)nullptr; 1600 Offset = 1601 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1602 InvalidBase = false; 1603 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1604 IsNullPtr = true; 1605 } 1606 1607 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1608 set(B, true); 1609 } 1610 1611 std::string toString(ASTContext &Ctx, QualType T) const { 1612 APValue Printable; 1613 moveInto(Printable); 1614 return Printable.getAsString(Ctx, T); 1615 } 1616 1617 private: 1618 // Check that this LValue is not based on a null pointer. If it is, produce 1619 // a diagnostic and mark the designator as invalid. 1620 template <typename GenDiagType> 1621 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1622 if (Designator.Invalid) 1623 return false; 1624 if (IsNullPtr) { 1625 GenDiag(); 1626 Designator.setInvalid(); 1627 return false; 1628 } 1629 return true; 1630 } 1631 1632 public: 1633 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1634 CheckSubobjectKind CSK) { 1635 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1636 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1637 }); 1638 } 1639 1640 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1641 AccessKinds AK) { 1642 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1643 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1644 }); 1645 } 1646 1647 // Check this LValue refers to an object. If not, set the designator to be 1648 // invalid and emit a diagnostic. 1649 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1650 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1651 Designator.checkSubobject(Info, E, CSK); 1652 } 1653 1654 void addDecl(EvalInfo &Info, const Expr *E, 1655 const Decl *D, bool Virtual = false) { 1656 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1657 Designator.addDeclUnchecked(D, Virtual); 1658 } 1659 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1660 if (!Designator.Entries.empty()) { 1661 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1662 Designator.setInvalid(); 1663 return; 1664 } 1665 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1666 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1667 Designator.FirstEntryIsAnUnsizedArray = true; 1668 Designator.addUnsizedArrayUnchecked(ElemTy); 1669 } 1670 } 1671 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1672 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1673 Designator.addArrayUnchecked(CAT); 1674 } 1675 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1676 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1677 Designator.addComplexUnchecked(EltTy, Imag); 1678 } 1679 void clearIsNullPointer() { 1680 IsNullPtr = false; 1681 } 1682 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1683 const APSInt &Index, CharUnits ElementSize) { 1684 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1685 // but we're not required to diagnose it and it's valid in C++.) 1686 if (!Index) 1687 return; 1688 1689 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1690 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1691 // offsets. 1692 uint64_t Offset64 = Offset.getQuantity(); 1693 uint64_t ElemSize64 = ElementSize.getQuantity(); 1694 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1695 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1696 1697 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1698 Designator.adjustIndex(Info, E, Index); 1699 clearIsNullPointer(); 1700 } 1701 void adjustOffset(CharUnits N) { 1702 Offset += N; 1703 if (N.getQuantity()) 1704 clearIsNullPointer(); 1705 } 1706 }; 1707 1708 struct MemberPtr { 1709 MemberPtr() {} 1710 explicit MemberPtr(const ValueDecl *Decl) : 1711 DeclAndIsDerivedMember(Decl, false), Path() {} 1712 1713 /// The member or (direct or indirect) field referred to by this member 1714 /// pointer, or 0 if this is a null member pointer. 1715 const ValueDecl *getDecl() const { 1716 return DeclAndIsDerivedMember.getPointer(); 1717 } 1718 /// Is this actually a member of some type derived from the relevant class? 1719 bool isDerivedMember() const { 1720 return DeclAndIsDerivedMember.getInt(); 1721 } 1722 /// Get the class which the declaration actually lives in. 1723 const CXXRecordDecl *getContainingRecord() const { 1724 return cast<CXXRecordDecl>( 1725 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1726 } 1727 1728 void moveInto(APValue &V) const { 1729 V = APValue(getDecl(), isDerivedMember(), Path); 1730 } 1731 void setFrom(const APValue &V) { 1732 assert(V.isMemberPointer()); 1733 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1734 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1735 Path.clear(); 1736 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1737 Path.insert(Path.end(), P.begin(), P.end()); 1738 } 1739 1740 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1741 /// whether the member is a member of some class derived from the class type 1742 /// of the member pointer. 1743 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1744 /// Path - The path of base/derived classes from the member declaration's 1745 /// class (exclusive) to the class type of the member pointer (inclusive). 1746 SmallVector<const CXXRecordDecl*, 4> Path; 1747 1748 /// Perform a cast towards the class of the Decl (either up or down the 1749 /// hierarchy). 1750 bool castBack(const CXXRecordDecl *Class) { 1751 assert(!Path.empty()); 1752 const CXXRecordDecl *Expected; 1753 if (Path.size() >= 2) 1754 Expected = Path[Path.size() - 2]; 1755 else 1756 Expected = getContainingRecord(); 1757 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1758 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1759 // if B does not contain the original member and is not a base or 1760 // derived class of the class containing the original member, the result 1761 // of the cast is undefined. 1762 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1763 // (D::*). We consider that to be a language defect. 1764 return false; 1765 } 1766 Path.pop_back(); 1767 return true; 1768 } 1769 /// Perform a base-to-derived member pointer cast. 1770 bool castToDerived(const CXXRecordDecl *Derived) { 1771 if (!getDecl()) 1772 return true; 1773 if (!isDerivedMember()) { 1774 Path.push_back(Derived); 1775 return true; 1776 } 1777 if (!castBack(Derived)) 1778 return false; 1779 if (Path.empty()) 1780 DeclAndIsDerivedMember.setInt(false); 1781 return true; 1782 } 1783 /// Perform a derived-to-base member pointer cast. 1784 bool castToBase(const CXXRecordDecl *Base) { 1785 if (!getDecl()) 1786 return true; 1787 if (Path.empty()) 1788 DeclAndIsDerivedMember.setInt(true); 1789 if (isDerivedMember()) { 1790 Path.push_back(Base); 1791 return true; 1792 } 1793 return castBack(Base); 1794 } 1795 }; 1796 1797 /// Compare two member pointers, which are assumed to be of the same type. 1798 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1799 if (!LHS.getDecl() || !RHS.getDecl()) 1800 return !LHS.getDecl() && !RHS.getDecl(); 1801 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1802 return false; 1803 return LHS.Path == RHS.Path; 1804 } 1805 } 1806 1807 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1808 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1809 const LValue &This, const Expr *E, 1810 bool AllowNonLiteralTypes = false); 1811 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1812 bool InvalidBaseOK = false); 1813 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1814 bool InvalidBaseOK = false); 1815 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1816 EvalInfo &Info); 1817 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1818 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1819 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1820 EvalInfo &Info); 1821 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1822 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1823 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1824 EvalInfo &Info); 1825 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1826 1827 /// Evaluate an integer or fixed point expression into an APResult. 1828 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1829 EvalInfo &Info); 1830 1831 /// Evaluate only a fixed point expression into an APResult. 1832 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1833 EvalInfo &Info); 1834 1835 //===----------------------------------------------------------------------===// 1836 // Misc utilities 1837 //===----------------------------------------------------------------------===// 1838 1839 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1840 /// preserving its value (by extending by up to one bit as needed). 1841 static void negateAsSigned(APSInt &Int) { 1842 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1843 Int = Int.extend(Int.getBitWidth() + 1); 1844 Int.setIsSigned(true); 1845 } 1846 Int = -Int; 1847 } 1848 1849 template<typename KeyT> 1850 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1851 ScopeKind Scope, LValue &LV) { 1852 unsigned Version = getTempVersion(); 1853 APValue::LValueBase Base(Key, Index, Version); 1854 LV.set(Base); 1855 return createLocal(Base, Key, T, Scope); 1856 } 1857 1858 /// Allocate storage for a parameter of a function call made in this frame. 1859 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1860 LValue &LV) { 1861 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1862 APValue::LValueBase Base(PVD, Index, Args.Version); 1863 LV.set(Base); 1864 // We always destroy parameters at the end of the call, even if we'd allow 1865 // them to live to the end of the full-expression at runtime, in order to 1866 // give portable results and match other compilers. 1867 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1868 } 1869 1870 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1871 QualType T, ScopeKind Scope) { 1872 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1873 unsigned Version = Base.getVersion(); 1874 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1875 assert(Result.isAbsent() && "local created multiple times"); 1876 1877 // If we're creating a local immediately in the operand of a speculative 1878 // evaluation, don't register a cleanup to be run outside the speculative 1879 // evaluation context, since we won't actually be able to initialize this 1880 // object. 1881 if (Index <= Info.SpeculativeEvaluationDepth) { 1882 if (T.isDestructedType()) 1883 Info.noteSideEffect(); 1884 } else { 1885 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1886 } 1887 return Result; 1888 } 1889 1890 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1891 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1892 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1893 return nullptr; 1894 } 1895 1896 DynamicAllocLValue DA(NumHeapAllocs++); 1897 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1898 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1899 std::forward_as_tuple(DA), std::tuple<>()); 1900 assert(Result.second && "reused a heap alloc index?"); 1901 Result.first->second.AllocExpr = E; 1902 return &Result.first->second.Value; 1903 } 1904 1905 /// Produce a string describing the given constexpr call. 1906 void CallStackFrame::describe(raw_ostream &Out) { 1907 unsigned ArgIndex = 0; 1908 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1909 !isa<CXXConstructorDecl>(Callee) && 1910 cast<CXXMethodDecl>(Callee)->isInstance(); 1911 1912 if (!IsMemberCall) 1913 Out << *Callee << '('; 1914 1915 if (This && IsMemberCall) { 1916 APValue Val; 1917 This->moveInto(Val); 1918 Val.printPretty(Out, Info.Ctx, 1919 This->Designator.MostDerivedType); 1920 // FIXME: Add parens around Val if needed. 1921 Out << "->" << *Callee << '('; 1922 IsMemberCall = false; 1923 } 1924 1925 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1926 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1927 if (ArgIndex > (unsigned)IsMemberCall) 1928 Out << ", "; 1929 1930 const ParmVarDecl *Param = *I; 1931 APValue *V = Info.getParamSlot(Arguments, Param); 1932 if (V) 1933 V->printPretty(Out, Info.Ctx, Param->getType()); 1934 else 1935 Out << "<...>"; 1936 1937 if (ArgIndex == 0 && IsMemberCall) 1938 Out << "->" << *Callee << '('; 1939 } 1940 1941 Out << ')'; 1942 } 1943 1944 /// Evaluate an expression to see if it had side-effects, and discard its 1945 /// result. 1946 /// \return \c true if the caller should keep evaluating. 1947 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1948 assert(!E->isValueDependent()); 1949 APValue Scratch; 1950 if (!Evaluate(Scratch, Info, E)) 1951 // We don't need the value, but we might have skipped a side effect here. 1952 return Info.noteSideEffect(); 1953 return true; 1954 } 1955 1956 /// Should this call expression be treated as a string literal? 1957 static bool IsStringLiteralCall(const CallExpr *E) { 1958 unsigned Builtin = E->getBuiltinCallee(); 1959 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1960 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1961 } 1962 1963 static bool IsGlobalLValue(APValue::LValueBase B) { 1964 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1965 // constant expression of pointer type that evaluates to... 1966 1967 // ... a null pointer value, or a prvalue core constant expression of type 1968 // std::nullptr_t. 1969 if (!B) return true; 1970 1971 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1972 // ... the address of an object with static storage duration, 1973 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1974 return VD->hasGlobalStorage(); 1975 if (isa<TemplateParamObjectDecl>(D)) 1976 return true; 1977 // ... the address of a function, 1978 // ... the address of a GUID [MS extension], 1979 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1980 } 1981 1982 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1983 return true; 1984 1985 const Expr *E = B.get<const Expr*>(); 1986 switch (E->getStmtClass()) { 1987 default: 1988 return false; 1989 case Expr::CompoundLiteralExprClass: { 1990 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1991 return CLE->isFileScope() && CLE->isLValue(); 1992 } 1993 case Expr::MaterializeTemporaryExprClass: 1994 // A materialized temporary might have been lifetime-extended to static 1995 // storage duration. 1996 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1997 // A string literal has static storage duration. 1998 case Expr::StringLiteralClass: 1999 case Expr::PredefinedExprClass: 2000 case Expr::ObjCStringLiteralClass: 2001 case Expr::ObjCEncodeExprClass: 2002 return true; 2003 case Expr::ObjCBoxedExprClass: 2004 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2005 case Expr::CallExprClass: 2006 return IsStringLiteralCall(cast<CallExpr>(E)); 2007 // For GCC compatibility, &&label has static storage duration. 2008 case Expr::AddrLabelExprClass: 2009 return true; 2010 // A Block literal expression may be used as the initialization value for 2011 // Block variables at global or local static scope. 2012 case Expr::BlockExprClass: 2013 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2014 case Expr::ImplicitValueInitExprClass: 2015 // FIXME: 2016 // We can never form an lvalue with an implicit value initialization as its 2017 // base through expression evaluation, so these only appear in one case: the 2018 // implicit variable declaration we invent when checking whether a constexpr 2019 // constructor can produce a constant expression. We must assume that such 2020 // an expression might be a global lvalue. 2021 return true; 2022 } 2023 } 2024 2025 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2026 return LVal.Base.dyn_cast<const ValueDecl*>(); 2027 } 2028 2029 static bool IsLiteralLValue(const LValue &Value) { 2030 if (Value.getLValueCallIndex()) 2031 return false; 2032 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2033 return E && !isa<MaterializeTemporaryExpr>(E); 2034 } 2035 2036 static bool IsWeakLValue(const LValue &Value) { 2037 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2038 return Decl && Decl->isWeak(); 2039 } 2040 2041 static bool isZeroSized(const LValue &Value) { 2042 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2043 if (Decl && isa<VarDecl>(Decl)) { 2044 QualType Ty = Decl->getType(); 2045 if (Ty->isArrayType()) 2046 return Ty->isIncompleteType() || 2047 Decl->getASTContext().getTypeSize(Ty) == 0; 2048 } 2049 return false; 2050 } 2051 2052 static bool HasSameBase(const LValue &A, const LValue &B) { 2053 if (!A.getLValueBase()) 2054 return !B.getLValueBase(); 2055 if (!B.getLValueBase()) 2056 return false; 2057 2058 if (A.getLValueBase().getOpaqueValue() != 2059 B.getLValueBase().getOpaqueValue()) 2060 return false; 2061 2062 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2063 A.getLValueVersion() == B.getLValueVersion(); 2064 } 2065 2066 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2067 assert(Base && "no location for a null lvalue"); 2068 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2069 2070 // For a parameter, find the corresponding call stack frame (if it still 2071 // exists), and point at the parameter of the function definition we actually 2072 // invoked. 2073 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2074 unsigned Idx = PVD->getFunctionScopeIndex(); 2075 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2076 if (F->Arguments.CallIndex == Base.getCallIndex() && 2077 F->Arguments.Version == Base.getVersion() && F->Callee && 2078 Idx < F->Callee->getNumParams()) { 2079 VD = F->Callee->getParamDecl(Idx); 2080 break; 2081 } 2082 } 2083 } 2084 2085 if (VD) 2086 Info.Note(VD->getLocation(), diag::note_declared_at); 2087 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2088 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2089 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2090 // FIXME: Produce a note for dangling pointers too. 2091 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2092 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2093 diag::note_constexpr_dynamic_alloc_here); 2094 } 2095 // We have no information to show for a typeid(T) object. 2096 } 2097 2098 enum class CheckEvaluationResultKind { 2099 ConstantExpression, 2100 FullyInitialized, 2101 }; 2102 2103 /// Materialized temporaries that we've already checked to determine if they're 2104 /// initializsed by a constant expression. 2105 using CheckedTemporaries = 2106 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2107 2108 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2109 EvalInfo &Info, SourceLocation DiagLoc, 2110 QualType Type, const APValue &Value, 2111 ConstantExprKind Kind, 2112 SourceLocation SubobjectLoc, 2113 CheckedTemporaries &CheckedTemps); 2114 2115 /// Check that this reference or pointer core constant expression is a valid 2116 /// value for an address or reference constant expression. Return true if we 2117 /// can fold this expression, whether or not it's a constant expression. 2118 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2119 QualType Type, const LValue &LVal, 2120 ConstantExprKind Kind, 2121 CheckedTemporaries &CheckedTemps) { 2122 bool IsReferenceType = Type->isReferenceType(); 2123 2124 APValue::LValueBase Base = LVal.getLValueBase(); 2125 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2126 2127 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2128 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2129 2130 // Additional restrictions apply in a template argument. We only enforce the 2131 // C++20 restrictions here; additional syntactic and semantic restrictions 2132 // are applied elsewhere. 2133 if (isTemplateArgument(Kind)) { 2134 int InvalidBaseKind = -1; 2135 StringRef Ident; 2136 if (Base.is<TypeInfoLValue>()) 2137 InvalidBaseKind = 0; 2138 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2139 InvalidBaseKind = 1; 2140 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2141 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2142 InvalidBaseKind = 2; 2143 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2144 InvalidBaseKind = 3; 2145 Ident = PE->getIdentKindName(); 2146 } 2147 2148 if (InvalidBaseKind != -1) { 2149 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2150 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2151 << Ident; 2152 return false; 2153 } 2154 } 2155 2156 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2157 if (FD->isConsteval()) { 2158 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2159 << !Type->isAnyPointerType(); 2160 Info.Note(FD->getLocation(), diag::note_declared_at); 2161 return false; 2162 } 2163 } 2164 2165 // Check that the object is a global. Note that the fake 'this' object we 2166 // manufacture when checking potential constant expressions is conservatively 2167 // assumed to be global here. 2168 if (!IsGlobalLValue(Base)) { 2169 if (Info.getLangOpts().CPlusPlus11) { 2170 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2171 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2172 << IsReferenceType << !Designator.Entries.empty() 2173 << !!VD << VD; 2174 2175 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2176 if (VarD && VarD->isConstexpr()) { 2177 // Non-static local constexpr variables have unintuitive semantics: 2178 // constexpr int a = 1; 2179 // constexpr const int *p = &a; 2180 // ... is invalid because the address of 'a' is not constant. Suggest 2181 // adding a 'static' in this case. 2182 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2183 << VarD 2184 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2185 } else { 2186 NoteLValueLocation(Info, Base); 2187 } 2188 } else { 2189 Info.FFDiag(Loc); 2190 } 2191 // Don't allow references to temporaries to escape. 2192 return false; 2193 } 2194 assert((Info.checkingPotentialConstantExpression() || 2195 LVal.getLValueCallIndex() == 0) && 2196 "have call index for global lvalue"); 2197 2198 if (Base.is<DynamicAllocLValue>()) { 2199 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2200 << IsReferenceType << !Designator.Entries.empty(); 2201 NoteLValueLocation(Info, Base); 2202 return false; 2203 } 2204 2205 if (BaseVD) { 2206 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2207 // Check if this is a thread-local variable. 2208 if (Var->getTLSKind()) 2209 // FIXME: Diagnostic! 2210 return false; 2211 2212 // A dllimport variable never acts like a constant, unless we're 2213 // evaluating a value for use only in name mangling. 2214 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2215 // FIXME: Diagnostic! 2216 return false; 2217 } 2218 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2219 // __declspec(dllimport) must be handled very carefully: 2220 // We must never initialize an expression with the thunk in C++. 2221 // Doing otherwise would allow the same id-expression to yield 2222 // different addresses for the same function in different translation 2223 // units. However, this means that we must dynamically initialize the 2224 // expression with the contents of the import address table at runtime. 2225 // 2226 // The C language has no notion of ODR; furthermore, it has no notion of 2227 // dynamic initialization. This means that we are permitted to 2228 // perform initialization with the address of the thunk. 2229 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2230 FD->hasAttr<DLLImportAttr>()) 2231 // FIXME: Diagnostic! 2232 return false; 2233 } 2234 } else if (const auto *MTE = 2235 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2236 if (CheckedTemps.insert(MTE).second) { 2237 QualType TempType = getType(Base); 2238 if (TempType.isDestructedType()) { 2239 Info.FFDiag(MTE->getExprLoc(), 2240 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2241 << TempType; 2242 return false; 2243 } 2244 2245 APValue *V = MTE->getOrCreateValue(false); 2246 assert(V && "evasluation result refers to uninitialised temporary"); 2247 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2248 Info, MTE->getExprLoc(), TempType, *V, 2249 Kind, SourceLocation(), CheckedTemps)) 2250 return false; 2251 } 2252 } 2253 2254 // Allow address constant expressions to be past-the-end pointers. This is 2255 // an extension: the standard requires them to point to an object. 2256 if (!IsReferenceType) 2257 return true; 2258 2259 // A reference constant expression must refer to an object. 2260 if (!Base) { 2261 // FIXME: diagnostic 2262 Info.CCEDiag(Loc); 2263 return true; 2264 } 2265 2266 // Does this refer one past the end of some object? 2267 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2268 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2269 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2270 NoteLValueLocation(Info, Base); 2271 } 2272 2273 return true; 2274 } 2275 2276 /// Member pointers are constant expressions unless they point to a 2277 /// non-virtual dllimport member function. 2278 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2279 SourceLocation Loc, 2280 QualType Type, 2281 const APValue &Value, 2282 ConstantExprKind Kind) { 2283 const ValueDecl *Member = Value.getMemberPointerDecl(); 2284 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2285 if (!FD) 2286 return true; 2287 if (FD->isConsteval()) { 2288 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2289 Info.Note(FD->getLocation(), diag::note_declared_at); 2290 return false; 2291 } 2292 return isForManglingOnly(Kind) || FD->isVirtual() || 2293 !FD->hasAttr<DLLImportAttr>(); 2294 } 2295 2296 /// Check that this core constant expression is of literal type, and if not, 2297 /// produce an appropriate diagnostic. 2298 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2299 const LValue *This = nullptr) { 2300 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2301 return true; 2302 2303 // C++1y: A constant initializer for an object o [...] may also invoke 2304 // constexpr constructors for o and its subobjects even if those objects 2305 // are of non-literal class types. 2306 // 2307 // C++11 missed this detail for aggregates, so classes like this: 2308 // struct foo_t { union { int i; volatile int j; } u; }; 2309 // are not (obviously) initializable like so: 2310 // __attribute__((__require_constant_initialization__)) 2311 // static const foo_t x = {{0}}; 2312 // because "i" is a subobject with non-literal initialization (due to the 2313 // volatile member of the union). See: 2314 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2315 // Therefore, we use the C++1y behavior. 2316 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2317 return true; 2318 2319 // Prvalue constant expressions must be of literal types. 2320 if (Info.getLangOpts().CPlusPlus11) 2321 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2322 << E->getType(); 2323 else 2324 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2325 return false; 2326 } 2327 2328 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2329 EvalInfo &Info, SourceLocation DiagLoc, 2330 QualType Type, const APValue &Value, 2331 ConstantExprKind Kind, 2332 SourceLocation SubobjectLoc, 2333 CheckedTemporaries &CheckedTemps) { 2334 if (!Value.hasValue()) { 2335 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2336 << true << Type; 2337 if (SubobjectLoc.isValid()) 2338 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2339 return false; 2340 } 2341 2342 // We allow _Atomic(T) to be initialized from anything that T can be 2343 // initialized from. 2344 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2345 Type = AT->getValueType(); 2346 2347 // Core issue 1454: For a literal constant expression of array or class type, 2348 // each subobject of its value shall have been initialized by a constant 2349 // expression. 2350 if (Value.isArray()) { 2351 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2352 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2353 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2354 Value.getArrayInitializedElt(I), Kind, 2355 SubobjectLoc, CheckedTemps)) 2356 return false; 2357 } 2358 if (!Value.hasArrayFiller()) 2359 return true; 2360 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2361 Value.getArrayFiller(), Kind, SubobjectLoc, 2362 CheckedTemps); 2363 } 2364 if (Value.isUnion() && Value.getUnionField()) { 2365 return CheckEvaluationResult( 2366 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2367 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2368 CheckedTemps); 2369 } 2370 if (Value.isStruct()) { 2371 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2372 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2373 unsigned BaseIndex = 0; 2374 for (const CXXBaseSpecifier &BS : CD->bases()) { 2375 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2376 Value.getStructBase(BaseIndex), Kind, 2377 BS.getBeginLoc(), CheckedTemps)) 2378 return false; 2379 ++BaseIndex; 2380 } 2381 } 2382 for (const auto *I : RD->fields()) { 2383 if (I->isUnnamedBitfield()) 2384 continue; 2385 2386 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2387 Value.getStructField(I->getFieldIndex()), 2388 Kind, I->getLocation(), CheckedTemps)) 2389 return false; 2390 } 2391 } 2392 2393 if (Value.isLValue() && 2394 CERK == CheckEvaluationResultKind::ConstantExpression) { 2395 LValue LVal; 2396 LVal.setFrom(Info.Ctx, Value); 2397 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2398 CheckedTemps); 2399 } 2400 2401 if (Value.isMemberPointer() && 2402 CERK == CheckEvaluationResultKind::ConstantExpression) 2403 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2404 2405 // Everything else is fine. 2406 return true; 2407 } 2408 2409 /// Check that this core constant expression value is a valid value for a 2410 /// constant expression. If not, report an appropriate diagnostic. Does not 2411 /// check that the expression is of literal type. 2412 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2413 QualType Type, const APValue &Value, 2414 ConstantExprKind Kind) { 2415 // Nothing to check for a constant expression of type 'cv void'. 2416 if (Type->isVoidType()) 2417 return true; 2418 2419 CheckedTemporaries CheckedTemps; 2420 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2421 Info, DiagLoc, Type, Value, Kind, 2422 SourceLocation(), CheckedTemps); 2423 } 2424 2425 /// Check that this evaluated value is fully-initialized and can be loaded by 2426 /// an lvalue-to-rvalue conversion. 2427 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2428 QualType Type, const APValue &Value) { 2429 CheckedTemporaries CheckedTemps; 2430 return CheckEvaluationResult( 2431 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2432 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2433 } 2434 2435 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2436 /// "the allocated storage is deallocated within the evaluation". 2437 static bool CheckMemoryLeaks(EvalInfo &Info) { 2438 if (!Info.HeapAllocs.empty()) { 2439 // We can still fold to a constant despite a compile-time memory leak, 2440 // so long as the heap allocation isn't referenced in the result (we check 2441 // that in CheckConstantExpression). 2442 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2443 diag::note_constexpr_memory_leak) 2444 << unsigned(Info.HeapAllocs.size() - 1); 2445 } 2446 return true; 2447 } 2448 2449 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2450 // A null base expression indicates a null pointer. These are always 2451 // evaluatable, and they are false unless the offset is zero. 2452 if (!Value.getLValueBase()) { 2453 Result = !Value.getLValueOffset().isZero(); 2454 return true; 2455 } 2456 2457 // We have a non-null base. These are generally known to be true, but if it's 2458 // a weak declaration it can be null at runtime. 2459 Result = true; 2460 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2461 return !Decl || !Decl->isWeak(); 2462 } 2463 2464 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2465 switch (Val.getKind()) { 2466 case APValue::None: 2467 case APValue::Indeterminate: 2468 return false; 2469 case APValue::Int: 2470 Result = Val.getInt().getBoolValue(); 2471 return true; 2472 case APValue::FixedPoint: 2473 Result = Val.getFixedPoint().getBoolValue(); 2474 return true; 2475 case APValue::Float: 2476 Result = !Val.getFloat().isZero(); 2477 return true; 2478 case APValue::ComplexInt: 2479 Result = Val.getComplexIntReal().getBoolValue() || 2480 Val.getComplexIntImag().getBoolValue(); 2481 return true; 2482 case APValue::ComplexFloat: 2483 Result = !Val.getComplexFloatReal().isZero() || 2484 !Val.getComplexFloatImag().isZero(); 2485 return true; 2486 case APValue::LValue: 2487 return EvalPointerValueAsBool(Val, Result); 2488 case APValue::MemberPointer: 2489 Result = Val.getMemberPointerDecl(); 2490 return true; 2491 case APValue::Vector: 2492 case APValue::Array: 2493 case APValue::Struct: 2494 case APValue::Union: 2495 case APValue::AddrLabelDiff: 2496 return false; 2497 } 2498 2499 llvm_unreachable("unknown APValue kind"); 2500 } 2501 2502 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2503 EvalInfo &Info) { 2504 assert(!E->isValueDependent()); 2505 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2506 APValue Val; 2507 if (!Evaluate(Val, Info, E)) 2508 return false; 2509 return HandleConversionToBool(Val, Result); 2510 } 2511 2512 template<typename T> 2513 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2514 const T &SrcValue, QualType DestType) { 2515 Info.CCEDiag(E, diag::note_constexpr_overflow) 2516 << SrcValue << DestType; 2517 return Info.noteUndefinedBehavior(); 2518 } 2519 2520 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2521 QualType SrcType, const APFloat &Value, 2522 QualType DestType, APSInt &Result) { 2523 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2524 // Determine whether we are converting to unsigned or signed. 2525 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2526 2527 Result = APSInt(DestWidth, !DestSigned); 2528 bool ignored; 2529 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2530 & APFloat::opInvalidOp) 2531 return HandleOverflow(Info, E, Value, DestType); 2532 return true; 2533 } 2534 2535 /// Get rounding mode used for evaluation of the specified expression. 2536 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2537 /// dynamic. 2538 /// If rounding mode is unknown at compile time, still try to evaluate the 2539 /// expression. If the result is exact, it does not depend on rounding mode. 2540 /// So return "tonearest" mode instead of "dynamic". 2541 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2542 bool &DynamicRM) { 2543 llvm::RoundingMode RM = 2544 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2545 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2546 if (DynamicRM) 2547 RM = llvm::RoundingMode::NearestTiesToEven; 2548 return RM; 2549 } 2550 2551 /// Check if the given evaluation result is allowed for constant evaluation. 2552 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2553 APFloat::opStatus St) { 2554 // In a constant context, assume that any dynamic rounding mode or FP 2555 // exception state matches the default floating-point environment. 2556 if (Info.InConstantContext) 2557 return true; 2558 2559 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2560 if ((St & APFloat::opInexact) && 2561 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2562 // Inexact result means that it depends on rounding mode. If the requested 2563 // mode is dynamic, the evaluation cannot be made in compile time. 2564 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2565 return false; 2566 } 2567 2568 if ((St != APFloat::opOK) && 2569 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2570 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2571 FPO.getAllowFEnvAccess())) { 2572 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2573 return false; 2574 } 2575 2576 if ((St & APFloat::opStatus::opInvalidOp) && 2577 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2578 // There is no usefully definable result. 2579 Info.FFDiag(E); 2580 return false; 2581 } 2582 2583 // FIXME: if: 2584 // - evaluation triggered other FP exception, and 2585 // - exception mode is not "ignore", and 2586 // - the expression being evaluated is not a part of global variable 2587 // initializer, 2588 // the evaluation probably need to be rejected. 2589 return true; 2590 } 2591 2592 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2593 QualType SrcType, QualType DestType, 2594 APFloat &Result) { 2595 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2596 bool DynamicRM; 2597 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2598 APFloat::opStatus St; 2599 APFloat Value = Result; 2600 bool ignored; 2601 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2602 return checkFloatingPointResult(Info, E, St); 2603 } 2604 2605 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2606 QualType DestType, QualType SrcType, 2607 const APSInt &Value) { 2608 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2609 // Figure out if this is a truncate, extend or noop cast. 2610 // If the input is signed, do a sign extend, noop, or truncate. 2611 APSInt Result = Value.extOrTrunc(DestWidth); 2612 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2613 if (DestType->isBooleanType()) 2614 Result = Value.getBoolValue(); 2615 return Result; 2616 } 2617 2618 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2619 const FPOptions FPO, 2620 QualType SrcType, const APSInt &Value, 2621 QualType DestType, APFloat &Result) { 2622 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2623 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2624 APFloat::rmNearestTiesToEven); 2625 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2626 FPO.isFPConstrained()) { 2627 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2628 return false; 2629 } 2630 return true; 2631 } 2632 2633 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2634 APValue &Value, const FieldDecl *FD) { 2635 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2636 2637 if (!Value.isInt()) { 2638 // Trying to store a pointer-cast-to-integer into a bitfield. 2639 // FIXME: In this case, we should provide the diagnostic for casting 2640 // a pointer to an integer. 2641 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2642 Info.FFDiag(E); 2643 return false; 2644 } 2645 2646 APSInt &Int = Value.getInt(); 2647 unsigned OldBitWidth = Int.getBitWidth(); 2648 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2649 if (NewBitWidth < OldBitWidth) 2650 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2651 return true; 2652 } 2653 2654 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2655 llvm::APInt &Res) { 2656 APValue SVal; 2657 if (!Evaluate(SVal, Info, E)) 2658 return false; 2659 if (SVal.isInt()) { 2660 Res = SVal.getInt(); 2661 return true; 2662 } 2663 if (SVal.isFloat()) { 2664 Res = SVal.getFloat().bitcastToAPInt(); 2665 return true; 2666 } 2667 if (SVal.isVector()) { 2668 QualType VecTy = E->getType(); 2669 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2670 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2671 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2672 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2673 Res = llvm::APInt::getNullValue(VecSize); 2674 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2675 APValue &Elt = SVal.getVectorElt(i); 2676 llvm::APInt EltAsInt; 2677 if (Elt.isInt()) { 2678 EltAsInt = Elt.getInt(); 2679 } else if (Elt.isFloat()) { 2680 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2681 } else { 2682 // Don't try to handle vectors of anything other than int or float 2683 // (not sure if it's possible to hit this case). 2684 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2685 return false; 2686 } 2687 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2688 if (BigEndian) 2689 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2690 else 2691 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2692 } 2693 return true; 2694 } 2695 // Give up if the input isn't an int, float, or vector. For example, we 2696 // reject "(v4i16)(intptr_t)&a". 2697 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2698 return false; 2699 } 2700 2701 /// Perform the given integer operation, which is known to need at most BitWidth 2702 /// bits, and check for overflow in the original type (if that type was not an 2703 /// unsigned type). 2704 template<typename Operation> 2705 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2706 const APSInt &LHS, const APSInt &RHS, 2707 unsigned BitWidth, Operation Op, 2708 APSInt &Result) { 2709 if (LHS.isUnsigned()) { 2710 Result = Op(LHS, RHS); 2711 return true; 2712 } 2713 2714 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2715 Result = Value.trunc(LHS.getBitWidth()); 2716 if (Result.extend(BitWidth) != Value) { 2717 if (Info.checkingForUndefinedBehavior()) 2718 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2719 diag::warn_integer_constant_overflow) 2720 << Result.toString(10) << E->getType(); 2721 return HandleOverflow(Info, E, Value, E->getType()); 2722 } 2723 return true; 2724 } 2725 2726 /// Perform the given binary integer operation. 2727 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2728 BinaryOperatorKind Opcode, APSInt RHS, 2729 APSInt &Result) { 2730 switch (Opcode) { 2731 default: 2732 Info.FFDiag(E); 2733 return false; 2734 case BO_Mul: 2735 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2736 std::multiplies<APSInt>(), Result); 2737 case BO_Add: 2738 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2739 std::plus<APSInt>(), Result); 2740 case BO_Sub: 2741 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2742 std::minus<APSInt>(), Result); 2743 case BO_And: Result = LHS & RHS; return true; 2744 case BO_Xor: Result = LHS ^ RHS; return true; 2745 case BO_Or: Result = LHS | RHS; return true; 2746 case BO_Div: 2747 case BO_Rem: 2748 if (RHS == 0) { 2749 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2750 return false; 2751 } 2752 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2753 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2754 // this operation and gives the two's complement result. 2755 if (RHS.isNegative() && RHS.isAllOnesValue() && 2756 LHS.isSigned() && LHS.isMinSignedValue()) 2757 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2758 E->getType()); 2759 return true; 2760 case BO_Shl: { 2761 if (Info.getLangOpts().OpenCL) 2762 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2763 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2764 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2765 RHS.isUnsigned()); 2766 else if (RHS.isSigned() && RHS.isNegative()) { 2767 // During constant-folding, a negative shift is an opposite shift. Such 2768 // a shift is not a constant expression. 2769 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2770 RHS = -RHS; 2771 goto shift_right; 2772 } 2773 shift_left: 2774 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2775 // the shifted type. 2776 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2777 if (SA != RHS) { 2778 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2779 << RHS << E->getType() << LHS.getBitWidth(); 2780 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2781 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2782 // operand, and must not overflow the corresponding unsigned type. 2783 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2784 // E1 x 2^E2 module 2^N. 2785 if (LHS.isNegative()) 2786 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2787 else if (LHS.countLeadingZeros() < SA) 2788 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2789 } 2790 Result = LHS << SA; 2791 return true; 2792 } 2793 case BO_Shr: { 2794 if (Info.getLangOpts().OpenCL) 2795 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2796 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2797 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2798 RHS.isUnsigned()); 2799 else if (RHS.isSigned() && RHS.isNegative()) { 2800 // During constant-folding, a negative shift is an opposite shift. Such a 2801 // shift is not a constant expression. 2802 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2803 RHS = -RHS; 2804 goto shift_left; 2805 } 2806 shift_right: 2807 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2808 // shifted type. 2809 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2810 if (SA != RHS) 2811 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2812 << RHS << E->getType() << LHS.getBitWidth(); 2813 Result = LHS >> SA; 2814 return true; 2815 } 2816 2817 case BO_LT: Result = LHS < RHS; return true; 2818 case BO_GT: Result = LHS > RHS; return true; 2819 case BO_LE: Result = LHS <= RHS; return true; 2820 case BO_GE: Result = LHS >= RHS; return true; 2821 case BO_EQ: Result = LHS == RHS; return true; 2822 case BO_NE: Result = LHS != RHS; return true; 2823 case BO_Cmp: 2824 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2825 } 2826 } 2827 2828 /// Perform the given binary floating-point operation, in-place, on LHS. 2829 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2830 APFloat &LHS, BinaryOperatorKind Opcode, 2831 const APFloat &RHS) { 2832 bool DynamicRM; 2833 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2834 APFloat::opStatus St; 2835 switch (Opcode) { 2836 default: 2837 Info.FFDiag(E); 2838 return false; 2839 case BO_Mul: 2840 St = LHS.multiply(RHS, RM); 2841 break; 2842 case BO_Add: 2843 St = LHS.add(RHS, RM); 2844 break; 2845 case BO_Sub: 2846 St = LHS.subtract(RHS, RM); 2847 break; 2848 case BO_Div: 2849 // [expr.mul]p4: 2850 // If the second operand of / or % is zero the behavior is undefined. 2851 if (RHS.isZero()) 2852 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2853 St = LHS.divide(RHS, RM); 2854 break; 2855 } 2856 2857 // [expr.pre]p4: 2858 // If during the evaluation of an expression, the result is not 2859 // mathematically defined [...], the behavior is undefined. 2860 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2861 if (LHS.isNaN()) { 2862 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2863 return Info.noteUndefinedBehavior(); 2864 } 2865 2866 return checkFloatingPointResult(Info, E, St); 2867 } 2868 2869 static bool handleLogicalOpForVector(const APInt &LHSValue, 2870 BinaryOperatorKind Opcode, 2871 const APInt &RHSValue, APInt &Result) { 2872 bool LHS = (LHSValue != 0); 2873 bool RHS = (RHSValue != 0); 2874 2875 if (Opcode == BO_LAnd) 2876 Result = LHS && RHS; 2877 else 2878 Result = LHS || RHS; 2879 return true; 2880 } 2881 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2882 BinaryOperatorKind Opcode, 2883 const APFloat &RHSValue, APInt &Result) { 2884 bool LHS = !LHSValue.isZero(); 2885 bool RHS = !RHSValue.isZero(); 2886 2887 if (Opcode == BO_LAnd) 2888 Result = LHS && RHS; 2889 else 2890 Result = LHS || RHS; 2891 return true; 2892 } 2893 2894 static bool handleLogicalOpForVector(const APValue &LHSValue, 2895 BinaryOperatorKind Opcode, 2896 const APValue &RHSValue, APInt &Result) { 2897 // The result is always an int type, however operands match the first. 2898 if (LHSValue.getKind() == APValue::Int) 2899 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2900 RHSValue.getInt(), Result); 2901 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2902 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2903 RHSValue.getFloat(), Result); 2904 } 2905 2906 template <typename APTy> 2907 static bool 2908 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2909 const APTy &RHSValue, APInt &Result) { 2910 switch (Opcode) { 2911 default: 2912 llvm_unreachable("unsupported binary operator"); 2913 case BO_EQ: 2914 Result = (LHSValue == RHSValue); 2915 break; 2916 case BO_NE: 2917 Result = (LHSValue != RHSValue); 2918 break; 2919 case BO_LT: 2920 Result = (LHSValue < RHSValue); 2921 break; 2922 case BO_GT: 2923 Result = (LHSValue > RHSValue); 2924 break; 2925 case BO_LE: 2926 Result = (LHSValue <= RHSValue); 2927 break; 2928 case BO_GE: 2929 Result = (LHSValue >= RHSValue); 2930 break; 2931 } 2932 2933 return true; 2934 } 2935 2936 static bool handleCompareOpForVector(const APValue &LHSValue, 2937 BinaryOperatorKind Opcode, 2938 const APValue &RHSValue, APInt &Result) { 2939 // The result is always an int type, however operands match the first. 2940 if (LHSValue.getKind() == APValue::Int) 2941 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2942 RHSValue.getInt(), Result); 2943 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2944 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2945 RHSValue.getFloat(), Result); 2946 } 2947 2948 // Perform binary operations for vector types, in place on the LHS. 2949 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2950 BinaryOperatorKind Opcode, 2951 APValue &LHSValue, 2952 const APValue &RHSValue) { 2953 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2954 "Operation not supported on vector types"); 2955 2956 const auto *VT = E->getType()->castAs<VectorType>(); 2957 unsigned NumElements = VT->getNumElements(); 2958 QualType EltTy = VT->getElementType(); 2959 2960 // In the cases (typically C as I've observed) where we aren't evaluating 2961 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2962 // just give up. 2963 if (!LHSValue.isVector()) { 2964 assert(LHSValue.isLValue() && 2965 "A vector result that isn't a vector OR uncalculated LValue"); 2966 Info.FFDiag(E); 2967 return false; 2968 } 2969 2970 assert(LHSValue.getVectorLength() == NumElements && 2971 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2972 2973 SmallVector<APValue, 4> ResultElements; 2974 2975 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2976 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2977 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2978 2979 if (EltTy->isIntegerType()) { 2980 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2981 EltTy->isUnsignedIntegerType()}; 2982 bool Success = true; 2983 2984 if (BinaryOperator::isLogicalOp(Opcode)) 2985 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2986 else if (BinaryOperator::isComparisonOp(Opcode)) 2987 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2988 else 2989 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2990 RHSElt.getInt(), EltResult); 2991 2992 if (!Success) { 2993 Info.FFDiag(E); 2994 return false; 2995 } 2996 ResultElements.emplace_back(EltResult); 2997 2998 } else if (EltTy->isFloatingType()) { 2999 assert(LHSElt.getKind() == APValue::Float && 3000 RHSElt.getKind() == APValue::Float && 3001 "Mismatched LHS/RHS/Result Type"); 3002 APFloat LHSFloat = LHSElt.getFloat(); 3003 3004 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3005 RHSElt.getFloat())) { 3006 Info.FFDiag(E); 3007 return false; 3008 } 3009 3010 ResultElements.emplace_back(LHSFloat); 3011 } 3012 } 3013 3014 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3015 return true; 3016 } 3017 3018 /// Cast an lvalue referring to a base subobject to a derived class, by 3019 /// truncating the lvalue's path to the given length. 3020 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3021 const RecordDecl *TruncatedType, 3022 unsigned TruncatedElements) { 3023 SubobjectDesignator &D = Result.Designator; 3024 3025 // Check we actually point to a derived class object. 3026 if (TruncatedElements == D.Entries.size()) 3027 return true; 3028 assert(TruncatedElements >= D.MostDerivedPathLength && 3029 "not casting to a derived class"); 3030 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3031 return false; 3032 3033 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3034 const RecordDecl *RD = TruncatedType; 3035 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3036 if (RD->isInvalidDecl()) return false; 3037 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3038 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3039 if (isVirtualBaseClass(D.Entries[I])) 3040 Result.Offset -= Layout.getVBaseClassOffset(Base); 3041 else 3042 Result.Offset -= Layout.getBaseClassOffset(Base); 3043 RD = Base; 3044 } 3045 D.Entries.resize(TruncatedElements); 3046 return true; 3047 } 3048 3049 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3050 const CXXRecordDecl *Derived, 3051 const CXXRecordDecl *Base, 3052 const ASTRecordLayout *RL = nullptr) { 3053 if (!RL) { 3054 if (Derived->isInvalidDecl()) return false; 3055 RL = &Info.Ctx.getASTRecordLayout(Derived); 3056 } 3057 3058 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3059 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3060 return true; 3061 } 3062 3063 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3064 const CXXRecordDecl *DerivedDecl, 3065 const CXXBaseSpecifier *Base) { 3066 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3067 3068 if (!Base->isVirtual()) 3069 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3070 3071 SubobjectDesignator &D = Obj.Designator; 3072 if (D.Invalid) 3073 return false; 3074 3075 // Extract most-derived object and corresponding type. 3076 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3077 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3078 return false; 3079 3080 // Find the virtual base class. 3081 if (DerivedDecl->isInvalidDecl()) return false; 3082 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3083 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3084 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3085 return true; 3086 } 3087 3088 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3089 QualType Type, LValue &Result) { 3090 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3091 PathE = E->path_end(); 3092 PathI != PathE; ++PathI) { 3093 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3094 *PathI)) 3095 return false; 3096 Type = (*PathI)->getType(); 3097 } 3098 return true; 3099 } 3100 3101 /// Cast an lvalue referring to a derived class to a known base subobject. 3102 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3103 const CXXRecordDecl *DerivedRD, 3104 const CXXRecordDecl *BaseRD) { 3105 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3106 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3107 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3108 llvm_unreachable("Class must be derived from the passed in base class!"); 3109 3110 for (CXXBasePathElement &Elem : Paths.front()) 3111 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3112 return false; 3113 return true; 3114 } 3115 3116 /// Update LVal to refer to the given field, which must be a member of the type 3117 /// currently described by LVal. 3118 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3119 const FieldDecl *FD, 3120 const ASTRecordLayout *RL = nullptr) { 3121 if (!RL) { 3122 if (FD->getParent()->isInvalidDecl()) return false; 3123 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3124 } 3125 3126 unsigned I = FD->getFieldIndex(); 3127 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3128 LVal.addDecl(Info, E, FD); 3129 return true; 3130 } 3131 3132 /// Update LVal to refer to the given indirect field. 3133 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3134 LValue &LVal, 3135 const IndirectFieldDecl *IFD) { 3136 for (const auto *C : IFD->chain()) 3137 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3138 return false; 3139 return true; 3140 } 3141 3142 /// Get the size of the given type in char units. 3143 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3144 QualType Type, CharUnits &Size) { 3145 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3146 // extension. 3147 if (Type->isVoidType() || Type->isFunctionType()) { 3148 Size = CharUnits::One(); 3149 return true; 3150 } 3151 3152 if (Type->isDependentType()) { 3153 Info.FFDiag(Loc); 3154 return false; 3155 } 3156 3157 if (!Type->isConstantSizeType()) { 3158 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3159 // FIXME: Better diagnostic. 3160 Info.FFDiag(Loc); 3161 return false; 3162 } 3163 3164 Size = Info.Ctx.getTypeSizeInChars(Type); 3165 return true; 3166 } 3167 3168 /// Update a pointer value to model pointer arithmetic. 3169 /// \param Info - Information about the ongoing evaluation. 3170 /// \param E - The expression being evaluated, for diagnostic purposes. 3171 /// \param LVal - The pointer value to be updated. 3172 /// \param EltTy - The pointee type represented by LVal. 3173 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3174 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3175 LValue &LVal, QualType EltTy, 3176 APSInt Adjustment) { 3177 CharUnits SizeOfPointee; 3178 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3179 return false; 3180 3181 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3182 return true; 3183 } 3184 3185 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3186 LValue &LVal, QualType EltTy, 3187 int64_t Adjustment) { 3188 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3189 APSInt::get(Adjustment)); 3190 } 3191 3192 /// Update an lvalue to refer to a component of a complex number. 3193 /// \param Info - Information about the ongoing evaluation. 3194 /// \param LVal - The lvalue to be updated. 3195 /// \param EltTy - The complex number's component type. 3196 /// \param Imag - False for the real component, true for the imaginary. 3197 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3198 LValue &LVal, QualType EltTy, 3199 bool Imag) { 3200 if (Imag) { 3201 CharUnits SizeOfComponent; 3202 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3203 return false; 3204 LVal.Offset += SizeOfComponent; 3205 } 3206 LVal.addComplex(Info, E, EltTy, Imag); 3207 return true; 3208 } 3209 3210 /// Try to evaluate the initializer for a variable declaration. 3211 /// 3212 /// \param Info Information about the ongoing evaluation. 3213 /// \param E An expression to be used when printing diagnostics. 3214 /// \param VD The variable whose initializer should be obtained. 3215 /// \param Version The version of the variable within the frame. 3216 /// \param Frame The frame in which the variable was created. Must be null 3217 /// if this variable is not local to the evaluation. 3218 /// \param Result Filled in with a pointer to the value of the variable. 3219 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3220 const VarDecl *VD, CallStackFrame *Frame, 3221 unsigned Version, APValue *&Result) { 3222 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3223 3224 // If this is a local variable, dig out its value. 3225 if (Frame) { 3226 Result = Frame->getTemporary(VD, Version); 3227 if (Result) 3228 return true; 3229 3230 if (!isa<ParmVarDecl>(VD)) { 3231 // Assume variables referenced within a lambda's call operator that were 3232 // not declared within the call operator are captures and during checking 3233 // of a potential constant expression, assume they are unknown constant 3234 // expressions. 3235 assert(isLambdaCallOperator(Frame->Callee) && 3236 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3237 "missing value for local variable"); 3238 if (Info.checkingPotentialConstantExpression()) 3239 return false; 3240 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3241 // still reachable at all? 3242 Info.FFDiag(E->getBeginLoc(), 3243 diag::note_unimplemented_constexpr_lambda_feature_ast) 3244 << "captures not currently allowed"; 3245 return false; 3246 } 3247 } 3248 3249 // If we're currently evaluating the initializer of this declaration, use that 3250 // in-flight value. 3251 if (Info.EvaluatingDecl == Base) { 3252 Result = Info.EvaluatingDeclValue; 3253 return true; 3254 } 3255 3256 if (isa<ParmVarDecl>(VD)) { 3257 // Assume parameters of a potential constant expression are usable in 3258 // constant expressions. 3259 if (!Info.checkingPotentialConstantExpression() || 3260 !Info.CurrentCall->Callee || 3261 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3262 if (Info.getLangOpts().CPlusPlus11) { 3263 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3264 << VD; 3265 NoteLValueLocation(Info, Base); 3266 } else { 3267 Info.FFDiag(E); 3268 } 3269 } 3270 return false; 3271 } 3272 3273 // Dig out the initializer, and use the declaration which it's attached to. 3274 // FIXME: We should eventually check whether the variable has a reachable 3275 // initializing declaration. 3276 const Expr *Init = VD->getAnyInitializer(VD); 3277 if (!Init) { 3278 // Don't diagnose during potential constant expression checking; an 3279 // initializer might be added later. 3280 if (!Info.checkingPotentialConstantExpression()) { 3281 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3282 << VD; 3283 NoteLValueLocation(Info, Base); 3284 } 3285 return false; 3286 } 3287 3288 if (Init->isValueDependent()) { 3289 // The DeclRefExpr is not value-dependent, but the variable it refers to 3290 // has a value-dependent initializer. This should only happen in 3291 // constant-folding cases, where the variable is not actually of a suitable 3292 // type for use in a constant expression (otherwise the DeclRefExpr would 3293 // have been value-dependent too), so diagnose that. 3294 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3295 if (!Info.checkingPotentialConstantExpression()) { 3296 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3297 ? diag::note_constexpr_ltor_non_constexpr 3298 : diag::note_constexpr_ltor_non_integral, 1) 3299 << VD << VD->getType(); 3300 NoteLValueLocation(Info, Base); 3301 } 3302 return false; 3303 } 3304 3305 // Check that we can fold the initializer. In C++, we will have already done 3306 // this in the cases where it matters for conformance. 3307 if (!VD->evaluateValue()) { 3308 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3309 NoteLValueLocation(Info, Base); 3310 return false; 3311 } 3312 3313 // Check that the variable is actually usable in constant expressions. For a 3314 // const integral variable or a reference, we might have a non-constant 3315 // initializer that we can nonetheless evaluate the initializer for. Such 3316 // variables are not usable in constant expressions. In C++98, the 3317 // initializer also syntactically needs to be an ICE. 3318 // 3319 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3320 // expressions here; doing so would regress diagnostics for things like 3321 // reading from a volatile constexpr variable. 3322 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3323 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3324 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3325 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3326 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3327 NoteLValueLocation(Info, Base); 3328 } 3329 3330 // Never use the initializer of a weak variable, not even for constant 3331 // folding. We can't be sure that this is the definition that will be used. 3332 if (VD->isWeak()) { 3333 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3334 NoteLValueLocation(Info, Base); 3335 return false; 3336 } 3337 3338 Result = VD->getEvaluatedValue(); 3339 return true; 3340 } 3341 3342 /// Get the base index of the given base class within an APValue representing 3343 /// the given derived class. 3344 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3345 const CXXRecordDecl *Base) { 3346 Base = Base->getCanonicalDecl(); 3347 unsigned Index = 0; 3348 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3349 E = Derived->bases_end(); I != E; ++I, ++Index) { 3350 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3351 return Index; 3352 } 3353 3354 llvm_unreachable("base class missing from derived class's bases list"); 3355 } 3356 3357 /// Extract the value of a character from a string literal. 3358 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3359 uint64_t Index) { 3360 assert(!isa<SourceLocExpr>(Lit) && 3361 "SourceLocExpr should have already been converted to a StringLiteral"); 3362 3363 // FIXME: Support MakeStringConstant 3364 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3365 std::string Str; 3366 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3367 assert(Index <= Str.size() && "Index too large"); 3368 return APSInt::getUnsigned(Str.c_str()[Index]); 3369 } 3370 3371 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3372 Lit = PE->getFunctionName(); 3373 const StringLiteral *S = cast<StringLiteral>(Lit); 3374 const ConstantArrayType *CAT = 3375 Info.Ctx.getAsConstantArrayType(S->getType()); 3376 assert(CAT && "string literal isn't an array"); 3377 QualType CharType = CAT->getElementType(); 3378 assert(CharType->isIntegerType() && "unexpected character type"); 3379 3380 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3381 CharType->isUnsignedIntegerType()); 3382 if (Index < S->getLength()) 3383 Value = S->getCodeUnit(Index); 3384 return Value; 3385 } 3386 3387 // Expand a string literal into an array of characters. 3388 // 3389 // FIXME: This is inefficient; we should probably introduce something similar 3390 // to the LLVM ConstantDataArray to make this cheaper. 3391 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3392 APValue &Result, 3393 QualType AllocType = QualType()) { 3394 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3395 AllocType.isNull() ? S->getType() : AllocType); 3396 assert(CAT && "string literal isn't an array"); 3397 QualType CharType = CAT->getElementType(); 3398 assert(CharType->isIntegerType() && "unexpected character type"); 3399 3400 unsigned Elts = CAT->getSize().getZExtValue(); 3401 Result = APValue(APValue::UninitArray(), 3402 std::min(S->getLength(), Elts), Elts); 3403 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3404 CharType->isUnsignedIntegerType()); 3405 if (Result.hasArrayFiller()) 3406 Result.getArrayFiller() = APValue(Value); 3407 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3408 Value = S->getCodeUnit(I); 3409 Result.getArrayInitializedElt(I) = APValue(Value); 3410 } 3411 } 3412 3413 // Expand an array so that it has more than Index filled elements. 3414 static void expandArray(APValue &Array, unsigned Index) { 3415 unsigned Size = Array.getArraySize(); 3416 assert(Index < Size); 3417 3418 // Always at least double the number of elements for which we store a value. 3419 unsigned OldElts = Array.getArrayInitializedElts(); 3420 unsigned NewElts = std::max(Index+1, OldElts * 2); 3421 NewElts = std::min(Size, std::max(NewElts, 8u)); 3422 3423 // Copy the data across. 3424 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3425 for (unsigned I = 0; I != OldElts; ++I) 3426 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3427 for (unsigned I = OldElts; I != NewElts; ++I) 3428 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3429 if (NewValue.hasArrayFiller()) 3430 NewValue.getArrayFiller() = Array.getArrayFiller(); 3431 Array.swap(NewValue); 3432 } 3433 3434 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3435 /// conversion. If it's of class type, we may assume that the copy operation 3436 /// is trivial. Note that this is never true for a union type with fields 3437 /// (because the copy always "reads" the active member) and always true for 3438 /// a non-class type. 3439 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3440 static bool isReadByLvalueToRvalueConversion(QualType T) { 3441 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3442 return !RD || isReadByLvalueToRvalueConversion(RD); 3443 } 3444 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3445 // FIXME: A trivial copy of a union copies the object representation, even if 3446 // the union is empty. 3447 if (RD->isUnion()) 3448 return !RD->field_empty(); 3449 if (RD->isEmpty()) 3450 return false; 3451 3452 for (auto *Field : RD->fields()) 3453 if (!Field->isUnnamedBitfield() && 3454 isReadByLvalueToRvalueConversion(Field->getType())) 3455 return true; 3456 3457 for (auto &BaseSpec : RD->bases()) 3458 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3459 return true; 3460 3461 return false; 3462 } 3463 3464 /// Diagnose an attempt to read from any unreadable field within the specified 3465 /// type, which might be a class type. 3466 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3467 QualType T) { 3468 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3469 if (!RD) 3470 return false; 3471 3472 if (!RD->hasMutableFields()) 3473 return false; 3474 3475 for (auto *Field : RD->fields()) { 3476 // If we're actually going to read this field in some way, then it can't 3477 // be mutable. If we're in a union, then assigning to a mutable field 3478 // (even an empty one) can change the active member, so that's not OK. 3479 // FIXME: Add core issue number for the union case. 3480 if (Field->isMutable() && 3481 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3482 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3483 Info.Note(Field->getLocation(), diag::note_declared_at); 3484 return true; 3485 } 3486 3487 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3488 return true; 3489 } 3490 3491 for (auto &BaseSpec : RD->bases()) 3492 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3493 return true; 3494 3495 // All mutable fields were empty, and thus not actually read. 3496 return false; 3497 } 3498 3499 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3500 APValue::LValueBase Base, 3501 bool MutableSubobject = false) { 3502 // A temporary or transient heap allocation we created. 3503 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3504 return true; 3505 3506 switch (Info.IsEvaluatingDecl) { 3507 case EvalInfo::EvaluatingDeclKind::None: 3508 return false; 3509 3510 case EvalInfo::EvaluatingDeclKind::Ctor: 3511 // The variable whose initializer we're evaluating. 3512 if (Info.EvaluatingDecl == Base) 3513 return true; 3514 3515 // A temporary lifetime-extended by the variable whose initializer we're 3516 // evaluating. 3517 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3518 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3519 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3520 return false; 3521 3522 case EvalInfo::EvaluatingDeclKind::Dtor: 3523 // C++2a [expr.const]p6: 3524 // [during constant destruction] the lifetime of a and its non-mutable 3525 // subobjects (but not its mutable subobjects) [are] considered to start 3526 // within e. 3527 if (MutableSubobject || Base != Info.EvaluatingDecl) 3528 return false; 3529 // FIXME: We can meaningfully extend this to cover non-const objects, but 3530 // we will need special handling: we should be able to access only 3531 // subobjects of such objects that are themselves declared const. 3532 QualType T = getType(Base); 3533 return T.isConstQualified() || T->isReferenceType(); 3534 } 3535 3536 llvm_unreachable("unknown evaluating decl kind"); 3537 } 3538 3539 namespace { 3540 /// A handle to a complete object (an object that is not a subobject of 3541 /// another object). 3542 struct CompleteObject { 3543 /// The identity of the object. 3544 APValue::LValueBase Base; 3545 /// The value of the complete object. 3546 APValue *Value; 3547 /// The type of the complete object. 3548 QualType Type; 3549 3550 CompleteObject() : Value(nullptr) {} 3551 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3552 : Base(Base), Value(Value), Type(Type) {} 3553 3554 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3555 // If this isn't a "real" access (eg, if it's just accessing the type 3556 // info), allow it. We assume the type doesn't change dynamically for 3557 // subobjects of constexpr objects (even though we'd hit UB here if it 3558 // did). FIXME: Is this right? 3559 if (!isAnyAccess(AK)) 3560 return true; 3561 3562 // In C++14 onwards, it is permitted to read a mutable member whose 3563 // lifetime began within the evaluation. 3564 // FIXME: Should we also allow this in C++11? 3565 if (!Info.getLangOpts().CPlusPlus14) 3566 return false; 3567 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3568 } 3569 3570 explicit operator bool() const { return !Type.isNull(); } 3571 }; 3572 } // end anonymous namespace 3573 3574 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3575 bool IsMutable = false) { 3576 // C++ [basic.type.qualifier]p1: 3577 // - A const object is an object of type const T or a non-mutable subobject 3578 // of a const object. 3579 if (ObjType.isConstQualified() && !IsMutable) 3580 SubobjType.addConst(); 3581 // - A volatile object is an object of type const T or a subobject of a 3582 // volatile object. 3583 if (ObjType.isVolatileQualified()) 3584 SubobjType.addVolatile(); 3585 return SubobjType; 3586 } 3587 3588 /// Find the designated sub-object of an rvalue. 3589 template<typename SubobjectHandler> 3590 typename SubobjectHandler::result_type 3591 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3592 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3593 if (Sub.Invalid) 3594 // A diagnostic will have already been produced. 3595 return handler.failed(); 3596 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3597 if (Info.getLangOpts().CPlusPlus11) 3598 Info.FFDiag(E, Sub.isOnePastTheEnd() 3599 ? diag::note_constexpr_access_past_end 3600 : diag::note_constexpr_access_unsized_array) 3601 << handler.AccessKind; 3602 else 3603 Info.FFDiag(E); 3604 return handler.failed(); 3605 } 3606 3607 APValue *O = Obj.Value; 3608 QualType ObjType = Obj.Type; 3609 const FieldDecl *LastField = nullptr; 3610 const FieldDecl *VolatileField = nullptr; 3611 3612 // Walk the designator's path to find the subobject. 3613 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3614 // Reading an indeterminate value is undefined, but assigning over one is OK. 3615 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3616 (O->isIndeterminate() && 3617 !isValidIndeterminateAccess(handler.AccessKind))) { 3618 if (!Info.checkingPotentialConstantExpression()) 3619 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3620 << handler.AccessKind << O->isIndeterminate(); 3621 return handler.failed(); 3622 } 3623 3624 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3625 // const and volatile semantics are not applied on an object under 3626 // {con,de}struction. 3627 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3628 ObjType->isRecordType() && 3629 Info.isEvaluatingCtorDtor( 3630 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3631 Sub.Entries.begin() + I)) != 3632 ConstructionPhase::None) { 3633 ObjType = Info.Ctx.getCanonicalType(ObjType); 3634 ObjType.removeLocalConst(); 3635 ObjType.removeLocalVolatile(); 3636 } 3637 3638 // If this is our last pass, check that the final object type is OK. 3639 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3640 // Accesses to volatile objects are prohibited. 3641 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3642 if (Info.getLangOpts().CPlusPlus) { 3643 int DiagKind; 3644 SourceLocation Loc; 3645 const NamedDecl *Decl = nullptr; 3646 if (VolatileField) { 3647 DiagKind = 2; 3648 Loc = VolatileField->getLocation(); 3649 Decl = VolatileField; 3650 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3651 DiagKind = 1; 3652 Loc = VD->getLocation(); 3653 Decl = VD; 3654 } else { 3655 DiagKind = 0; 3656 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3657 Loc = E->getExprLoc(); 3658 } 3659 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3660 << handler.AccessKind << DiagKind << Decl; 3661 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3662 } else { 3663 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3664 } 3665 return handler.failed(); 3666 } 3667 3668 // If we are reading an object of class type, there may still be more 3669 // things we need to check: if there are any mutable subobjects, we 3670 // cannot perform this read. (This only happens when performing a trivial 3671 // copy or assignment.) 3672 if (ObjType->isRecordType() && 3673 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3674 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3675 return handler.failed(); 3676 } 3677 3678 if (I == N) { 3679 if (!handler.found(*O, ObjType)) 3680 return false; 3681 3682 // If we modified a bit-field, truncate it to the right width. 3683 if (isModification(handler.AccessKind) && 3684 LastField && LastField->isBitField() && 3685 !truncateBitfieldValue(Info, E, *O, LastField)) 3686 return false; 3687 3688 return true; 3689 } 3690 3691 LastField = nullptr; 3692 if (ObjType->isArrayType()) { 3693 // Next subobject is an array element. 3694 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3695 assert(CAT && "vla in literal type?"); 3696 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3697 if (CAT->getSize().ule(Index)) { 3698 // Note, it should not be possible to form a pointer with a valid 3699 // designator which points more than one past the end of the array. 3700 if (Info.getLangOpts().CPlusPlus11) 3701 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3702 << handler.AccessKind; 3703 else 3704 Info.FFDiag(E); 3705 return handler.failed(); 3706 } 3707 3708 ObjType = CAT->getElementType(); 3709 3710 if (O->getArrayInitializedElts() > Index) 3711 O = &O->getArrayInitializedElt(Index); 3712 else if (!isRead(handler.AccessKind)) { 3713 expandArray(*O, Index); 3714 O = &O->getArrayInitializedElt(Index); 3715 } else 3716 O = &O->getArrayFiller(); 3717 } else if (ObjType->isAnyComplexType()) { 3718 // Next subobject is a complex number. 3719 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3720 if (Index > 1) { 3721 if (Info.getLangOpts().CPlusPlus11) 3722 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3723 << handler.AccessKind; 3724 else 3725 Info.FFDiag(E); 3726 return handler.failed(); 3727 } 3728 3729 ObjType = getSubobjectType( 3730 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3731 3732 assert(I == N - 1 && "extracting subobject of scalar?"); 3733 if (O->isComplexInt()) { 3734 return handler.found(Index ? O->getComplexIntImag() 3735 : O->getComplexIntReal(), ObjType); 3736 } else { 3737 assert(O->isComplexFloat()); 3738 return handler.found(Index ? O->getComplexFloatImag() 3739 : O->getComplexFloatReal(), ObjType); 3740 } 3741 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3742 if (Field->isMutable() && 3743 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3744 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3745 << handler.AccessKind << Field; 3746 Info.Note(Field->getLocation(), diag::note_declared_at); 3747 return handler.failed(); 3748 } 3749 3750 // Next subobject is a class, struct or union field. 3751 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3752 if (RD->isUnion()) { 3753 const FieldDecl *UnionField = O->getUnionField(); 3754 if (!UnionField || 3755 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3756 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3757 // Placement new onto an inactive union member makes it active. 3758 O->setUnion(Field, APValue()); 3759 } else { 3760 // FIXME: If O->getUnionValue() is absent, report that there's no 3761 // active union member rather than reporting the prior active union 3762 // member. We'll need to fix nullptr_t to not use APValue() as its 3763 // representation first. 3764 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3765 << handler.AccessKind << Field << !UnionField << UnionField; 3766 return handler.failed(); 3767 } 3768 } 3769 O = &O->getUnionValue(); 3770 } else 3771 O = &O->getStructField(Field->getFieldIndex()); 3772 3773 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3774 LastField = Field; 3775 if (Field->getType().isVolatileQualified()) 3776 VolatileField = Field; 3777 } else { 3778 // Next subobject is a base class. 3779 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3780 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3781 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3782 3783 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3784 } 3785 } 3786 } 3787 3788 namespace { 3789 struct ExtractSubobjectHandler { 3790 EvalInfo &Info; 3791 const Expr *E; 3792 APValue &Result; 3793 const AccessKinds AccessKind; 3794 3795 typedef bool result_type; 3796 bool failed() { return false; } 3797 bool found(APValue &Subobj, QualType SubobjType) { 3798 Result = Subobj; 3799 if (AccessKind == AK_ReadObjectRepresentation) 3800 return true; 3801 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3802 } 3803 bool found(APSInt &Value, QualType SubobjType) { 3804 Result = APValue(Value); 3805 return true; 3806 } 3807 bool found(APFloat &Value, QualType SubobjType) { 3808 Result = APValue(Value); 3809 return true; 3810 } 3811 }; 3812 } // end anonymous namespace 3813 3814 /// Extract the designated sub-object of an rvalue. 3815 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3816 const CompleteObject &Obj, 3817 const SubobjectDesignator &Sub, APValue &Result, 3818 AccessKinds AK = AK_Read) { 3819 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3820 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3821 return findSubobject(Info, E, Obj, Sub, Handler); 3822 } 3823 3824 namespace { 3825 struct ModifySubobjectHandler { 3826 EvalInfo &Info; 3827 APValue &NewVal; 3828 const Expr *E; 3829 3830 typedef bool result_type; 3831 static const AccessKinds AccessKind = AK_Assign; 3832 3833 bool checkConst(QualType QT) { 3834 // Assigning to a const object has undefined behavior. 3835 if (QT.isConstQualified()) { 3836 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3837 return false; 3838 } 3839 return true; 3840 } 3841 3842 bool failed() { return false; } 3843 bool found(APValue &Subobj, QualType SubobjType) { 3844 if (!checkConst(SubobjType)) 3845 return false; 3846 // We've been given ownership of NewVal, so just swap it in. 3847 Subobj.swap(NewVal); 3848 return true; 3849 } 3850 bool found(APSInt &Value, QualType SubobjType) { 3851 if (!checkConst(SubobjType)) 3852 return false; 3853 if (!NewVal.isInt()) { 3854 // Maybe trying to write a cast pointer value into a complex? 3855 Info.FFDiag(E); 3856 return false; 3857 } 3858 Value = NewVal.getInt(); 3859 return true; 3860 } 3861 bool found(APFloat &Value, QualType SubobjType) { 3862 if (!checkConst(SubobjType)) 3863 return false; 3864 Value = NewVal.getFloat(); 3865 return true; 3866 } 3867 }; 3868 } // end anonymous namespace 3869 3870 const AccessKinds ModifySubobjectHandler::AccessKind; 3871 3872 /// Update the designated sub-object of an rvalue to the given value. 3873 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3874 const CompleteObject &Obj, 3875 const SubobjectDesignator &Sub, 3876 APValue &NewVal) { 3877 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3878 return findSubobject(Info, E, Obj, Sub, Handler); 3879 } 3880 3881 /// Find the position where two subobject designators diverge, or equivalently 3882 /// the length of the common initial subsequence. 3883 static unsigned FindDesignatorMismatch(QualType ObjType, 3884 const SubobjectDesignator &A, 3885 const SubobjectDesignator &B, 3886 bool &WasArrayIndex) { 3887 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3888 for (/**/; I != N; ++I) { 3889 if (!ObjType.isNull() && 3890 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3891 // Next subobject is an array element. 3892 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3893 WasArrayIndex = true; 3894 return I; 3895 } 3896 if (ObjType->isAnyComplexType()) 3897 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3898 else 3899 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3900 } else { 3901 if (A.Entries[I].getAsBaseOrMember() != 3902 B.Entries[I].getAsBaseOrMember()) { 3903 WasArrayIndex = false; 3904 return I; 3905 } 3906 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3907 // Next subobject is a field. 3908 ObjType = FD->getType(); 3909 else 3910 // Next subobject is a base class. 3911 ObjType = QualType(); 3912 } 3913 } 3914 WasArrayIndex = false; 3915 return I; 3916 } 3917 3918 /// Determine whether the given subobject designators refer to elements of the 3919 /// same array object. 3920 static bool AreElementsOfSameArray(QualType ObjType, 3921 const SubobjectDesignator &A, 3922 const SubobjectDesignator &B) { 3923 if (A.Entries.size() != B.Entries.size()) 3924 return false; 3925 3926 bool IsArray = A.MostDerivedIsArrayElement; 3927 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3928 // A is a subobject of the array element. 3929 return false; 3930 3931 // If A (and B) designates an array element, the last entry will be the array 3932 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3933 // of length 1' case, and the entire path must match. 3934 bool WasArrayIndex; 3935 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3936 return CommonLength >= A.Entries.size() - IsArray; 3937 } 3938 3939 /// Find the complete object to which an LValue refers. 3940 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3941 AccessKinds AK, const LValue &LVal, 3942 QualType LValType) { 3943 if (LVal.InvalidBase) { 3944 Info.FFDiag(E); 3945 return CompleteObject(); 3946 } 3947 3948 if (!LVal.Base) { 3949 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3950 return CompleteObject(); 3951 } 3952 3953 CallStackFrame *Frame = nullptr; 3954 unsigned Depth = 0; 3955 if (LVal.getLValueCallIndex()) { 3956 std::tie(Frame, Depth) = 3957 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3958 if (!Frame) { 3959 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3960 << AK << LVal.Base.is<const ValueDecl*>(); 3961 NoteLValueLocation(Info, LVal.Base); 3962 return CompleteObject(); 3963 } 3964 } 3965 3966 bool IsAccess = isAnyAccess(AK); 3967 3968 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3969 // is not a constant expression (even if the object is non-volatile). We also 3970 // apply this rule to C++98, in order to conform to the expected 'volatile' 3971 // semantics. 3972 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3973 if (Info.getLangOpts().CPlusPlus) 3974 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3975 << AK << LValType; 3976 else 3977 Info.FFDiag(E); 3978 return CompleteObject(); 3979 } 3980 3981 // Compute value storage location and type of base object. 3982 APValue *BaseVal = nullptr; 3983 QualType BaseType = getType(LVal.Base); 3984 3985 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3986 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3987 // This is the object whose initializer we're evaluating, so its lifetime 3988 // started in the current evaluation. 3989 BaseVal = Info.EvaluatingDeclValue; 3990 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3991 // Allow reading from a GUID declaration. 3992 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3993 if (isModification(AK)) { 3994 // All the remaining cases do not permit modification of the object. 3995 Info.FFDiag(E, diag::note_constexpr_modify_global); 3996 return CompleteObject(); 3997 } 3998 APValue &V = GD->getAsAPValue(); 3999 if (V.isAbsent()) { 4000 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4001 << GD->getType(); 4002 return CompleteObject(); 4003 } 4004 return CompleteObject(LVal.Base, &V, GD->getType()); 4005 } 4006 4007 // Allow reading from template parameter objects. 4008 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4009 if (isModification(AK)) { 4010 Info.FFDiag(E, diag::note_constexpr_modify_global); 4011 return CompleteObject(); 4012 } 4013 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4014 TPO->getType()); 4015 } 4016 4017 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4018 // In C++11, constexpr, non-volatile variables initialized with constant 4019 // expressions are constant expressions too. Inside constexpr functions, 4020 // parameters are constant expressions even if they're non-const. 4021 // In C++1y, objects local to a constant expression (those with a Frame) are 4022 // both readable and writable inside constant expressions. 4023 // In C, such things can also be folded, although they are not ICEs. 4024 const VarDecl *VD = dyn_cast<VarDecl>(D); 4025 if (VD) { 4026 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4027 VD = VDef; 4028 } 4029 if (!VD || VD->isInvalidDecl()) { 4030 Info.FFDiag(E); 4031 return CompleteObject(); 4032 } 4033 4034 bool IsConstant = BaseType.isConstant(Info.Ctx); 4035 4036 // Unless we're looking at a local variable or argument in a constexpr call, 4037 // the variable we're reading must be const. 4038 if (!Frame) { 4039 if (IsAccess && isa<ParmVarDecl>(VD)) { 4040 // Access of a parameter that's not associated with a frame isn't going 4041 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4042 // suitable diagnostic. 4043 } else if (Info.getLangOpts().CPlusPlus14 && 4044 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4045 // OK, we can read and modify an object if we're in the process of 4046 // evaluating its initializer, because its lifetime began in this 4047 // evaluation. 4048 } else if (isModification(AK)) { 4049 // All the remaining cases do not permit modification of the object. 4050 Info.FFDiag(E, diag::note_constexpr_modify_global); 4051 return CompleteObject(); 4052 } else if (VD->isConstexpr()) { 4053 // OK, we can read this variable. 4054 } else if (BaseType->isIntegralOrEnumerationType()) { 4055 if (!IsConstant) { 4056 if (!IsAccess) 4057 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4058 if (Info.getLangOpts().CPlusPlus) { 4059 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4060 Info.Note(VD->getLocation(), diag::note_declared_at); 4061 } else { 4062 Info.FFDiag(E); 4063 } 4064 return CompleteObject(); 4065 } 4066 } else if (!IsAccess) { 4067 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4068 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4069 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4070 // This variable might end up being constexpr. Don't diagnose it yet. 4071 } else if (IsConstant) { 4072 // Keep evaluating to see what we can do. In particular, we support 4073 // folding of const floating-point types, in order to make static const 4074 // data members of such types (supported as an extension) more useful. 4075 if (Info.getLangOpts().CPlusPlus) { 4076 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4077 ? diag::note_constexpr_ltor_non_constexpr 4078 : diag::note_constexpr_ltor_non_integral, 1) 4079 << VD << BaseType; 4080 Info.Note(VD->getLocation(), diag::note_declared_at); 4081 } else { 4082 Info.CCEDiag(E); 4083 } 4084 } else { 4085 // Never allow reading a non-const value. 4086 if (Info.getLangOpts().CPlusPlus) { 4087 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4088 ? diag::note_constexpr_ltor_non_constexpr 4089 : diag::note_constexpr_ltor_non_integral, 1) 4090 << VD << BaseType; 4091 Info.Note(VD->getLocation(), diag::note_declared_at); 4092 } else { 4093 Info.FFDiag(E); 4094 } 4095 return CompleteObject(); 4096 } 4097 } 4098 4099 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4100 return CompleteObject(); 4101 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4102 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4103 if (!Alloc) { 4104 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4105 return CompleteObject(); 4106 } 4107 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4108 LVal.Base.getDynamicAllocType()); 4109 } else { 4110 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4111 4112 if (!Frame) { 4113 if (const MaterializeTemporaryExpr *MTE = 4114 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4115 assert(MTE->getStorageDuration() == SD_Static && 4116 "should have a frame for a non-global materialized temporary"); 4117 4118 // C++20 [expr.const]p4: [DR2126] 4119 // An object or reference is usable in constant expressions if it is 4120 // - a temporary object of non-volatile const-qualified literal type 4121 // whose lifetime is extended to that of a variable that is usable 4122 // in constant expressions 4123 // 4124 // C++20 [expr.const]p5: 4125 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4126 // - a non-volatile glvalue that refers to an object that is usable 4127 // in constant expressions, or 4128 // - a non-volatile glvalue of literal type that refers to a 4129 // non-volatile object whose lifetime began within the evaluation 4130 // of E; 4131 // 4132 // C++11 misses the 'began within the evaluation of e' check and 4133 // instead allows all temporaries, including things like: 4134 // int &&r = 1; 4135 // int x = ++r; 4136 // constexpr int k = r; 4137 // Therefore we use the C++14-onwards rules in C++11 too. 4138 // 4139 // Note that temporaries whose lifetimes began while evaluating a 4140 // variable's constructor are not usable while evaluating the 4141 // corresponding destructor, not even if they're of const-qualified 4142 // types. 4143 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4144 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4145 if (!IsAccess) 4146 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4147 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4148 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4149 return CompleteObject(); 4150 } 4151 4152 BaseVal = MTE->getOrCreateValue(false); 4153 assert(BaseVal && "got reference to unevaluated temporary"); 4154 } else { 4155 if (!IsAccess) 4156 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4157 APValue Val; 4158 LVal.moveInto(Val); 4159 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4160 << AK 4161 << Val.getAsString(Info.Ctx, 4162 Info.Ctx.getLValueReferenceType(LValType)); 4163 NoteLValueLocation(Info, LVal.Base); 4164 return CompleteObject(); 4165 } 4166 } else { 4167 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4168 assert(BaseVal && "missing value for temporary"); 4169 } 4170 } 4171 4172 // In C++14, we can't safely access any mutable state when we might be 4173 // evaluating after an unmodeled side effect. Parameters are modeled as state 4174 // in the caller, but aren't visible once the call returns, so they can be 4175 // modified in a speculatively-evaluated call. 4176 // 4177 // FIXME: Not all local state is mutable. Allow local constant subobjects 4178 // to be read here (but take care with 'mutable' fields). 4179 unsigned VisibleDepth = Depth; 4180 if (llvm::isa_and_nonnull<ParmVarDecl>( 4181 LVal.Base.dyn_cast<const ValueDecl *>())) 4182 ++VisibleDepth; 4183 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4184 Info.EvalStatus.HasSideEffects) || 4185 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4186 return CompleteObject(); 4187 4188 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4189 } 4190 4191 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4192 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4193 /// glvalue referred to by an entity of reference type. 4194 /// 4195 /// \param Info - Information about the ongoing evaluation. 4196 /// \param Conv - The expression for which we are performing the conversion. 4197 /// Used for diagnostics. 4198 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4199 /// case of a non-class type). 4200 /// \param LVal - The glvalue on which we are attempting to perform this action. 4201 /// \param RVal - The produced value will be placed here. 4202 /// \param WantObjectRepresentation - If true, we're looking for the object 4203 /// representation rather than the value, and in particular, 4204 /// there is no requirement that the result be fully initialized. 4205 static bool 4206 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4207 const LValue &LVal, APValue &RVal, 4208 bool WantObjectRepresentation = false) { 4209 if (LVal.Designator.Invalid) 4210 return false; 4211 4212 // Check for special cases where there is no existing APValue to look at. 4213 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4214 4215 AccessKinds AK = 4216 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4217 4218 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4219 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4220 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4221 // initializer until now for such expressions. Such an expression can't be 4222 // an ICE in C, so this only matters for fold. 4223 if (Type.isVolatileQualified()) { 4224 Info.FFDiag(Conv); 4225 return false; 4226 } 4227 APValue Lit; 4228 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4229 return false; 4230 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4231 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4232 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4233 // Special-case character extraction so we don't have to construct an 4234 // APValue for the whole string. 4235 assert(LVal.Designator.Entries.size() <= 1 && 4236 "Can only read characters from string literals"); 4237 if (LVal.Designator.Entries.empty()) { 4238 // Fail for now for LValue to RValue conversion of an array. 4239 // (This shouldn't show up in C/C++, but it could be triggered by a 4240 // weird EvaluateAsRValue call from a tool.) 4241 Info.FFDiag(Conv); 4242 return false; 4243 } 4244 if (LVal.Designator.isOnePastTheEnd()) { 4245 if (Info.getLangOpts().CPlusPlus11) 4246 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4247 else 4248 Info.FFDiag(Conv); 4249 return false; 4250 } 4251 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4252 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4253 return true; 4254 } 4255 } 4256 4257 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4258 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4259 } 4260 4261 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4262 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4263 QualType LValType, APValue &Val) { 4264 if (LVal.Designator.Invalid) 4265 return false; 4266 4267 if (!Info.getLangOpts().CPlusPlus14) { 4268 Info.FFDiag(E); 4269 return false; 4270 } 4271 4272 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4273 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4274 } 4275 4276 namespace { 4277 struct CompoundAssignSubobjectHandler { 4278 EvalInfo &Info; 4279 const CompoundAssignOperator *E; 4280 QualType PromotedLHSType; 4281 BinaryOperatorKind Opcode; 4282 const APValue &RHS; 4283 4284 static const AccessKinds AccessKind = AK_Assign; 4285 4286 typedef bool result_type; 4287 4288 bool checkConst(QualType QT) { 4289 // Assigning to a const object has undefined behavior. 4290 if (QT.isConstQualified()) { 4291 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4292 return false; 4293 } 4294 return true; 4295 } 4296 4297 bool failed() { return false; } 4298 bool found(APValue &Subobj, QualType SubobjType) { 4299 switch (Subobj.getKind()) { 4300 case APValue::Int: 4301 return found(Subobj.getInt(), SubobjType); 4302 case APValue::Float: 4303 return found(Subobj.getFloat(), SubobjType); 4304 case APValue::ComplexInt: 4305 case APValue::ComplexFloat: 4306 // FIXME: Implement complex compound assignment. 4307 Info.FFDiag(E); 4308 return false; 4309 case APValue::LValue: 4310 return foundPointer(Subobj, SubobjType); 4311 case APValue::Vector: 4312 return foundVector(Subobj, SubobjType); 4313 default: 4314 // FIXME: can this happen? 4315 Info.FFDiag(E); 4316 return false; 4317 } 4318 } 4319 4320 bool foundVector(APValue &Value, QualType SubobjType) { 4321 if (!checkConst(SubobjType)) 4322 return false; 4323 4324 if (!SubobjType->isVectorType()) { 4325 Info.FFDiag(E); 4326 return false; 4327 } 4328 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4329 } 4330 4331 bool found(APSInt &Value, QualType SubobjType) { 4332 if (!checkConst(SubobjType)) 4333 return false; 4334 4335 if (!SubobjType->isIntegerType()) { 4336 // We don't support compound assignment on integer-cast-to-pointer 4337 // values. 4338 Info.FFDiag(E); 4339 return false; 4340 } 4341 4342 if (RHS.isInt()) { 4343 APSInt LHS = 4344 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4345 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4346 return false; 4347 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4348 return true; 4349 } else if (RHS.isFloat()) { 4350 const FPOptions FPO = E->getFPFeaturesInEffect( 4351 Info.Ctx.getLangOpts()); 4352 APFloat FValue(0.0); 4353 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4354 PromotedLHSType, FValue) && 4355 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4356 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4357 Value); 4358 } 4359 4360 Info.FFDiag(E); 4361 return false; 4362 } 4363 bool found(APFloat &Value, QualType SubobjType) { 4364 return checkConst(SubobjType) && 4365 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4366 Value) && 4367 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4368 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4369 } 4370 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4371 if (!checkConst(SubobjType)) 4372 return false; 4373 4374 QualType PointeeType; 4375 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4376 PointeeType = PT->getPointeeType(); 4377 4378 if (PointeeType.isNull() || !RHS.isInt() || 4379 (Opcode != BO_Add && Opcode != BO_Sub)) { 4380 Info.FFDiag(E); 4381 return false; 4382 } 4383 4384 APSInt Offset = RHS.getInt(); 4385 if (Opcode == BO_Sub) 4386 negateAsSigned(Offset); 4387 4388 LValue LVal; 4389 LVal.setFrom(Info.Ctx, Subobj); 4390 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4391 return false; 4392 LVal.moveInto(Subobj); 4393 return true; 4394 } 4395 }; 4396 } // end anonymous namespace 4397 4398 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4399 4400 /// Perform a compound assignment of LVal <op>= RVal. 4401 static bool handleCompoundAssignment(EvalInfo &Info, 4402 const CompoundAssignOperator *E, 4403 const LValue &LVal, QualType LValType, 4404 QualType PromotedLValType, 4405 BinaryOperatorKind Opcode, 4406 const APValue &RVal) { 4407 if (LVal.Designator.Invalid) 4408 return false; 4409 4410 if (!Info.getLangOpts().CPlusPlus14) { 4411 Info.FFDiag(E); 4412 return false; 4413 } 4414 4415 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4416 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4417 RVal }; 4418 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4419 } 4420 4421 namespace { 4422 struct IncDecSubobjectHandler { 4423 EvalInfo &Info; 4424 const UnaryOperator *E; 4425 AccessKinds AccessKind; 4426 APValue *Old; 4427 4428 typedef bool result_type; 4429 4430 bool checkConst(QualType QT) { 4431 // Assigning to a const object has undefined behavior. 4432 if (QT.isConstQualified()) { 4433 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4434 return false; 4435 } 4436 return true; 4437 } 4438 4439 bool failed() { return false; } 4440 bool found(APValue &Subobj, QualType SubobjType) { 4441 // Stash the old value. Also clear Old, so we don't clobber it later 4442 // if we're post-incrementing a complex. 4443 if (Old) { 4444 *Old = Subobj; 4445 Old = nullptr; 4446 } 4447 4448 switch (Subobj.getKind()) { 4449 case APValue::Int: 4450 return found(Subobj.getInt(), SubobjType); 4451 case APValue::Float: 4452 return found(Subobj.getFloat(), SubobjType); 4453 case APValue::ComplexInt: 4454 return found(Subobj.getComplexIntReal(), 4455 SubobjType->castAs<ComplexType>()->getElementType() 4456 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4457 case APValue::ComplexFloat: 4458 return found(Subobj.getComplexFloatReal(), 4459 SubobjType->castAs<ComplexType>()->getElementType() 4460 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4461 case APValue::LValue: 4462 return foundPointer(Subobj, SubobjType); 4463 default: 4464 // FIXME: can this happen? 4465 Info.FFDiag(E); 4466 return false; 4467 } 4468 } 4469 bool found(APSInt &Value, QualType SubobjType) { 4470 if (!checkConst(SubobjType)) 4471 return false; 4472 4473 if (!SubobjType->isIntegerType()) { 4474 // We don't support increment / decrement on integer-cast-to-pointer 4475 // values. 4476 Info.FFDiag(E); 4477 return false; 4478 } 4479 4480 if (Old) *Old = APValue(Value); 4481 4482 // bool arithmetic promotes to int, and the conversion back to bool 4483 // doesn't reduce mod 2^n, so special-case it. 4484 if (SubobjType->isBooleanType()) { 4485 if (AccessKind == AK_Increment) 4486 Value = 1; 4487 else 4488 Value = !Value; 4489 return true; 4490 } 4491 4492 bool WasNegative = Value.isNegative(); 4493 if (AccessKind == AK_Increment) { 4494 ++Value; 4495 4496 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4497 APSInt ActualValue(Value, /*IsUnsigned*/true); 4498 return HandleOverflow(Info, E, ActualValue, SubobjType); 4499 } 4500 } else { 4501 --Value; 4502 4503 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4504 unsigned BitWidth = Value.getBitWidth(); 4505 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4506 ActualValue.setBit(BitWidth); 4507 return HandleOverflow(Info, E, ActualValue, SubobjType); 4508 } 4509 } 4510 return true; 4511 } 4512 bool found(APFloat &Value, QualType SubobjType) { 4513 if (!checkConst(SubobjType)) 4514 return false; 4515 4516 if (Old) *Old = APValue(Value); 4517 4518 APFloat One(Value.getSemantics(), 1); 4519 if (AccessKind == AK_Increment) 4520 Value.add(One, APFloat::rmNearestTiesToEven); 4521 else 4522 Value.subtract(One, APFloat::rmNearestTiesToEven); 4523 return true; 4524 } 4525 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4526 if (!checkConst(SubobjType)) 4527 return false; 4528 4529 QualType PointeeType; 4530 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4531 PointeeType = PT->getPointeeType(); 4532 else { 4533 Info.FFDiag(E); 4534 return false; 4535 } 4536 4537 LValue LVal; 4538 LVal.setFrom(Info.Ctx, Subobj); 4539 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4540 AccessKind == AK_Increment ? 1 : -1)) 4541 return false; 4542 LVal.moveInto(Subobj); 4543 return true; 4544 } 4545 }; 4546 } // end anonymous namespace 4547 4548 /// Perform an increment or decrement on LVal. 4549 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4550 QualType LValType, bool IsIncrement, APValue *Old) { 4551 if (LVal.Designator.Invalid) 4552 return false; 4553 4554 if (!Info.getLangOpts().CPlusPlus14) { 4555 Info.FFDiag(E); 4556 return false; 4557 } 4558 4559 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4560 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4561 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4562 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4563 } 4564 4565 /// Build an lvalue for the object argument of a member function call. 4566 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4567 LValue &This) { 4568 if (Object->getType()->isPointerType() && Object->isRValue()) 4569 return EvaluatePointer(Object, This, Info); 4570 4571 if (Object->isGLValue()) 4572 return EvaluateLValue(Object, This, Info); 4573 4574 if (Object->getType()->isLiteralType(Info.Ctx)) 4575 return EvaluateTemporary(Object, This, Info); 4576 4577 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4578 return false; 4579 } 4580 4581 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4582 /// lvalue referring to the result. 4583 /// 4584 /// \param Info - Information about the ongoing evaluation. 4585 /// \param LV - An lvalue referring to the base of the member pointer. 4586 /// \param RHS - The member pointer expression. 4587 /// \param IncludeMember - Specifies whether the member itself is included in 4588 /// the resulting LValue subobject designator. This is not possible when 4589 /// creating a bound member function. 4590 /// \return The field or method declaration to which the member pointer refers, 4591 /// or 0 if evaluation fails. 4592 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4593 QualType LVType, 4594 LValue &LV, 4595 const Expr *RHS, 4596 bool IncludeMember = true) { 4597 MemberPtr MemPtr; 4598 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4599 return nullptr; 4600 4601 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4602 // member value, the behavior is undefined. 4603 if (!MemPtr.getDecl()) { 4604 // FIXME: Specific diagnostic. 4605 Info.FFDiag(RHS); 4606 return nullptr; 4607 } 4608 4609 if (MemPtr.isDerivedMember()) { 4610 // This is a member of some derived class. Truncate LV appropriately. 4611 // The end of the derived-to-base path for the base object must match the 4612 // derived-to-base path for the member pointer. 4613 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4614 LV.Designator.Entries.size()) { 4615 Info.FFDiag(RHS); 4616 return nullptr; 4617 } 4618 unsigned PathLengthToMember = 4619 LV.Designator.Entries.size() - MemPtr.Path.size(); 4620 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4621 const CXXRecordDecl *LVDecl = getAsBaseClass( 4622 LV.Designator.Entries[PathLengthToMember + I]); 4623 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4624 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4625 Info.FFDiag(RHS); 4626 return nullptr; 4627 } 4628 } 4629 4630 // Truncate the lvalue to the appropriate derived class. 4631 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4632 PathLengthToMember)) 4633 return nullptr; 4634 } else if (!MemPtr.Path.empty()) { 4635 // Extend the LValue path with the member pointer's path. 4636 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4637 MemPtr.Path.size() + IncludeMember); 4638 4639 // Walk down to the appropriate base class. 4640 if (const PointerType *PT = LVType->getAs<PointerType>()) 4641 LVType = PT->getPointeeType(); 4642 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4643 assert(RD && "member pointer access on non-class-type expression"); 4644 // The first class in the path is that of the lvalue. 4645 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4646 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4647 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4648 return nullptr; 4649 RD = Base; 4650 } 4651 // Finally cast to the class containing the member. 4652 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4653 MemPtr.getContainingRecord())) 4654 return nullptr; 4655 } 4656 4657 // Add the member. Note that we cannot build bound member functions here. 4658 if (IncludeMember) { 4659 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4660 if (!HandleLValueMember(Info, RHS, LV, FD)) 4661 return nullptr; 4662 } else if (const IndirectFieldDecl *IFD = 4663 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4664 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4665 return nullptr; 4666 } else { 4667 llvm_unreachable("can't construct reference to bound member function"); 4668 } 4669 } 4670 4671 return MemPtr.getDecl(); 4672 } 4673 4674 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4675 const BinaryOperator *BO, 4676 LValue &LV, 4677 bool IncludeMember = true) { 4678 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4679 4680 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4681 if (Info.noteFailure()) { 4682 MemberPtr MemPtr; 4683 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4684 } 4685 return nullptr; 4686 } 4687 4688 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4689 BO->getRHS(), IncludeMember); 4690 } 4691 4692 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4693 /// the provided lvalue, which currently refers to the base object. 4694 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4695 LValue &Result) { 4696 SubobjectDesignator &D = Result.Designator; 4697 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4698 return false; 4699 4700 QualType TargetQT = E->getType(); 4701 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4702 TargetQT = PT->getPointeeType(); 4703 4704 // Check this cast lands within the final derived-to-base subobject path. 4705 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4706 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4707 << D.MostDerivedType << TargetQT; 4708 return false; 4709 } 4710 4711 // Check the type of the final cast. We don't need to check the path, 4712 // since a cast can only be formed if the path is unique. 4713 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4714 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4715 const CXXRecordDecl *FinalType; 4716 if (NewEntriesSize == D.MostDerivedPathLength) 4717 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4718 else 4719 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4720 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4721 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4722 << D.MostDerivedType << TargetQT; 4723 return false; 4724 } 4725 4726 // Truncate the lvalue to the appropriate derived class. 4727 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4728 } 4729 4730 /// Get the value to use for a default-initialized object of type T. 4731 /// Return false if it encounters something invalid. 4732 static bool getDefaultInitValue(QualType T, APValue &Result) { 4733 bool Success = true; 4734 if (auto *RD = T->getAsCXXRecordDecl()) { 4735 if (RD->isInvalidDecl()) { 4736 Result = APValue(); 4737 return false; 4738 } 4739 if (RD->isUnion()) { 4740 Result = APValue((const FieldDecl *)nullptr); 4741 return true; 4742 } 4743 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4744 std::distance(RD->field_begin(), RD->field_end())); 4745 4746 unsigned Index = 0; 4747 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4748 End = RD->bases_end(); 4749 I != End; ++I, ++Index) 4750 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4751 4752 for (const auto *I : RD->fields()) { 4753 if (I->isUnnamedBitfield()) 4754 continue; 4755 Success &= getDefaultInitValue(I->getType(), 4756 Result.getStructField(I->getFieldIndex())); 4757 } 4758 return Success; 4759 } 4760 4761 if (auto *AT = 4762 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4763 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4764 if (Result.hasArrayFiller()) 4765 Success &= 4766 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4767 4768 return Success; 4769 } 4770 4771 Result = APValue::IndeterminateValue(); 4772 return true; 4773 } 4774 4775 namespace { 4776 enum EvalStmtResult { 4777 /// Evaluation failed. 4778 ESR_Failed, 4779 /// Hit a 'return' statement. 4780 ESR_Returned, 4781 /// Evaluation succeeded. 4782 ESR_Succeeded, 4783 /// Hit a 'continue' statement. 4784 ESR_Continue, 4785 /// Hit a 'break' statement. 4786 ESR_Break, 4787 /// Still scanning for 'case' or 'default' statement. 4788 ESR_CaseNotFound 4789 }; 4790 } 4791 4792 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4793 // We don't need to evaluate the initializer for a static local. 4794 if (!VD->hasLocalStorage()) 4795 return true; 4796 4797 LValue Result; 4798 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4799 ScopeKind::Block, Result); 4800 4801 const Expr *InitE = VD->getInit(); 4802 if (!InitE) { 4803 if (VD->getType()->isDependentType()) 4804 return Info.noteSideEffect(); 4805 return getDefaultInitValue(VD->getType(), Val); 4806 } 4807 if (InitE->isValueDependent()) 4808 return false; 4809 4810 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4811 // Wipe out any partially-computed value, to allow tracking that this 4812 // evaluation failed. 4813 Val = APValue(); 4814 return false; 4815 } 4816 4817 return true; 4818 } 4819 4820 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4821 bool OK = true; 4822 4823 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4824 OK &= EvaluateVarDecl(Info, VD); 4825 4826 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4827 for (auto *BD : DD->bindings()) 4828 if (auto *VD = BD->getHoldingVar()) 4829 OK &= EvaluateDecl(Info, VD); 4830 4831 return OK; 4832 } 4833 4834 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4835 assert(E->isValueDependent()); 4836 if (Info.noteSideEffect()) 4837 return true; 4838 assert(E->containsErrors() && "valid value-dependent expression should never " 4839 "reach invalid code path."); 4840 return false; 4841 } 4842 4843 /// Evaluate a condition (either a variable declaration or an expression). 4844 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4845 const Expr *Cond, bool &Result) { 4846 if (Cond->isValueDependent()) 4847 return false; 4848 FullExpressionRAII Scope(Info); 4849 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4850 return false; 4851 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4852 return false; 4853 return Scope.destroy(); 4854 } 4855 4856 namespace { 4857 /// A location where the result (returned value) of evaluating a 4858 /// statement should be stored. 4859 struct StmtResult { 4860 /// The APValue that should be filled in with the returned value. 4861 APValue &Value; 4862 /// The location containing the result, if any (used to support RVO). 4863 const LValue *Slot; 4864 }; 4865 4866 struct TempVersionRAII { 4867 CallStackFrame &Frame; 4868 4869 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4870 Frame.pushTempVersion(); 4871 } 4872 4873 ~TempVersionRAII() { 4874 Frame.popTempVersion(); 4875 } 4876 }; 4877 4878 } 4879 4880 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4881 const Stmt *S, 4882 const SwitchCase *SC = nullptr); 4883 4884 /// Evaluate the body of a loop, and translate the result as appropriate. 4885 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4886 const Stmt *Body, 4887 const SwitchCase *Case = nullptr) { 4888 BlockScopeRAII Scope(Info); 4889 4890 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4891 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4892 ESR = ESR_Failed; 4893 4894 switch (ESR) { 4895 case ESR_Break: 4896 return ESR_Succeeded; 4897 case ESR_Succeeded: 4898 case ESR_Continue: 4899 return ESR_Continue; 4900 case ESR_Failed: 4901 case ESR_Returned: 4902 case ESR_CaseNotFound: 4903 return ESR; 4904 } 4905 llvm_unreachable("Invalid EvalStmtResult!"); 4906 } 4907 4908 /// Evaluate a switch statement. 4909 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4910 const SwitchStmt *SS) { 4911 BlockScopeRAII Scope(Info); 4912 4913 // Evaluate the switch condition. 4914 APSInt Value; 4915 { 4916 if (const Stmt *Init = SS->getInit()) { 4917 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4918 if (ESR != ESR_Succeeded) { 4919 if (ESR != ESR_Failed && !Scope.destroy()) 4920 ESR = ESR_Failed; 4921 return ESR; 4922 } 4923 } 4924 4925 FullExpressionRAII CondScope(Info); 4926 if (SS->getConditionVariable() && 4927 !EvaluateDecl(Info, SS->getConditionVariable())) 4928 return ESR_Failed; 4929 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4930 return ESR_Failed; 4931 if (!CondScope.destroy()) 4932 return ESR_Failed; 4933 } 4934 4935 // Find the switch case corresponding to the value of the condition. 4936 // FIXME: Cache this lookup. 4937 const SwitchCase *Found = nullptr; 4938 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4939 SC = SC->getNextSwitchCase()) { 4940 if (isa<DefaultStmt>(SC)) { 4941 Found = SC; 4942 continue; 4943 } 4944 4945 const CaseStmt *CS = cast<CaseStmt>(SC); 4946 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4947 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4948 : LHS; 4949 if (LHS <= Value && Value <= RHS) { 4950 Found = SC; 4951 break; 4952 } 4953 } 4954 4955 if (!Found) 4956 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4957 4958 // Search the switch body for the switch case and evaluate it from there. 4959 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4960 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4961 return ESR_Failed; 4962 4963 switch (ESR) { 4964 case ESR_Break: 4965 return ESR_Succeeded; 4966 case ESR_Succeeded: 4967 case ESR_Continue: 4968 case ESR_Failed: 4969 case ESR_Returned: 4970 return ESR; 4971 case ESR_CaseNotFound: 4972 // This can only happen if the switch case is nested within a statement 4973 // expression. We have no intention of supporting that. 4974 Info.FFDiag(Found->getBeginLoc(), 4975 diag::note_constexpr_stmt_expr_unsupported); 4976 return ESR_Failed; 4977 } 4978 llvm_unreachable("Invalid EvalStmtResult!"); 4979 } 4980 4981 // Evaluate a statement. 4982 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4983 const Stmt *S, const SwitchCase *Case) { 4984 if (!Info.nextStep(S)) 4985 return ESR_Failed; 4986 4987 // If we're hunting down a 'case' or 'default' label, recurse through 4988 // substatements until we hit the label. 4989 if (Case) { 4990 switch (S->getStmtClass()) { 4991 case Stmt::CompoundStmtClass: 4992 // FIXME: Precompute which substatement of a compound statement we 4993 // would jump to, and go straight there rather than performing a 4994 // linear scan each time. 4995 case Stmt::LabelStmtClass: 4996 case Stmt::AttributedStmtClass: 4997 case Stmt::DoStmtClass: 4998 break; 4999 5000 case Stmt::CaseStmtClass: 5001 case Stmt::DefaultStmtClass: 5002 if (Case == S) 5003 Case = nullptr; 5004 break; 5005 5006 case Stmt::IfStmtClass: { 5007 // FIXME: Precompute which side of an 'if' we would jump to, and go 5008 // straight there rather than scanning both sides. 5009 const IfStmt *IS = cast<IfStmt>(S); 5010 5011 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5012 // preceded by our switch label. 5013 BlockScopeRAII Scope(Info); 5014 5015 // Step into the init statement in case it brings an (uninitialized) 5016 // variable into scope. 5017 if (const Stmt *Init = IS->getInit()) { 5018 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5019 if (ESR != ESR_CaseNotFound) { 5020 assert(ESR != ESR_Succeeded); 5021 return ESR; 5022 } 5023 } 5024 5025 // Condition variable must be initialized if it exists. 5026 // FIXME: We can skip evaluating the body if there's a condition 5027 // variable, as there can't be any case labels within it. 5028 // (The same is true for 'for' statements.) 5029 5030 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5031 if (ESR == ESR_Failed) 5032 return ESR; 5033 if (ESR != ESR_CaseNotFound) 5034 return Scope.destroy() ? ESR : ESR_Failed; 5035 if (!IS->getElse()) 5036 return ESR_CaseNotFound; 5037 5038 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5039 if (ESR == ESR_Failed) 5040 return ESR; 5041 if (ESR != ESR_CaseNotFound) 5042 return Scope.destroy() ? ESR : ESR_Failed; 5043 return ESR_CaseNotFound; 5044 } 5045 5046 case Stmt::WhileStmtClass: { 5047 EvalStmtResult ESR = 5048 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5049 if (ESR != ESR_Continue) 5050 return ESR; 5051 break; 5052 } 5053 5054 case Stmt::ForStmtClass: { 5055 const ForStmt *FS = cast<ForStmt>(S); 5056 BlockScopeRAII Scope(Info); 5057 5058 // Step into the init statement in case it brings an (uninitialized) 5059 // variable into scope. 5060 if (const Stmt *Init = FS->getInit()) { 5061 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5062 if (ESR != ESR_CaseNotFound) { 5063 assert(ESR != ESR_Succeeded); 5064 return ESR; 5065 } 5066 } 5067 5068 EvalStmtResult ESR = 5069 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5070 if (ESR != ESR_Continue) 5071 return ESR; 5072 if (const auto *Inc = FS->getInc()) { 5073 if (Inc->isValueDependent()) { 5074 if (!EvaluateDependentExpr(Inc, Info)) 5075 return ESR_Failed; 5076 } else { 5077 FullExpressionRAII IncScope(Info); 5078 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5079 return ESR_Failed; 5080 } 5081 } 5082 break; 5083 } 5084 5085 case Stmt::DeclStmtClass: { 5086 // Start the lifetime of any uninitialized variables we encounter. They 5087 // might be used by the selected branch of the switch. 5088 const DeclStmt *DS = cast<DeclStmt>(S); 5089 for (const auto *D : DS->decls()) { 5090 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5091 if (VD->hasLocalStorage() && !VD->getInit()) 5092 if (!EvaluateVarDecl(Info, VD)) 5093 return ESR_Failed; 5094 // FIXME: If the variable has initialization that can't be jumped 5095 // over, bail out of any immediately-surrounding compound-statement 5096 // too. There can't be any case labels here. 5097 } 5098 } 5099 return ESR_CaseNotFound; 5100 } 5101 5102 default: 5103 return ESR_CaseNotFound; 5104 } 5105 } 5106 5107 switch (S->getStmtClass()) { 5108 default: 5109 if (const Expr *E = dyn_cast<Expr>(S)) { 5110 if (E->isValueDependent()) { 5111 if (!EvaluateDependentExpr(E, Info)) 5112 return ESR_Failed; 5113 } else { 5114 // Don't bother evaluating beyond an expression-statement which couldn't 5115 // be evaluated. 5116 // FIXME: Do we need the FullExpressionRAII object here? 5117 // VisitExprWithCleanups should create one when necessary. 5118 FullExpressionRAII Scope(Info); 5119 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5120 return ESR_Failed; 5121 } 5122 return ESR_Succeeded; 5123 } 5124 5125 Info.FFDiag(S->getBeginLoc()); 5126 return ESR_Failed; 5127 5128 case Stmt::NullStmtClass: 5129 return ESR_Succeeded; 5130 5131 case Stmt::DeclStmtClass: { 5132 const DeclStmt *DS = cast<DeclStmt>(S); 5133 for (const auto *D : DS->decls()) { 5134 // Each declaration initialization is its own full-expression. 5135 FullExpressionRAII Scope(Info); 5136 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5137 return ESR_Failed; 5138 if (!Scope.destroy()) 5139 return ESR_Failed; 5140 } 5141 return ESR_Succeeded; 5142 } 5143 5144 case Stmt::ReturnStmtClass: { 5145 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5146 FullExpressionRAII Scope(Info); 5147 if (RetExpr && RetExpr->isValueDependent()) { 5148 EvaluateDependentExpr(RetExpr, Info); 5149 // We know we returned, but we don't know what the value is. 5150 return ESR_Failed; 5151 } 5152 if (RetExpr && 5153 !(Result.Slot 5154 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5155 : Evaluate(Result.Value, Info, RetExpr))) 5156 return ESR_Failed; 5157 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5158 } 5159 5160 case Stmt::CompoundStmtClass: { 5161 BlockScopeRAII Scope(Info); 5162 5163 const CompoundStmt *CS = cast<CompoundStmt>(S); 5164 for (const auto *BI : CS->body()) { 5165 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5166 if (ESR == ESR_Succeeded) 5167 Case = nullptr; 5168 else if (ESR != ESR_CaseNotFound) { 5169 if (ESR != ESR_Failed && !Scope.destroy()) 5170 return ESR_Failed; 5171 return ESR; 5172 } 5173 } 5174 if (Case) 5175 return ESR_CaseNotFound; 5176 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5177 } 5178 5179 case Stmt::IfStmtClass: { 5180 const IfStmt *IS = cast<IfStmt>(S); 5181 5182 // Evaluate the condition, as either a var decl or as an expression. 5183 BlockScopeRAII Scope(Info); 5184 if (const Stmt *Init = IS->getInit()) { 5185 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5186 if (ESR != ESR_Succeeded) { 5187 if (ESR != ESR_Failed && !Scope.destroy()) 5188 return ESR_Failed; 5189 return ESR; 5190 } 5191 } 5192 bool Cond; 5193 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5194 return ESR_Failed; 5195 5196 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5197 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5198 if (ESR != ESR_Succeeded) { 5199 if (ESR != ESR_Failed && !Scope.destroy()) 5200 return ESR_Failed; 5201 return ESR; 5202 } 5203 } 5204 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5205 } 5206 5207 case Stmt::WhileStmtClass: { 5208 const WhileStmt *WS = cast<WhileStmt>(S); 5209 while (true) { 5210 BlockScopeRAII Scope(Info); 5211 bool Continue; 5212 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5213 Continue)) 5214 return ESR_Failed; 5215 if (!Continue) 5216 break; 5217 5218 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5219 if (ESR != ESR_Continue) { 5220 if (ESR != ESR_Failed && !Scope.destroy()) 5221 return ESR_Failed; 5222 return ESR; 5223 } 5224 if (!Scope.destroy()) 5225 return ESR_Failed; 5226 } 5227 return ESR_Succeeded; 5228 } 5229 5230 case Stmt::DoStmtClass: { 5231 const DoStmt *DS = cast<DoStmt>(S); 5232 bool Continue; 5233 do { 5234 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5235 if (ESR != ESR_Continue) 5236 return ESR; 5237 Case = nullptr; 5238 5239 if (DS->getCond()->isValueDependent()) { 5240 EvaluateDependentExpr(DS->getCond(), Info); 5241 // Bailout as we don't know whether to keep going or terminate the loop. 5242 return ESR_Failed; 5243 } 5244 FullExpressionRAII CondScope(Info); 5245 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5246 !CondScope.destroy()) 5247 return ESR_Failed; 5248 } while (Continue); 5249 return ESR_Succeeded; 5250 } 5251 5252 case Stmt::ForStmtClass: { 5253 const ForStmt *FS = cast<ForStmt>(S); 5254 BlockScopeRAII ForScope(Info); 5255 if (FS->getInit()) { 5256 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5257 if (ESR != ESR_Succeeded) { 5258 if (ESR != ESR_Failed && !ForScope.destroy()) 5259 return ESR_Failed; 5260 return ESR; 5261 } 5262 } 5263 while (true) { 5264 BlockScopeRAII IterScope(Info); 5265 bool Continue = true; 5266 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5267 FS->getCond(), Continue)) 5268 return ESR_Failed; 5269 if (!Continue) 5270 break; 5271 5272 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5273 if (ESR != ESR_Continue) { 5274 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5275 return ESR_Failed; 5276 return ESR; 5277 } 5278 5279 if (const auto *Inc = FS->getInc()) { 5280 if (Inc->isValueDependent()) { 5281 if (!EvaluateDependentExpr(Inc, Info)) 5282 return ESR_Failed; 5283 } else { 5284 FullExpressionRAII IncScope(Info); 5285 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5286 return ESR_Failed; 5287 } 5288 } 5289 5290 if (!IterScope.destroy()) 5291 return ESR_Failed; 5292 } 5293 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5294 } 5295 5296 case Stmt::CXXForRangeStmtClass: { 5297 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5298 BlockScopeRAII Scope(Info); 5299 5300 // Evaluate the init-statement if present. 5301 if (FS->getInit()) { 5302 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5303 if (ESR != ESR_Succeeded) { 5304 if (ESR != ESR_Failed && !Scope.destroy()) 5305 return ESR_Failed; 5306 return ESR; 5307 } 5308 } 5309 5310 // Initialize the __range variable. 5311 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5312 if (ESR != ESR_Succeeded) { 5313 if (ESR != ESR_Failed && !Scope.destroy()) 5314 return ESR_Failed; 5315 return ESR; 5316 } 5317 5318 // Create the __begin and __end iterators. 5319 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5320 if (ESR != ESR_Succeeded) { 5321 if (ESR != ESR_Failed && !Scope.destroy()) 5322 return ESR_Failed; 5323 return ESR; 5324 } 5325 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5326 if (ESR != ESR_Succeeded) { 5327 if (ESR != ESR_Failed && !Scope.destroy()) 5328 return ESR_Failed; 5329 return ESR; 5330 } 5331 5332 while (true) { 5333 // Condition: __begin != __end. 5334 { 5335 if (FS->getCond()->isValueDependent()) { 5336 EvaluateDependentExpr(FS->getCond(), Info); 5337 // We don't know whether to keep going or terminate the loop. 5338 return ESR_Failed; 5339 } 5340 bool Continue = true; 5341 FullExpressionRAII CondExpr(Info); 5342 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5343 return ESR_Failed; 5344 if (!Continue) 5345 break; 5346 } 5347 5348 // User's variable declaration, initialized by *__begin. 5349 BlockScopeRAII InnerScope(Info); 5350 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5351 if (ESR != ESR_Succeeded) { 5352 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5353 return ESR_Failed; 5354 return ESR; 5355 } 5356 5357 // Loop body. 5358 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5359 if (ESR != ESR_Continue) { 5360 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5361 return ESR_Failed; 5362 return ESR; 5363 } 5364 if (FS->getInc()->isValueDependent()) { 5365 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5366 return ESR_Failed; 5367 } else { 5368 // Increment: ++__begin 5369 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5370 return ESR_Failed; 5371 } 5372 5373 if (!InnerScope.destroy()) 5374 return ESR_Failed; 5375 } 5376 5377 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5378 } 5379 5380 case Stmt::SwitchStmtClass: 5381 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5382 5383 case Stmt::ContinueStmtClass: 5384 return ESR_Continue; 5385 5386 case Stmt::BreakStmtClass: 5387 return ESR_Break; 5388 5389 case Stmt::LabelStmtClass: 5390 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5391 5392 case Stmt::AttributedStmtClass: 5393 // As a general principle, C++11 attributes can be ignored without 5394 // any semantic impact. 5395 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5396 Case); 5397 5398 case Stmt::CaseStmtClass: 5399 case Stmt::DefaultStmtClass: 5400 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5401 case Stmt::CXXTryStmtClass: 5402 // Evaluate try blocks by evaluating all sub statements. 5403 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5404 } 5405 } 5406 5407 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5408 /// default constructor. If so, we'll fold it whether or not it's marked as 5409 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5410 /// so we need special handling. 5411 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5412 const CXXConstructorDecl *CD, 5413 bool IsValueInitialization) { 5414 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5415 return false; 5416 5417 // Value-initialization does not call a trivial default constructor, so such a 5418 // call is a core constant expression whether or not the constructor is 5419 // constexpr. 5420 if (!CD->isConstexpr() && !IsValueInitialization) { 5421 if (Info.getLangOpts().CPlusPlus11) { 5422 // FIXME: If DiagDecl is an implicitly-declared special member function, 5423 // we should be much more explicit about why it's not constexpr. 5424 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5425 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5426 Info.Note(CD->getLocation(), diag::note_declared_at); 5427 } else { 5428 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5429 } 5430 } 5431 return true; 5432 } 5433 5434 /// CheckConstexprFunction - Check that a function can be called in a constant 5435 /// expression. 5436 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5437 const FunctionDecl *Declaration, 5438 const FunctionDecl *Definition, 5439 const Stmt *Body) { 5440 // Potential constant expressions can contain calls to declared, but not yet 5441 // defined, constexpr functions. 5442 if (Info.checkingPotentialConstantExpression() && !Definition && 5443 Declaration->isConstexpr()) 5444 return false; 5445 5446 // Bail out if the function declaration itself is invalid. We will 5447 // have produced a relevant diagnostic while parsing it, so just 5448 // note the problematic sub-expression. 5449 if (Declaration->isInvalidDecl()) { 5450 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5451 return false; 5452 } 5453 5454 // DR1872: An instantiated virtual constexpr function can't be called in a 5455 // constant expression (prior to C++20). We can still constant-fold such a 5456 // call. 5457 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5458 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5459 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5460 5461 if (Definition && Definition->isInvalidDecl()) { 5462 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5463 return false; 5464 } 5465 5466 // Can we evaluate this function call? 5467 if (Definition && Definition->isConstexpr() && Body) 5468 return true; 5469 5470 if (Info.getLangOpts().CPlusPlus11) { 5471 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5472 5473 // If this function is not constexpr because it is an inherited 5474 // non-constexpr constructor, diagnose that directly. 5475 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5476 if (CD && CD->isInheritingConstructor()) { 5477 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5478 if (!Inherited->isConstexpr()) 5479 DiagDecl = CD = Inherited; 5480 } 5481 5482 // FIXME: If DiagDecl is an implicitly-declared special member function 5483 // or an inheriting constructor, we should be much more explicit about why 5484 // it's not constexpr. 5485 if (CD && CD->isInheritingConstructor()) 5486 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5487 << CD->getInheritedConstructor().getConstructor()->getParent(); 5488 else 5489 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5490 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5491 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5492 } else { 5493 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5494 } 5495 return false; 5496 } 5497 5498 namespace { 5499 struct CheckDynamicTypeHandler { 5500 AccessKinds AccessKind; 5501 typedef bool result_type; 5502 bool failed() { return false; } 5503 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5504 bool found(APSInt &Value, QualType SubobjType) { return true; } 5505 bool found(APFloat &Value, QualType SubobjType) { return true; } 5506 }; 5507 } // end anonymous namespace 5508 5509 /// Check that we can access the notional vptr of an object / determine its 5510 /// dynamic type. 5511 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5512 AccessKinds AK, bool Polymorphic) { 5513 if (This.Designator.Invalid) 5514 return false; 5515 5516 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5517 5518 if (!Obj) 5519 return false; 5520 5521 if (!Obj.Value) { 5522 // The object is not usable in constant expressions, so we can't inspect 5523 // its value to see if it's in-lifetime or what the active union members 5524 // are. We can still check for a one-past-the-end lvalue. 5525 if (This.Designator.isOnePastTheEnd() || 5526 This.Designator.isMostDerivedAnUnsizedArray()) { 5527 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5528 ? diag::note_constexpr_access_past_end 5529 : diag::note_constexpr_access_unsized_array) 5530 << AK; 5531 return false; 5532 } else if (Polymorphic) { 5533 // Conservatively refuse to perform a polymorphic operation if we would 5534 // not be able to read a notional 'vptr' value. 5535 APValue Val; 5536 This.moveInto(Val); 5537 QualType StarThisType = 5538 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5539 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5540 << AK << Val.getAsString(Info.Ctx, StarThisType); 5541 return false; 5542 } 5543 return true; 5544 } 5545 5546 CheckDynamicTypeHandler Handler{AK}; 5547 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5548 } 5549 5550 /// Check that the pointee of the 'this' pointer in a member function call is 5551 /// either within its lifetime or in its period of construction or destruction. 5552 static bool 5553 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5554 const LValue &This, 5555 const CXXMethodDecl *NamedMember) { 5556 return checkDynamicType( 5557 Info, E, This, 5558 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5559 } 5560 5561 struct DynamicType { 5562 /// The dynamic class type of the object. 5563 const CXXRecordDecl *Type; 5564 /// The corresponding path length in the lvalue. 5565 unsigned PathLength; 5566 }; 5567 5568 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5569 unsigned PathLength) { 5570 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5571 Designator.Entries.size() && "invalid path length"); 5572 return (PathLength == Designator.MostDerivedPathLength) 5573 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5574 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5575 } 5576 5577 /// Determine the dynamic type of an object. 5578 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5579 LValue &This, AccessKinds AK) { 5580 // If we don't have an lvalue denoting an object of class type, there is no 5581 // meaningful dynamic type. (We consider objects of non-class type to have no 5582 // dynamic type.) 5583 if (!checkDynamicType(Info, E, This, AK, true)) 5584 return None; 5585 5586 // Refuse to compute a dynamic type in the presence of virtual bases. This 5587 // shouldn't happen other than in constant-folding situations, since literal 5588 // types can't have virtual bases. 5589 // 5590 // Note that consumers of DynamicType assume that the type has no virtual 5591 // bases, and will need modifications if this restriction is relaxed. 5592 const CXXRecordDecl *Class = 5593 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5594 if (!Class || Class->getNumVBases()) { 5595 Info.FFDiag(E); 5596 return None; 5597 } 5598 5599 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5600 // binary search here instead. But the overwhelmingly common case is that 5601 // we're not in the middle of a constructor, so it probably doesn't matter 5602 // in practice. 5603 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5604 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5605 PathLength <= Path.size(); ++PathLength) { 5606 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5607 Path.slice(0, PathLength))) { 5608 case ConstructionPhase::Bases: 5609 case ConstructionPhase::DestroyingBases: 5610 // We're constructing or destroying a base class. This is not the dynamic 5611 // type. 5612 break; 5613 5614 case ConstructionPhase::None: 5615 case ConstructionPhase::AfterBases: 5616 case ConstructionPhase::AfterFields: 5617 case ConstructionPhase::Destroying: 5618 // We've finished constructing the base classes and not yet started 5619 // destroying them again, so this is the dynamic type. 5620 return DynamicType{getBaseClassType(This.Designator, PathLength), 5621 PathLength}; 5622 } 5623 } 5624 5625 // CWG issue 1517: we're constructing a base class of the object described by 5626 // 'This', so that object has not yet begun its period of construction and 5627 // any polymorphic operation on it results in undefined behavior. 5628 Info.FFDiag(E); 5629 return None; 5630 } 5631 5632 /// Perform virtual dispatch. 5633 static const CXXMethodDecl *HandleVirtualDispatch( 5634 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5635 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5636 Optional<DynamicType> DynType = ComputeDynamicType( 5637 Info, E, This, 5638 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5639 if (!DynType) 5640 return nullptr; 5641 5642 // Find the final overrider. It must be declared in one of the classes on the 5643 // path from the dynamic type to the static type. 5644 // FIXME: If we ever allow literal types to have virtual base classes, that 5645 // won't be true. 5646 const CXXMethodDecl *Callee = Found; 5647 unsigned PathLength = DynType->PathLength; 5648 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5649 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5650 const CXXMethodDecl *Overrider = 5651 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5652 if (Overrider) { 5653 Callee = Overrider; 5654 break; 5655 } 5656 } 5657 5658 // C++2a [class.abstract]p6: 5659 // the effect of making a virtual call to a pure virtual function [...] is 5660 // undefined 5661 if (Callee->isPure()) { 5662 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5663 Info.Note(Callee->getLocation(), diag::note_declared_at); 5664 return nullptr; 5665 } 5666 5667 // If necessary, walk the rest of the path to determine the sequence of 5668 // covariant adjustment steps to apply. 5669 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5670 Found->getReturnType())) { 5671 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5672 for (unsigned CovariantPathLength = PathLength + 1; 5673 CovariantPathLength != This.Designator.Entries.size(); 5674 ++CovariantPathLength) { 5675 const CXXRecordDecl *NextClass = 5676 getBaseClassType(This.Designator, CovariantPathLength); 5677 const CXXMethodDecl *Next = 5678 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5679 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5680 Next->getReturnType(), CovariantAdjustmentPath.back())) 5681 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5682 } 5683 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5684 CovariantAdjustmentPath.back())) 5685 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5686 } 5687 5688 // Perform 'this' adjustment. 5689 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5690 return nullptr; 5691 5692 return Callee; 5693 } 5694 5695 /// Perform the adjustment from a value returned by a virtual function to 5696 /// a value of the statically expected type, which may be a pointer or 5697 /// reference to a base class of the returned type. 5698 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5699 APValue &Result, 5700 ArrayRef<QualType> Path) { 5701 assert(Result.isLValue() && 5702 "unexpected kind of APValue for covariant return"); 5703 if (Result.isNullPointer()) 5704 return true; 5705 5706 LValue LVal; 5707 LVal.setFrom(Info.Ctx, Result); 5708 5709 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5710 for (unsigned I = 1; I != Path.size(); ++I) { 5711 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5712 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5713 if (OldClass != NewClass && 5714 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5715 return false; 5716 OldClass = NewClass; 5717 } 5718 5719 LVal.moveInto(Result); 5720 return true; 5721 } 5722 5723 /// Determine whether \p Base, which is known to be a direct base class of 5724 /// \p Derived, is a public base class. 5725 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5726 const CXXRecordDecl *Base) { 5727 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5728 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5729 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5730 return BaseSpec.getAccessSpecifier() == AS_public; 5731 } 5732 llvm_unreachable("Base is not a direct base of Derived"); 5733 } 5734 5735 /// Apply the given dynamic cast operation on the provided lvalue. 5736 /// 5737 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5738 /// to find a suitable target subobject. 5739 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5740 LValue &Ptr) { 5741 // We can't do anything with a non-symbolic pointer value. 5742 SubobjectDesignator &D = Ptr.Designator; 5743 if (D.Invalid) 5744 return false; 5745 5746 // C++ [expr.dynamic.cast]p6: 5747 // If v is a null pointer value, the result is a null pointer value. 5748 if (Ptr.isNullPointer() && !E->isGLValue()) 5749 return true; 5750 5751 // For all the other cases, we need the pointer to point to an object within 5752 // its lifetime / period of construction / destruction, and we need to know 5753 // its dynamic type. 5754 Optional<DynamicType> DynType = 5755 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5756 if (!DynType) 5757 return false; 5758 5759 // C++ [expr.dynamic.cast]p7: 5760 // If T is "pointer to cv void", then the result is a pointer to the most 5761 // derived object 5762 if (E->getType()->isVoidPointerType()) 5763 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5764 5765 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5766 assert(C && "dynamic_cast target is not void pointer nor class"); 5767 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5768 5769 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5770 // C++ [expr.dynamic.cast]p9: 5771 if (!E->isGLValue()) { 5772 // The value of a failed cast to pointer type is the null pointer value 5773 // of the required result type. 5774 Ptr.setNull(Info.Ctx, E->getType()); 5775 return true; 5776 } 5777 5778 // A failed cast to reference type throws [...] std::bad_cast. 5779 unsigned DiagKind; 5780 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5781 DynType->Type->isDerivedFrom(C))) 5782 DiagKind = 0; 5783 else if (!Paths || Paths->begin() == Paths->end()) 5784 DiagKind = 1; 5785 else if (Paths->isAmbiguous(CQT)) 5786 DiagKind = 2; 5787 else { 5788 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5789 DiagKind = 3; 5790 } 5791 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5792 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5793 << Info.Ctx.getRecordType(DynType->Type) 5794 << E->getType().getUnqualifiedType(); 5795 return false; 5796 }; 5797 5798 // Runtime check, phase 1: 5799 // Walk from the base subobject towards the derived object looking for the 5800 // target type. 5801 for (int PathLength = Ptr.Designator.Entries.size(); 5802 PathLength >= (int)DynType->PathLength; --PathLength) { 5803 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5804 if (declaresSameEntity(Class, C)) 5805 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5806 // We can only walk across public inheritance edges. 5807 if (PathLength > (int)DynType->PathLength && 5808 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5809 Class)) 5810 return RuntimeCheckFailed(nullptr); 5811 } 5812 5813 // Runtime check, phase 2: 5814 // Search the dynamic type for an unambiguous public base of type C. 5815 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5816 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5817 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5818 Paths.front().Access == AS_public) { 5819 // Downcast to the dynamic type... 5820 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5821 return false; 5822 // ... then upcast to the chosen base class subobject. 5823 for (CXXBasePathElement &Elem : Paths.front()) 5824 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5825 return false; 5826 return true; 5827 } 5828 5829 // Otherwise, the runtime check fails. 5830 return RuntimeCheckFailed(&Paths); 5831 } 5832 5833 namespace { 5834 struct StartLifetimeOfUnionMemberHandler { 5835 EvalInfo &Info; 5836 const Expr *LHSExpr; 5837 const FieldDecl *Field; 5838 bool DuringInit; 5839 bool Failed = false; 5840 static const AccessKinds AccessKind = AK_Assign; 5841 5842 typedef bool result_type; 5843 bool failed() { return Failed; } 5844 bool found(APValue &Subobj, QualType SubobjType) { 5845 // We are supposed to perform no initialization but begin the lifetime of 5846 // the object. We interpret that as meaning to do what default 5847 // initialization of the object would do if all constructors involved were 5848 // trivial: 5849 // * All base, non-variant member, and array element subobjects' lifetimes 5850 // begin 5851 // * No variant members' lifetimes begin 5852 // * All scalar subobjects whose lifetimes begin have indeterminate values 5853 assert(SubobjType->isUnionType()); 5854 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5855 // This union member is already active. If it's also in-lifetime, there's 5856 // nothing to do. 5857 if (Subobj.getUnionValue().hasValue()) 5858 return true; 5859 } else if (DuringInit) { 5860 // We're currently in the process of initializing a different union 5861 // member. If we carried on, that initialization would attempt to 5862 // store to an inactive union member, resulting in undefined behavior. 5863 Info.FFDiag(LHSExpr, 5864 diag::note_constexpr_union_member_change_during_init); 5865 return false; 5866 } 5867 APValue Result; 5868 Failed = !getDefaultInitValue(Field->getType(), Result); 5869 Subobj.setUnion(Field, Result); 5870 return true; 5871 } 5872 bool found(APSInt &Value, QualType SubobjType) { 5873 llvm_unreachable("wrong value kind for union object"); 5874 } 5875 bool found(APFloat &Value, QualType SubobjType) { 5876 llvm_unreachable("wrong value kind for union object"); 5877 } 5878 }; 5879 } // end anonymous namespace 5880 5881 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5882 5883 /// Handle a builtin simple-assignment or a call to a trivial assignment 5884 /// operator whose left-hand side might involve a union member access. If it 5885 /// does, implicitly start the lifetime of any accessed union elements per 5886 /// C++20 [class.union]5. 5887 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5888 const LValue &LHS) { 5889 if (LHS.InvalidBase || LHS.Designator.Invalid) 5890 return false; 5891 5892 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5893 // C++ [class.union]p5: 5894 // define the set S(E) of subexpressions of E as follows: 5895 unsigned PathLength = LHS.Designator.Entries.size(); 5896 for (const Expr *E = LHSExpr; E != nullptr;) { 5897 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5898 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5899 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5900 // Note that we can't implicitly start the lifetime of a reference, 5901 // so we don't need to proceed any further if we reach one. 5902 if (!FD || FD->getType()->isReferenceType()) 5903 break; 5904 5905 // ... and also contains A.B if B names a union member ... 5906 if (FD->getParent()->isUnion()) { 5907 // ... of a non-class, non-array type, or of a class type with a 5908 // trivial default constructor that is not deleted, or an array of 5909 // such types. 5910 auto *RD = 5911 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5912 if (!RD || RD->hasTrivialDefaultConstructor()) 5913 UnionPathLengths.push_back({PathLength - 1, FD}); 5914 } 5915 5916 E = ME->getBase(); 5917 --PathLength; 5918 assert(declaresSameEntity(FD, 5919 LHS.Designator.Entries[PathLength] 5920 .getAsBaseOrMember().getPointer())); 5921 5922 // -- If E is of the form A[B] and is interpreted as a built-in array 5923 // subscripting operator, S(E) is [S(the array operand, if any)]. 5924 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5925 // Step over an ArrayToPointerDecay implicit cast. 5926 auto *Base = ASE->getBase()->IgnoreImplicit(); 5927 if (!Base->getType()->isArrayType()) 5928 break; 5929 5930 E = Base; 5931 --PathLength; 5932 5933 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5934 // Step over a derived-to-base conversion. 5935 E = ICE->getSubExpr(); 5936 if (ICE->getCastKind() == CK_NoOp) 5937 continue; 5938 if (ICE->getCastKind() != CK_DerivedToBase && 5939 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5940 break; 5941 // Walk path backwards as we walk up from the base to the derived class. 5942 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5943 --PathLength; 5944 (void)Elt; 5945 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5946 LHS.Designator.Entries[PathLength] 5947 .getAsBaseOrMember().getPointer())); 5948 } 5949 5950 // -- Otherwise, S(E) is empty. 5951 } else { 5952 break; 5953 } 5954 } 5955 5956 // Common case: no unions' lifetimes are started. 5957 if (UnionPathLengths.empty()) 5958 return true; 5959 5960 // if modification of X [would access an inactive union member], an object 5961 // of the type of X is implicitly created 5962 CompleteObject Obj = 5963 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5964 if (!Obj) 5965 return false; 5966 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5967 llvm::reverse(UnionPathLengths)) { 5968 // Form a designator for the union object. 5969 SubobjectDesignator D = LHS.Designator; 5970 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5971 5972 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5973 ConstructionPhase::AfterBases; 5974 StartLifetimeOfUnionMemberHandler StartLifetime{ 5975 Info, LHSExpr, LengthAndField.second, DuringInit}; 5976 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5977 return false; 5978 } 5979 5980 return true; 5981 } 5982 5983 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5984 CallRef Call, EvalInfo &Info, 5985 bool NonNull = false) { 5986 LValue LV; 5987 // Create the parameter slot and register its destruction. For a vararg 5988 // argument, create a temporary. 5989 // FIXME: For calling conventions that destroy parameters in the callee, 5990 // should we consider performing destruction when the function returns 5991 // instead? 5992 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5993 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5994 ScopeKind::Call, LV); 5995 if (!EvaluateInPlace(V, Info, LV, Arg)) 5996 return false; 5997 5998 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 5999 // undefined behavior, so is non-constant. 6000 if (NonNull && V.isLValue() && V.isNullPointer()) { 6001 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6002 return false; 6003 } 6004 6005 return true; 6006 } 6007 6008 /// Evaluate the arguments to a function call. 6009 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6010 EvalInfo &Info, const FunctionDecl *Callee, 6011 bool RightToLeft = false) { 6012 bool Success = true; 6013 llvm::SmallBitVector ForbiddenNullArgs; 6014 if (Callee->hasAttr<NonNullAttr>()) { 6015 ForbiddenNullArgs.resize(Args.size()); 6016 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6017 if (!Attr->args_size()) { 6018 ForbiddenNullArgs.set(); 6019 break; 6020 } else 6021 for (auto Idx : Attr->args()) { 6022 unsigned ASTIdx = Idx.getASTIndex(); 6023 if (ASTIdx >= Args.size()) 6024 continue; 6025 ForbiddenNullArgs[ASTIdx] = 1; 6026 } 6027 } 6028 } 6029 for (unsigned I = 0; I < Args.size(); I++) { 6030 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6031 const ParmVarDecl *PVD = 6032 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6033 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6034 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6035 // If we're checking for a potential constant expression, evaluate all 6036 // initializers even if some of them fail. 6037 if (!Info.noteFailure()) 6038 return false; 6039 Success = false; 6040 } 6041 } 6042 return Success; 6043 } 6044 6045 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6046 /// constructor or assignment operator. 6047 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6048 const Expr *E, APValue &Result, 6049 bool CopyObjectRepresentation) { 6050 // Find the reference argument. 6051 CallStackFrame *Frame = Info.CurrentCall; 6052 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6053 if (!RefValue) { 6054 Info.FFDiag(E); 6055 return false; 6056 } 6057 6058 // Copy out the contents of the RHS object. 6059 LValue RefLValue; 6060 RefLValue.setFrom(Info.Ctx, *RefValue); 6061 return handleLValueToRValueConversion( 6062 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6063 CopyObjectRepresentation); 6064 } 6065 6066 /// Evaluate a function call. 6067 static bool HandleFunctionCall(SourceLocation CallLoc, 6068 const FunctionDecl *Callee, const LValue *This, 6069 ArrayRef<const Expr *> Args, CallRef Call, 6070 const Stmt *Body, EvalInfo &Info, 6071 APValue &Result, const LValue *ResultSlot) { 6072 if (!Info.CheckCallLimit(CallLoc)) 6073 return false; 6074 6075 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6076 6077 // For a trivial copy or move assignment, perform an APValue copy. This is 6078 // essential for unions, where the operations performed by the assignment 6079 // operator cannot be represented as statements. 6080 // 6081 // Skip this for non-union classes with no fields; in that case, the defaulted 6082 // copy/move does not actually read the object. 6083 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6084 if (MD && MD->isDefaulted() && 6085 (MD->getParent()->isUnion() || 6086 (MD->isTrivial() && 6087 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6088 assert(This && 6089 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6090 APValue RHSValue; 6091 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6092 MD->getParent()->isUnion())) 6093 return false; 6094 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6095 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6096 return false; 6097 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6098 RHSValue)) 6099 return false; 6100 This->moveInto(Result); 6101 return true; 6102 } else if (MD && isLambdaCallOperator(MD)) { 6103 // We're in a lambda; determine the lambda capture field maps unless we're 6104 // just constexpr checking a lambda's call operator. constexpr checking is 6105 // done before the captures have been added to the closure object (unless 6106 // we're inferring constexpr-ness), so we don't have access to them in this 6107 // case. But since we don't need the captures to constexpr check, we can 6108 // just ignore them. 6109 if (!Info.checkingPotentialConstantExpression()) 6110 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6111 Frame.LambdaThisCaptureField); 6112 } 6113 6114 StmtResult Ret = {Result, ResultSlot}; 6115 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6116 if (ESR == ESR_Succeeded) { 6117 if (Callee->getReturnType()->isVoidType()) 6118 return true; 6119 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6120 } 6121 return ESR == ESR_Returned; 6122 } 6123 6124 /// Evaluate a constructor call. 6125 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6126 CallRef Call, 6127 const CXXConstructorDecl *Definition, 6128 EvalInfo &Info, APValue &Result) { 6129 SourceLocation CallLoc = E->getExprLoc(); 6130 if (!Info.CheckCallLimit(CallLoc)) 6131 return false; 6132 6133 const CXXRecordDecl *RD = Definition->getParent(); 6134 if (RD->getNumVBases()) { 6135 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6136 return false; 6137 } 6138 6139 EvalInfo::EvaluatingConstructorRAII EvalObj( 6140 Info, 6141 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6142 RD->getNumBases()); 6143 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6144 6145 // FIXME: Creating an APValue just to hold a nonexistent return value is 6146 // wasteful. 6147 APValue RetVal; 6148 StmtResult Ret = {RetVal, nullptr}; 6149 6150 // If it's a delegating constructor, delegate. 6151 if (Definition->isDelegatingConstructor()) { 6152 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6153 if ((*I)->getInit()->isValueDependent()) { 6154 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6155 return false; 6156 } else { 6157 FullExpressionRAII InitScope(Info); 6158 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6159 !InitScope.destroy()) 6160 return false; 6161 } 6162 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6163 } 6164 6165 // For a trivial copy or move constructor, perform an APValue copy. This is 6166 // essential for unions (or classes with anonymous union members), where the 6167 // operations performed by the constructor cannot be represented by 6168 // ctor-initializers. 6169 // 6170 // Skip this for empty non-union classes; we should not perform an 6171 // lvalue-to-rvalue conversion on them because their copy constructor does not 6172 // actually read them. 6173 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6174 (Definition->getParent()->isUnion() || 6175 (Definition->isTrivial() && 6176 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6177 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6178 Definition->getParent()->isUnion()); 6179 } 6180 6181 // Reserve space for the struct members. 6182 if (!Result.hasValue()) { 6183 if (!RD->isUnion()) 6184 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6185 std::distance(RD->field_begin(), RD->field_end())); 6186 else 6187 // A union starts with no active member. 6188 Result = APValue((const FieldDecl*)nullptr); 6189 } 6190 6191 if (RD->isInvalidDecl()) return false; 6192 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6193 6194 // A scope for temporaries lifetime-extended by reference members. 6195 BlockScopeRAII LifetimeExtendedScope(Info); 6196 6197 bool Success = true; 6198 unsigned BasesSeen = 0; 6199 #ifndef NDEBUG 6200 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6201 #endif 6202 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6203 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6204 // We might be initializing the same field again if this is an indirect 6205 // field initialization. 6206 if (FieldIt == RD->field_end() || 6207 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6208 assert(Indirect && "fields out of order?"); 6209 return; 6210 } 6211 6212 // Default-initialize any fields with no explicit initializer. 6213 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6214 assert(FieldIt != RD->field_end() && "missing field?"); 6215 if (!FieldIt->isUnnamedBitfield()) 6216 Success &= getDefaultInitValue( 6217 FieldIt->getType(), 6218 Result.getStructField(FieldIt->getFieldIndex())); 6219 } 6220 ++FieldIt; 6221 }; 6222 for (const auto *I : Definition->inits()) { 6223 LValue Subobject = This; 6224 LValue SubobjectParent = This; 6225 APValue *Value = &Result; 6226 6227 // Determine the subobject to initialize. 6228 FieldDecl *FD = nullptr; 6229 if (I->isBaseInitializer()) { 6230 QualType BaseType(I->getBaseClass(), 0); 6231 #ifndef NDEBUG 6232 // Non-virtual base classes are initialized in the order in the class 6233 // definition. We have already checked for virtual base classes. 6234 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6235 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6236 "base class initializers not in expected order"); 6237 ++BaseIt; 6238 #endif 6239 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6240 BaseType->getAsCXXRecordDecl(), &Layout)) 6241 return false; 6242 Value = &Result.getStructBase(BasesSeen++); 6243 } else if ((FD = I->getMember())) { 6244 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6245 return false; 6246 if (RD->isUnion()) { 6247 Result = APValue(FD); 6248 Value = &Result.getUnionValue(); 6249 } else { 6250 SkipToField(FD, false); 6251 Value = &Result.getStructField(FD->getFieldIndex()); 6252 } 6253 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6254 // Walk the indirect field decl's chain to find the object to initialize, 6255 // and make sure we've initialized every step along it. 6256 auto IndirectFieldChain = IFD->chain(); 6257 for (auto *C : IndirectFieldChain) { 6258 FD = cast<FieldDecl>(C); 6259 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6260 // Switch the union field if it differs. This happens if we had 6261 // preceding zero-initialization, and we're now initializing a union 6262 // subobject other than the first. 6263 // FIXME: In this case, the values of the other subobjects are 6264 // specified, since zero-initialization sets all padding bits to zero. 6265 if (!Value->hasValue() || 6266 (Value->isUnion() && Value->getUnionField() != FD)) { 6267 if (CD->isUnion()) 6268 *Value = APValue(FD); 6269 else 6270 // FIXME: This immediately starts the lifetime of all members of 6271 // an anonymous struct. It would be preferable to strictly start 6272 // member lifetime in initialization order. 6273 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6274 } 6275 // Store Subobject as its parent before updating it for the last element 6276 // in the chain. 6277 if (C == IndirectFieldChain.back()) 6278 SubobjectParent = Subobject; 6279 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6280 return false; 6281 if (CD->isUnion()) 6282 Value = &Value->getUnionValue(); 6283 else { 6284 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6285 SkipToField(FD, true); 6286 Value = &Value->getStructField(FD->getFieldIndex()); 6287 } 6288 } 6289 } else { 6290 llvm_unreachable("unknown base initializer kind"); 6291 } 6292 6293 // Need to override This for implicit field initializers as in this case 6294 // This refers to innermost anonymous struct/union containing initializer, 6295 // not to currently constructed class. 6296 const Expr *Init = I->getInit(); 6297 if (Init->isValueDependent()) { 6298 if (!EvaluateDependentExpr(Init, Info)) 6299 return false; 6300 } else { 6301 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6302 isa<CXXDefaultInitExpr>(Init)); 6303 FullExpressionRAII InitScope(Info); 6304 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6305 (FD && FD->isBitField() && 6306 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6307 // If we're checking for a potential constant expression, evaluate all 6308 // initializers even if some of them fail. 6309 if (!Info.noteFailure()) 6310 return false; 6311 Success = false; 6312 } 6313 } 6314 6315 // This is the point at which the dynamic type of the object becomes this 6316 // class type. 6317 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6318 EvalObj.finishedConstructingBases(); 6319 } 6320 6321 // Default-initialize any remaining fields. 6322 if (!RD->isUnion()) { 6323 for (; FieldIt != RD->field_end(); ++FieldIt) { 6324 if (!FieldIt->isUnnamedBitfield()) 6325 Success &= getDefaultInitValue( 6326 FieldIt->getType(), 6327 Result.getStructField(FieldIt->getFieldIndex())); 6328 } 6329 } 6330 6331 EvalObj.finishedConstructingFields(); 6332 6333 return Success && 6334 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6335 LifetimeExtendedScope.destroy(); 6336 } 6337 6338 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6339 ArrayRef<const Expr*> Args, 6340 const CXXConstructorDecl *Definition, 6341 EvalInfo &Info, APValue &Result) { 6342 CallScopeRAII CallScope(Info); 6343 CallRef Call = Info.CurrentCall->createCall(Definition); 6344 if (!EvaluateArgs(Args, Call, Info, Definition)) 6345 return false; 6346 6347 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6348 CallScope.destroy(); 6349 } 6350 6351 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6352 const LValue &This, APValue &Value, 6353 QualType T) { 6354 // Objects can only be destroyed while they're within their lifetimes. 6355 // FIXME: We have no representation for whether an object of type nullptr_t 6356 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6357 // as indeterminate instead? 6358 if (Value.isAbsent() && !T->isNullPtrType()) { 6359 APValue Printable; 6360 This.moveInto(Printable); 6361 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6362 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6363 return false; 6364 } 6365 6366 // Invent an expression for location purposes. 6367 // FIXME: We shouldn't need to do this. 6368 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6369 6370 // For arrays, destroy elements right-to-left. 6371 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6372 uint64_t Size = CAT->getSize().getZExtValue(); 6373 QualType ElemT = CAT->getElementType(); 6374 6375 LValue ElemLV = This; 6376 ElemLV.addArray(Info, &LocE, CAT); 6377 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6378 return false; 6379 6380 // Ensure that we have actual array elements available to destroy; the 6381 // destructors might mutate the value, so we can't run them on the array 6382 // filler. 6383 if (Size && Size > Value.getArrayInitializedElts()) 6384 expandArray(Value, Value.getArraySize() - 1); 6385 6386 for (; Size != 0; --Size) { 6387 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6388 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6389 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6390 return false; 6391 } 6392 6393 // End the lifetime of this array now. 6394 Value = APValue(); 6395 return true; 6396 } 6397 6398 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6399 if (!RD) { 6400 if (T.isDestructedType()) { 6401 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6402 return false; 6403 } 6404 6405 Value = APValue(); 6406 return true; 6407 } 6408 6409 if (RD->getNumVBases()) { 6410 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6411 return false; 6412 } 6413 6414 const CXXDestructorDecl *DD = RD->getDestructor(); 6415 if (!DD && !RD->hasTrivialDestructor()) { 6416 Info.FFDiag(CallLoc); 6417 return false; 6418 } 6419 6420 if (!DD || DD->isTrivial() || 6421 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6422 // A trivial destructor just ends the lifetime of the object. Check for 6423 // this case before checking for a body, because we might not bother 6424 // building a body for a trivial destructor. Note that it doesn't matter 6425 // whether the destructor is constexpr in this case; all trivial 6426 // destructors are constexpr. 6427 // 6428 // If an anonymous union would be destroyed, some enclosing destructor must 6429 // have been explicitly defined, and the anonymous union destruction should 6430 // have no effect. 6431 Value = APValue(); 6432 return true; 6433 } 6434 6435 if (!Info.CheckCallLimit(CallLoc)) 6436 return false; 6437 6438 const FunctionDecl *Definition = nullptr; 6439 const Stmt *Body = DD->getBody(Definition); 6440 6441 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6442 return false; 6443 6444 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6445 6446 // We're now in the period of destruction of this object. 6447 unsigned BasesLeft = RD->getNumBases(); 6448 EvalInfo::EvaluatingDestructorRAII EvalObj( 6449 Info, 6450 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6451 if (!EvalObj.DidInsert) { 6452 // C++2a [class.dtor]p19: 6453 // the behavior is undefined if the destructor is invoked for an object 6454 // whose lifetime has ended 6455 // (Note that formally the lifetime ends when the period of destruction 6456 // begins, even though certain uses of the object remain valid until the 6457 // period of destruction ends.) 6458 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6459 return false; 6460 } 6461 6462 // FIXME: Creating an APValue just to hold a nonexistent return value is 6463 // wasteful. 6464 APValue RetVal; 6465 StmtResult Ret = {RetVal, nullptr}; 6466 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6467 return false; 6468 6469 // A union destructor does not implicitly destroy its members. 6470 if (RD->isUnion()) 6471 return true; 6472 6473 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6474 6475 // We don't have a good way to iterate fields in reverse, so collect all the 6476 // fields first and then walk them backwards. 6477 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6478 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6479 if (FD->isUnnamedBitfield()) 6480 continue; 6481 6482 LValue Subobject = This; 6483 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6484 return false; 6485 6486 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6487 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6488 FD->getType())) 6489 return false; 6490 } 6491 6492 if (BasesLeft != 0) 6493 EvalObj.startedDestroyingBases(); 6494 6495 // Destroy base classes in reverse order. 6496 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6497 --BasesLeft; 6498 6499 QualType BaseType = Base.getType(); 6500 LValue Subobject = This; 6501 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6502 BaseType->getAsCXXRecordDecl(), &Layout)) 6503 return false; 6504 6505 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6506 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6507 BaseType)) 6508 return false; 6509 } 6510 assert(BasesLeft == 0 && "NumBases was wrong?"); 6511 6512 // The period of destruction ends now. The object is gone. 6513 Value = APValue(); 6514 return true; 6515 } 6516 6517 namespace { 6518 struct DestroyObjectHandler { 6519 EvalInfo &Info; 6520 const Expr *E; 6521 const LValue &This; 6522 const AccessKinds AccessKind; 6523 6524 typedef bool result_type; 6525 bool failed() { return false; } 6526 bool found(APValue &Subobj, QualType SubobjType) { 6527 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6528 SubobjType); 6529 } 6530 bool found(APSInt &Value, QualType SubobjType) { 6531 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6532 return false; 6533 } 6534 bool found(APFloat &Value, QualType SubobjType) { 6535 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6536 return false; 6537 } 6538 }; 6539 } 6540 6541 /// Perform a destructor or pseudo-destructor call on the given object, which 6542 /// might in general not be a complete object. 6543 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6544 const LValue &This, QualType ThisType) { 6545 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6546 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6547 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6548 } 6549 6550 /// Destroy and end the lifetime of the given complete object. 6551 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6552 APValue::LValueBase LVBase, APValue &Value, 6553 QualType T) { 6554 // If we've had an unmodeled side-effect, we can't rely on mutable state 6555 // (such as the object we're about to destroy) being correct. 6556 if (Info.EvalStatus.HasSideEffects) 6557 return false; 6558 6559 LValue LV; 6560 LV.set({LVBase}); 6561 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6562 } 6563 6564 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6565 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6566 LValue &Result) { 6567 if (Info.checkingPotentialConstantExpression() || 6568 Info.SpeculativeEvaluationDepth) 6569 return false; 6570 6571 // This is permitted only within a call to std::allocator<T>::allocate. 6572 auto Caller = Info.getStdAllocatorCaller("allocate"); 6573 if (!Caller) { 6574 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6575 ? diag::note_constexpr_new_untyped 6576 : diag::note_constexpr_new); 6577 return false; 6578 } 6579 6580 QualType ElemType = Caller.ElemType; 6581 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6582 Info.FFDiag(E->getExprLoc(), 6583 diag::note_constexpr_new_not_complete_object_type) 6584 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6585 return false; 6586 } 6587 6588 APSInt ByteSize; 6589 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6590 return false; 6591 bool IsNothrow = false; 6592 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6593 EvaluateIgnoredValue(Info, E->getArg(I)); 6594 IsNothrow |= E->getType()->isNothrowT(); 6595 } 6596 6597 CharUnits ElemSize; 6598 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6599 return false; 6600 APInt Size, Remainder; 6601 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6602 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6603 if (Remainder != 0) { 6604 // This likely indicates a bug in the implementation of 'std::allocator'. 6605 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6606 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6607 return false; 6608 } 6609 6610 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6611 if (IsNothrow) { 6612 Result.setNull(Info.Ctx, E->getType()); 6613 return true; 6614 } 6615 6616 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6617 return false; 6618 } 6619 6620 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6621 ArrayType::Normal, 0); 6622 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6623 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6624 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6625 return true; 6626 } 6627 6628 static bool hasVirtualDestructor(QualType T) { 6629 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6630 if (CXXDestructorDecl *DD = RD->getDestructor()) 6631 return DD->isVirtual(); 6632 return false; 6633 } 6634 6635 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6636 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6637 if (CXXDestructorDecl *DD = RD->getDestructor()) 6638 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6639 return nullptr; 6640 } 6641 6642 /// Check that the given object is a suitable pointer to a heap allocation that 6643 /// still exists and is of the right kind for the purpose of a deletion. 6644 /// 6645 /// On success, returns the heap allocation to deallocate. On failure, produces 6646 /// a diagnostic and returns None. 6647 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6648 const LValue &Pointer, 6649 DynAlloc::Kind DeallocKind) { 6650 auto PointerAsString = [&] { 6651 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6652 }; 6653 6654 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6655 if (!DA) { 6656 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6657 << PointerAsString(); 6658 if (Pointer.Base) 6659 NoteLValueLocation(Info, Pointer.Base); 6660 return None; 6661 } 6662 6663 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6664 if (!Alloc) { 6665 Info.FFDiag(E, diag::note_constexpr_double_delete); 6666 return None; 6667 } 6668 6669 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6670 if (DeallocKind != (*Alloc)->getKind()) { 6671 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6672 << DeallocKind << (*Alloc)->getKind() << AllocType; 6673 NoteLValueLocation(Info, Pointer.Base); 6674 return None; 6675 } 6676 6677 bool Subobject = false; 6678 if (DeallocKind == DynAlloc::New) { 6679 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6680 Pointer.Designator.isOnePastTheEnd(); 6681 } else { 6682 Subobject = Pointer.Designator.Entries.size() != 1 || 6683 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6684 } 6685 if (Subobject) { 6686 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6687 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6688 return None; 6689 } 6690 6691 return Alloc; 6692 } 6693 6694 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6695 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6696 if (Info.checkingPotentialConstantExpression() || 6697 Info.SpeculativeEvaluationDepth) 6698 return false; 6699 6700 // This is permitted only within a call to std::allocator<T>::deallocate. 6701 if (!Info.getStdAllocatorCaller("deallocate")) { 6702 Info.FFDiag(E->getExprLoc()); 6703 return true; 6704 } 6705 6706 LValue Pointer; 6707 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6708 return false; 6709 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6710 EvaluateIgnoredValue(Info, E->getArg(I)); 6711 6712 if (Pointer.Designator.Invalid) 6713 return false; 6714 6715 // Deleting a null pointer has no effect. 6716 if (Pointer.isNullPointer()) 6717 return true; 6718 6719 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6720 return false; 6721 6722 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6723 return true; 6724 } 6725 6726 //===----------------------------------------------------------------------===// 6727 // Generic Evaluation 6728 //===----------------------------------------------------------------------===// 6729 namespace { 6730 6731 class BitCastBuffer { 6732 // FIXME: We're going to need bit-level granularity when we support 6733 // bit-fields. 6734 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6735 // we don't support a host or target where that is the case. Still, we should 6736 // use a more generic type in case we ever do. 6737 SmallVector<Optional<unsigned char>, 32> Bytes; 6738 6739 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6740 "Need at least 8 bit unsigned char"); 6741 6742 bool TargetIsLittleEndian; 6743 6744 public: 6745 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6746 : Bytes(Width.getQuantity()), 6747 TargetIsLittleEndian(TargetIsLittleEndian) {} 6748 6749 LLVM_NODISCARD 6750 bool readObject(CharUnits Offset, CharUnits Width, 6751 SmallVectorImpl<unsigned char> &Output) const { 6752 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6753 // If a byte of an integer is uninitialized, then the whole integer is 6754 // uninitalized. 6755 if (!Bytes[I.getQuantity()]) 6756 return false; 6757 Output.push_back(*Bytes[I.getQuantity()]); 6758 } 6759 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6760 std::reverse(Output.begin(), Output.end()); 6761 return true; 6762 } 6763 6764 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6765 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6766 std::reverse(Input.begin(), Input.end()); 6767 6768 size_t Index = 0; 6769 for (unsigned char Byte : Input) { 6770 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6771 Bytes[Offset.getQuantity() + Index] = Byte; 6772 ++Index; 6773 } 6774 } 6775 6776 size_t size() { return Bytes.size(); } 6777 }; 6778 6779 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6780 /// target would represent the value at runtime. 6781 class APValueToBufferConverter { 6782 EvalInfo &Info; 6783 BitCastBuffer Buffer; 6784 const CastExpr *BCE; 6785 6786 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6787 const CastExpr *BCE) 6788 : Info(Info), 6789 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6790 BCE(BCE) {} 6791 6792 bool visit(const APValue &Val, QualType Ty) { 6793 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6794 } 6795 6796 // Write out Val with type Ty into Buffer starting at Offset. 6797 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6798 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6799 6800 // As a special case, nullptr_t has an indeterminate value. 6801 if (Ty->isNullPtrType()) 6802 return true; 6803 6804 // Dig through Src to find the byte at SrcOffset. 6805 switch (Val.getKind()) { 6806 case APValue::Indeterminate: 6807 case APValue::None: 6808 return true; 6809 6810 case APValue::Int: 6811 return visitInt(Val.getInt(), Ty, Offset); 6812 case APValue::Float: 6813 return visitFloat(Val.getFloat(), Ty, Offset); 6814 case APValue::Array: 6815 return visitArray(Val, Ty, Offset); 6816 case APValue::Struct: 6817 return visitRecord(Val, Ty, Offset); 6818 6819 case APValue::ComplexInt: 6820 case APValue::ComplexFloat: 6821 case APValue::Vector: 6822 case APValue::FixedPoint: 6823 // FIXME: We should support these. 6824 6825 case APValue::Union: 6826 case APValue::MemberPointer: 6827 case APValue::AddrLabelDiff: { 6828 Info.FFDiag(BCE->getBeginLoc(), 6829 diag::note_constexpr_bit_cast_unsupported_type) 6830 << Ty; 6831 return false; 6832 } 6833 6834 case APValue::LValue: 6835 llvm_unreachable("LValue subobject in bit_cast?"); 6836 } 6837 llvm_unreachable("Unhandled APValue::ValueKind"); 6838 } 6839 6840 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6841 const RecordDecl *RD = Ty->getAsRecordDecl(); 6842 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6843 6844 // Visit the base classes. 6845 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6846 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6847 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6848 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6849 6850 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6851 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6852 return false; 6853 } 6854 } 6855 6856 // Visit the fields. 6857 unsigned FieldIdx = 0; 6858 for (FieldDecl *FD : RD->fields()) { 6859 if (FD->isBitField()) { 6860 Info.FFDiag(BCE->getBeginLoc(), 6861 diag::note_constexpr_bit_cast_unsupported_bitfield); 6862 return false; 6863 } 6864 6865 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6866 6867 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6868 "only bit-fields can have sub-char alignment"); 6869 CharUnits FieldOffset = 6870 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6871 QualType FieldTy = FD->getType(); 6872 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6873 return false; 6874 ++FieldIdx; 6875 } 6876 6877 return true; 6878 } 6879 6880 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6881 const auto *CAT = 6882 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6883 if (!CAT) 6884 return false; 6885 6886 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6887 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6888 unsigned ArraySize = Val.getArraySize(); 6889 // First, initialize the initialized elements. 6890 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6891 const APValue &SubObj = Val.getArrayInitializedElt(I); 6892 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6893 return false; 6894 } 6895 6896 // Next, initialize the rest of the array using the filler. 6897 if (Val.hasArrayFiller()) { 6898 const APValue &Filler = Val.getArrayFiller(); 6899 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6900 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6901 return false; 6902 } 6903 } 6904 6905 return true; 6906 } 6907 6908 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6909 APSInt AdjustedVal = Val; 6910 unsigned Width = AdjustedVal.getBitWidth(); 6911 if (Ty->isBooleanType()) { 6912 Width = Info.Ctx.getTypeSize(Ty); 6913 AdjustedVal = AdjustedVal.extend(Width); 6914 } 6915 6916 SmallVector<unsigned char, 8> Bytes(Width / 8); 6917 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6918 Buffer.writeObject(Offset, Bytes); 6919 return true; 6920 } 6921 6922 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6923 APSInt AsInt(Val.bitcastToAPInt()); 6924 return visitInt(AsInt, Ty, Offset); 6925 } 6926 6927 public: 6928 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6929 const CastExpr *BCE) { 6930 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6931 APValueToBufferConverter Converter(Info, DstSize, BCE); 6932 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6933 return None; 6934 return Converter.Buffer; 6935 } 6936 }; 6937 6938 /// Write an BitCastBuffer into an APValue. 6939 class BufferToAPValueConverter { 6940 EvalInfo &Info; 6941 const BitCastBuffer &Buffer; 6942 const CastExpr *BCE; 6943 6944 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6945 const CastExpr *BCE) 6946 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6947 6948 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6949 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6950 // Ideally this will be unreachable. 6951 llvm::NoneType unsupportedType(QualType Ty) { 6952 Info.FFDiag(BCE->getBeginLoc(), 6953 diag::note_constexpr_bit_cast_unsupported_type) 6954 << Ty; 6955 return None; 6956 } 6957 6958 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6959 Info.FFDiag(BCE->getBeginLoc(), 6960 diag::note_constexpr_bit_cast_unrepresentable_value) 6961 << Ty << Val.toString(/*Radix=*/10); 6962 return None; 6963 } 6964 6965 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6966 const EnumType *EnumSugar = nullptr) { 6967 if (T->isNullPtrType()) { 6968 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6969 return APValue((Expr *)nullptr, 6970 /*Offset=*/CharUnits::fromQuantity(NullValue), 6971 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6972 } 6973 6974 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6975 6976 // Work around floating point types that contain unused padding bytes. This 6977 // is really just `long double` on x86, which is the only fundamental type 6978 // with padding bytes. 6979 if (T->isRealFloatingType()) { 6980 const llvm::fltSemantics &Semantics = 6981 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6982 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6983 assert(NumBits % 8 == 0); 6984 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6985 if (NumBytes != SizeOf) 6986 SizeOf = NumBytes; 6987 } 6988 6989 SmallVector<uint8_t, 8> Bytes; 6990 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6991 // If this is std::byte or unsigned char, then its okay to store an 6992 // indeterminate value. 6993 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6994 bool IsUChar = 6995 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6996 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6997 if (!IsStdByte && !IsUChar) { 6998 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6999 Info.FFDiag(BCE->getExprLoc(), 7000 diag::note_constexpr_bit_cast_indet_dest) 7001 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7002 return None; 7003 } 7004 7005 return APValue::IndeterminateValue(); 7006 } 7007 7008 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7009 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7010 7011 if (T->isIntegralOrEnumerationType()) { 7012 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7013 7014 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7015 if (IntWidth != Val.getBitWidth()) { 7016 APSInt Truncated = Val.trunc(IntWidth); 7017 if (Truncated.extend(Val.getBitWidth()) != Val) 7018 return unrepresentableValue(QualType(T, 0), Val); 7019 Val = Truncated; 7020 } 7021 7022 return APValue(Val); 7023 } 7024 7025 if (T->isRealFloatingType()) { 7026 const llvm::fltSemantics &Semantics = 7027 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7028 return APValue(APFloat(Semantics, Val)); 7029 } 7030 7031 return unsupportedType(QualType(T, 0)); 7032 } 7033 7034 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7035 const RecordDecl *RD = RTy->getAsRecordDecl(); 7036 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7037 7038 unsigned NumBases = 0; 7039 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7040 NumBases = CXXRD->getNumBases(); 7041 7042 APValue ResultVal(APValue::UninitStruct(), NumBases, 7043 std::distance(RD->field_begin(), RD->field_end())); 7044 7045 // Visit the base classes. 7046 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7047 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7048 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7049 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7050 if (BaseDecl->isEmpty() || 7051 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7052 continue; 7053 7054 Optional<APValue> SubObj = visitType( 7055 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7056 if (!SubObj) 7057 return None; 7058 ResultVal.getStructBase(I) = *SubObj; 7059 } 7060 } 7061 7062 // Visit the fields. 7063 unsigned FieldIdx = 0; 7064 for (FieldDecl *FD : RD->fields()) { 7065 // FIXME: We don't currently support bit-fields. A lot of the logic for 7066 // this is in CodeGen, so we need to factor it around. 7067 if (FD->isBitField()) { 7068 Info.FFDiag(BCE->getBeginLoc(), 7069 diag::note_constexpr_bit_cast_unsupported_bitfield); 7070 return None; 7071 } 7072 7073 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7074 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7075 7076 CharUnits FieldOffset = 7077 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7078 Offset; 7079 QualType FieldTy = FD->getType(); 7080 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7081 if (!SubObj) 7082 return None; 7083 ResultVal.getStructField(FieldIdx) = *SubObj; 7084 ++FieldIdx; 7085 } 7086 7087 return ResultVal; 7088 } 7089 7090 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7091 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7092 assert(!RepresentationType.isNull() && 7093 "enum forward decl should be caught by Sema"); 7094 const auto *AsBuiltin = 7095 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7096 // Recurse into the underlying type. Treat std::byte transparently as 7097 // unsigned char. 7098 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7099 } 7100 7101 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7102 size_t Size = Ty->getSize().getLimitedValue(); 7103 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7104 7105 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7106 for (size_t I = 0; I != Size; ++I) { 7107 Optional<APValue> ElementValue = 7108 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7109 if (!ElementValue) 7110 return None; 7111 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7112 } 7113 7114 return ArrayValue; 7115 } 7116 7117 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7118 return unsupportedType(QualType(Ty, 0)); 7119 } 7120 7121 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7122 QualType Can = Ty.getCanonicalType(); 7123 7124 switch (Can->getTypeClass()) { 7125 #define TYPE(Class, Base) \ 7126 case Type::Class: \ 7127 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7128 #define ABSTRACT_TYPE(Class, Base) 7129 #define NON_CANONICAL_TYPE(Class, Base) \ 7130 case Type::Class: \ 7131 llvm_unreachable("non-canonical type should be impossible!"); 7132 #define DEPENDENT_TYPE(Class, Base) \ 7133 case Type::Class: \ 7134 llvm_unreachable( \ 7135 "dependent types aren't supported in the constant evaluator!"); 7136 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7137 case Type::Class: \ 7138 llvm_unreachable("either dependent or not canonical!"); 7139 #include "clang/AST/TypeNodes.inc" 7140 } 7141 llvm_unreachable("Unhandled Type::TypeClass"); 7142 } 7143 7144 public: 7145 // Pull out a full value of type DstType. 7146 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7147 const CastExpr *BCE) { 7148 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7149 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7150 } 7151 }; 7152 7153 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7154 QualType Ty, EvalInfo *Info, 7155 const ASTContext &Ctx, 7156 bool CheckingDest) { 7157 Ty = Ty.getCanonicalType(); 7158 7159 auto diag = [&](int Reason) { 7160 if (Info) 7161 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7162 << CheckingDest << (Reason == 4) << Reason; 7163 return false; 7164 }; 7165 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7166 if (Info) 7167 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7168 << NoteTy << Construct << Ty; 7169 return false; 7170 }; 7171 7172 if (Ty->isUnionType()) 7173 return diag(0); 7174 if (Ty->isPointerType()) 7175 return diag(1); 7176 if (Ty->isMemberPointerType()) 7177 return diag(2); 7178 if (Ty.isVolatileQualified()) 7179 return diag(3); 7180 7181 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7182 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7183 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7184 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7185 CheckingDest)) 7186 return note(1, BS.getType(), BS.getBeginLoc()); 7187 } 7188 for (FieldDecl *FD : Record->fields()) { 7189 if (FD->getType()->isReferenceType()) 7190 return diag(4); 7191 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7192 CheckingDest)) 7193 return note(0, FD->getType(), FD->getBeginLoc()); 7194 } 7195 } 7196 7197 if (Ty->isArrayType() && 7198 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7199 Info, Ctx, CheckingDest)) 7200 return false; 7201 7202 return true; 7203 } 7204 7205 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7206 const ASTContext &Ctx, 7207 const CastExpr *BCE) { 7208 bool DestOK = checkBitCastConstexprEligibilityType( 7209 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7210 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7211 BCE->getBeginLoc(), 7212 BCE->getSubExpr()->getType(), Info, Ctx, false); 7213 return SourceOK; 7214 } 7215 7216 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7217 APValue &SourceValue, 7218 const CastExpr *BCE) { 7219 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7220 "no host or target supports non 8-bit chars"); 7221 assert(SourceValue.isLValue() && 7222 "LValueToRValueBitcast requires an lvalue operand!"); 7223 7224 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7225 return false; 7226 7227 LValue SourceLValue; 7228 APValue SourceRValue; 7229 SourceLValue.setFrom(Info.Ctx, SourceValue); 7230 if (!handleLValueToRValueConversion( 7231 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7232 SourceRValue, /*WantObjectRepresentation=*/true)) 7233 return false; 7234 7235 // Read out SourceValue into a char buffer. 7236 Optional<BitCastBuffer> Buffer = 7237 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7238 if (!Buffer) 7239 return false; 7240 7241 // Write out the buffer into a new APValue. 7242 Optional<APValue> MaybeDestValue = 7243 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7244 if (!MaybeDestValue) 7245 return false; 7246 7247 DestValue = std::move(*MaybeDestValue); 7248 return true; 7249 } 7250 7251 template <class Derived> 7252 class ExprEvaluatorBase 7253 : public ConstStmtVisitor<Derived, bool> { 7254 private: 7255 Derived &getDerived() { return static_cast<Derived&>(*this); } 7256 bool DerivedSuccess(const APValue &V, const Expr *E) { 7257 return getDerived().Success(V, E); 7258 } 7259 bool DerivedZeroInitialization(const Expr *E) { 7260 return getDerived().ZeroInitialization(E); 7261 } 7262 7263 // Check whether a conditional operator with a non-constant condition is a 7264 // potential constant expression. If neither arm is a potential constant 7265 // expression, then the conditional operator is not either. 7266 template<typename ConditionalOperator> 7267 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7268 assert(Info.checkingPotentialConstantExpression()); 7269 7270 // Speculatively evaluate both arms. 7271 SmallVector<PartialDiagnosticAt, 8> Diag; 7272 { 7273 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7274 StmtVisitorTy::Visit(E->getFalseExpr()); 7275 if (Diag.empty()) 7276 return; 7277 } 7278 7279 { 7280 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7281 Diag.clear(); 7282 StmtVisitorTy::Visit(E->getTrueExpr()); 7283 if (Diag.empty()) 7284 return; 7285 } 7286 7287 Error(E, diag::note_constexpr_conditional_never_const); 7288 } 7289 7290 7291 template<typename ConditionalOperator> 7292 bool HandleConditionalOperator(const ConditionalOperator *E) { 7293 bool BoolResult; 7294 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7295 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7296 CheckPotentialConstantConditional(E); 7297 return false; 7298 } 7299 if (Info.noteFailure()) { 7300 StmtVisitorTy::Visit(E->getTrueExpr()); 7301 StmtVisitorTy::Visit(E->getFalseExpr()); 7302 } 7303 return false; 7304 } 7305 7306 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7307 return StmtVisitorTy::Visit(EvalExpr); 7308 } 7309 7310 protected: 7311 EvalInfo &Info; 7312 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7313 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7314 7315 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7316 return Info.CCEDiag(E, D); 7317 } 7318 7319 bool ZeroInitialization(const Expr *E) { return Error(E); } 7320 7321 public: 7322 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7323 7324 EvalInfo &getEvalInfo() { return Info; } 7325 7326 /// Report an evaluation error. This should only be called when an error is 7327 /// first discovered. When propagating an error, just return false. 7328 bool Error(const Expr *E, diag::kind D) { 7329 Info.FFDiag(E, D); 7330 return false; 7331 } 7332 bool Error(const Expr *E) { 7333 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7334 } 7335 7336 bool VisitStmt(const Stmt *) { 7337 llvm_unreachable("Expression evaluator should not be called on stmts"); 7338 } 7339 bool VisitExpr(const Expr *E) { 7340 return Error(E); 7341 } 7342 7343 bool VisitConstantExpr(const ConstantExpr *E) { 7344 if (E->hasAPValueResult()) 7345 return DerivedSuccess(E->getAPValueResult(), E); 7346 7347 return StmtVisitorTy::Visit(E->getSubExpr()); 7348 } 7349 7350 bool VisitParenExpr(const ParenExpr *E) 7351 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7352 bool VisitUnaryExtension(const UnaryOperator *E) 7353 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7354 bool VisitUnaryPlus(const UnaryOperator *E) 7355 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7356 bool VisitChooseExpr(const ChooseExpr *E) 7357 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7358 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7359 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7360 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7361 { return StmtVisitorTy::Visit(E->getReplacement()); } 7362 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7363 TempVersionRAII RAII(*Info.CurrentCall); 7364 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7365 return StmtVisitorTy::Visit(E->getExpr()); 7366 } 7367 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7368 TempVersionRAII RAII(*Info.CurrentCall); 7369 // The initializer may not have been parsed yet, or might be erroneous. 7370 if (!E->getExpr()) 7371 return Error(E); 7372 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7373 return StmtVisitorTy::Visit(E->getExpr()); 7374 } 7375 7376 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7377 FullExpressionRAII Scope(Info); 7378 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7379 } 7380 7381 // Temporaries are registered when created, so we don't care about 7382 // CXXBindTemporaryExpr. 7383 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7384 return StmtVisitorTy::Visit(E->getSubExpr()); 7385 } 7386 7387 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7388 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7389 return static_cast<Derived*>(this)->VisitCastExpr(E); 7390 } 7391 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7392 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7393 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7394 return static_cast<Derived*>(this)->VisitCastExpr(E); 7395 } 7396 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7397 return static_cast<Derived*>(this)->VisitCastExpr(E); 7398 } 7399 7400 bool VisitBinaryOperator(const BinaryOperator *E) { 7401 switch (E->getOpcode()) { 7402 default: 7403 return Error(E); 7404 7405 case BO_Comma: 7406 VisitIgnoredValue(E->getLHS()); 7407 return StmtVisitorTy::Visit(E->getRHS()); 7408 7409 case BO_PtrMemD: 7410 case BO_PtrMemI: { 7411 LValue Obj; 7412 if (!HandleMemberPointerAccess(Info, E, Obj)) 7413 return false; 7414 APValue Result; 7415 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7416 return false; 7417 return DerivedSuccess(Result, E); 7418 } 7419 } 7420 } 7421 7422 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7423 return StmtVisitorTy::Visit(E->getSemanticForm()); 7424 } 7425 7426 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7427 // Evaluate and cache the common expression. We treat it as a temporary, 7428 // even though it's not quite the same thing. 7429 LValue CommonLV; 7430 if (!Evaluate(Info.CurrentCall->createTemporary( 7431 E->getOpaqueValue(), 7432 getStorageType(Info.Ctx, E->getOpaqueValue()), 7433 ScopeKind::FullExpression, CommonLV), 7434 Info, E->getCommon())) 7435 return false; 7436 7437 return HandleConditionalOperator(E); 7438 } 7439 7440 bool VisitConditionalOperator(const ConditionalOperator *E) { 7441 bool IsBcpCall = false; 7442 // If the condition (ignoring parens) is a __builtin_constant_p call, 7443 // the result is a constant expression if it can be folded without 7444 // side-effects. This is an important GNU extension. See GCC PR38377 7445 // for discussion. 7446 if (const CallExpr *CallCE = 7447 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7448 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7449 IsBcpCall = true; 7450 7451 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7452 // constant expression; we can't check whether it's potentially foldable. 7453 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7454 // it would return 'false' in this mode. 7455 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7456 return false; 7457 7458 FoldConstant Fold(Info, IsBcpCall); 7459 if (!HandleConditionalOperator(E)) { 7460 Fold.keepDiagnostics(); 7461 return false; 7462 } 7463 7464 return true; 7465 } 7466 7467 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7468 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7469 return DerivedSuccess(*Value, E); 7470 7471 const Expr *Source = E->getSourceExpr(); 7472 if (!Source) 7473 return Error(E); 7474 if (Source == E) { // sanity checking. 7475 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7476 return Error(E); 7477 } 7478 return StmtVisitorTy::Visit(Source); 7479 } 7480 7481 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7482 for (const Expr *SemE : E->semantics()) { 7483 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7484 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7485 // result expression: there could be two different LValues that would 7486 // refer to the same object in that case, and we can't model that. 7487 if (SemE == E->getResultExpr()) 7488 return Error(E); 7489 7490 // Unique OVEs get evaluated if and when we encounter them when 7491 // emitting the rest of the semantic form, rather than eagerly. 7492 if (OVE->isUnique()) 7493 continue; 7494 7495 LValue LV; 7496 if (!Evaluate(Info.CurrentCall->createTemporary( 7497 OVE, getStorageType(Info.Ctx, OVE), 7498 ScopeKind::FullExpression, LV), 7499 Info, OVE->getSourceExpr())) 7500 return false; 7501 } else if (SemE == E->getResultExpr()) { 7502 if (!StmtVisitorTy::Visit(SemE)) 7503 return false; 7504 } else { 7505 if (!EvaluateIgnoredValue(Info, SemE)) 7506 return false; 7507 } 7508 } 7509 return true; 7510 } 7511 7512 bool VisitCallExpr(const CallExpr *E) { 7513 APValue Result; 7514 if (!handleCallExpr(E, Result, nullptr)) 7515 return false; 7516 return DerivedSuccess(Result, E); 7517 } 7518 7519 bool handleCallExpr(const CallExpr *E, APValue &Result, 7520 const LValue *ResultSlot) { 7521 CallScopeRAII CallScope(Info); 7522 7523 const Expr *Callee = E->getCallee()->IgnoreParens(); 7524 QualType CalleeType = Callee->getType(); 7525 7526 const FunctionDecl *FD = nullptr; 7527 LValue *This = nullptr, ThisVal; 7528 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7529 bool HasQualifier = false; 7530 7531 CallRef Call; 7532 7533 // Extract function decl and 'this' pointer from the callee. 7534 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7535 const CXXMethodDecl *Member = nullptr; 7536 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7537 // Explicit bound member calls, such as x.f() or p->g(); 7538 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7539 return false; 7540 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7541 if (!Member) 7542 return Error(Callee); 7543 This = &ThisVal; 7544 HasQualifier = ME->hasQualifier(); 7545 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7546 // Indirect bound member calls ('.*' or '->*'). 7547 const ValueDecl *D = 7548 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7549 if (!D) 7550 return false; 7551 Member = dyn_cast<CXXMethodDecl>(D); 7552 if (!Member) 7553 return Error(Callee); 7554 This = &ThisVal; 7555 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7556 if (!Info.getLangOpts().CPlusPlus20) 7557 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7558 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7559 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7560 } else 7561 return Error(Callee); 7562 FD = Member; 7563 } else if (CalleeType->isFunctionPointerType()) { 7564 LValue CalleeLV; 7565 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7566 return false; 7567 7568 if (!CalleeLV.getLValueOffset().isZero()) 7569 return Error(Callee); 7570 FD = dyn_cast_or_null<FunctionDecl>( 7571 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7572 if (!FD) 7573 return Error(Callee); 7574 // Don't call function pointers which have been cast to some other type. 7575 // Per DR (no number yet), the caller and callee can differ in noexcept. 7576 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7577 CalleeType->getPointeeType(), FD->getType())) { 7578 return Error(E); 7579 } 7580 7581 // For an (overloaded) assignment expression, evaluate the RHS before the 7582 // LHS. 7583 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7584 if (OCE && OCE->isAssignmentOp()) { 7585 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7586 Call = Info.CurrentCall->createCall(FD); 7587 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7588 Info, FD, /*RightToLeft=*/true)) 7589 return false; 7590 } 7591 7592 // Overloaded operator calls to member functions are represented as normal 7593 // calls with '*this' as the first argument. 7594 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7595 if (MD && !MD->isStatic()) { 7596 // FIXME: When selecting an implicit conversion for an overloaded 7597 // operator delete, we sometimes try to evaluate calls to conversion 7598 // operators without a 'this' parameter! 7599 if (Args.empty()) 7600 return Error(E); 7601 7602 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7603 return false; 7604 This = &ThisVal; 7605 Args = Args.slice(1); 7606 } else if (MD && MD->isLambdaStaticInvoker()) { 7607 // Map the static invoker for the lambda back to the call operator. 7608 // Conveniently, we don't have to slice out the 'this' argument (as is 7609 // being done for the non-static case), since a static member function 7610 // doesn't have an implicit argument passed in. 7611 const CXXRecordDecl *ClosureClass = MD->getParent(); 7612 assert( 7613 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7614 "Number of captures must be zero for conversion to function-ptr"); 7615 7616 const CXXMethodDecl *LambdaCallOp = 7617 ClosureClass->getLambdaCallOperator(); 7618 7619 // Set 'FD', the function that will be called below, to the call 7620 // operator. If the closure object represents a generic lambda, find 7621 // the corresponding specialization of the call operator. 7622 7623 if (ClosureClass->isGenericLambda()) { 7624 assert(MD->isFunctionTemplateSpecialization() && 7625 "A generic lambda's static-invoker function must be a " 7626 "template specialization"); 7627 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7628 FunctionTemplateDecl *CallOpTemplate = 7629 LambdaCallOp->getDescribedFunctionTemplate(); 7630 void *InsertPos = nullptr; 7631 FunctionDecl *CorrespondingCallOpSpecialization = 7632 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7633 assert(CorrespondingCallOpSpecialization && 7634 "We must always have a function call operator specialization " 7635 "that corresponds to our static invoker specialization"); 7636 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7637 } else 7638 FD = LambdaCallOp; 7639 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7640 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7641 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7642 LValue Ptr; 7643 if (!HandleOperatorNewCall(Info, E, Ptr)) 7644 return false; 7645 Ptr.moveInto(Result); 7646 return CallScope.destroy(); 7647 } else { 7648 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7649 } 7650 } 7651 } else 7652 return Error(E); 7653 7654 // Evaluate the arguments now if we've not already done so. 7655 if (!Call) { 7656 Call = Info.CurrentCall->createCall(FD); 7657 if (!EvaluateArgs(Args, Call, Info, FD)) 7658 return false; 7659 } 7660 7661 SmallVector<QualType, 4> CovariantAdjustmentPath; 7662 if (This) { 7663 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7664 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7665 // Perform virtual dispatch, if necessary. 7666 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7667 CovariantAdjustmentPath); 7668 if (!FD) 7669 return false; 7670 } else { 7671 // Check that the 'this' pointer points to an object of the right type. 7672 // FIXME: If this is an assignment operator call, we may need to change 7673 // the active union member before we check this. 7674 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7675 return false; 7676 } 7677 } 7678 7679 // Destructor calls are different enough that they have their own codepath. 7680 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7681 assert(This && "no 'this' pointer for destructor call"); 7682 return HandleDestruction(Info, E, *This, 7683 Info.Ctx.getRecordType(DD->getParent())) && 7684 CallScope.destroy(); 7685 } 7686 7687 const FunctionDecl *Definition = nullptr; 7688 Stmt *Body = FD->getBody(Definition); 7689 7690 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7691 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7692 Body, Info, Result, ResultSlot)) 7693 return false; 7694 7695 if (!CovariantAdjustmentPath.empty() && 7696 !HandleCovariantReturnAdjustment(Info, E, Result, 7697 CovariantAdjustmentPath)) 7698 return false; 7699 7700 return CallScope.destroy(); 7701 } 7702 7703 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7704 return StmtVisitorTy::Visit(E->getInitializer()); 7705 } 7706 bool VisitInitListExpr(const InitListExpr *E) { 7707 if (E->getNumInits() == 0) 7708 return DerivedZeroInitialization(E); 7709 if (E->getNumInits() == 1) 7710 return StmtVisitorTy::Visit(E->getInit(0)); 7711 return Error(E); 7712 } 7713 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7714 return DerivedZeroInitialization(E); 7715 } 7716 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7717 return DerivedZeroInitialization(E); 7718 } 7719 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7720 return DerivedZeroInitialization(E); 7721 } 7722 7723 /// A member expression where the object is a prvalue is itself a prvalue. 7724 bool VisitMemberExpr(const MemberExpr *E) { 7725 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7726 "missing temporary materialization conversion"); 7727 assert(!E->isArrow() && "missing call to bound member function?"); 7728 7729 APValue Val; 7730 if (!Evaluate(Val, Info, E->getBase())) 7731 return false; 7732 7733 QualType BaseTy = E->getBase()->getType(); 7734 7735 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7736 if (!FD) return Error(E); 7737 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7738 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7739 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7740 7741 // Note: there is no lvalue base here. But this case should only ever 7742 // happen in C or in C++98, where we cannot be evaluating a constexpr 7743 // constructor, which is the only case the base matters. 7744 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7745 SubobjectDesignator Designator(BaseTy); 7746 Designator.addDeclUnchecked(FD); 7747 7748 APValue Result; 7749 return extractSubobject(Info, E, Obj, Designator, Result) && 7750 DerivedSuccess(Result, E); 7751 } 7752 7753 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7754 APValue Val; 7755 if (!Evaluate(Val, Info, E->getBase())) 7756 return false; 7757 7758 if (Val.isVector()) { 7759 SmallVector<uint32_t, 4> Indices; 7760 E->getEncodedElementAccess(Indices); 7761 if (Indices.size() == 1) { 7762 // Return scalar. 7763 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7764 } else { 7765 // Construct new APValue vector. 7766 SmallVector<APValue, 4> Elts; 7767 for (unsigned I = 0; I < Indices.size(); ++I) { 7768 Elts.push_back(Val.getVectorElt(Indices[I])); 7769 } 7770 APValue VecResult(Elts.data(), Indices.size()); 7771 return DerivedSuccess(VecResult, E); 7772 } 7773 } 7774 7775 return false; 7776 } 7777 7778 bool VisitCastExpr(const CastExpr *E) { 7779 switch (E->getCastKind()) { 7780 default: 7781 break; 7782 7783 case CK_AtomicToNonAtomic: { 7784 APValue AtomicVal; 7785 // This does not need to be done in place even for class/array types: 7786 // atomic-to-non-atomic conversion implies copying the object 7787 // representation. 7788 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7789 return false; 7790 return DerivedSuccess(AtomicVal, E); 7791 } 7792 7793 case CK_NoOp: 7794 case CK_UserDefinedConversion: 7795 return StmtVisitorTy::Visit(E->getSubExpr()); 7796 7797 case CK_LValueToRValue: { 7798 LValue LVal; 7799 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7800 return false; 7801 APValue RVal; 7802 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7803 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7804 LVal, RVal)) 7805 return false; 7806 return DerivedSuccess(RVal, E); 7807 } 7808 case CK_LValueToRValueBitCast: { 7809 APValue DestValue, SourceValue; 7810 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7811 return false; 7812 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7813 return false; 7814 return DerivedSuccess(DestValue, E); 7815 } 7816 7817 case CK_AddressSpaceConversion: { 7818 APValue Value; 7819 if (!Evaluate(Value, Info, E->getSubExpr())) 7820 return false; 7821 return DerivedSuccess(Value, E); 7822 } 7823 } 7824 7825 return Error(E); 7826 } 7827 7828 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7829 return VisitUnaryPostIncDec(UO); 7830 } 7831 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7832 return VisitUnaryPostIncDec(UO); 7833 } 7834 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7835 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7836 return Error(UO); 7837 7838 LValue LVal; 7839 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7840 return false; 7841 APValue RVal; 7842 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7843 UO->isIncrementOp(), &RVal)) 7844 return false; 7845 return DerivedSuccess(RVal, UO); 7846 } 7847 7848 bool VisitStmtExpr(const StmtExpr *E) { 7849 // We will have checked the full-expressions inside the statement expression 7850 // when they were completed, and don't need to check them again now. 7851 llvm::SaveAndRestore<bool> NotCheckingForUB( 7852 Info.CheckingForUndefinedBehavior, false); 7853 7854 const CompoundStmt *CS = E->getSubStmt(); 7855 if (CS->body_empty()) 7856 return true; 7857 7858 BlockScopeRAII Scope(Info); 7859 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7860 BE = CS->body_end(); 7861 /**/; ++BI) { 7862 if (BI + 1 == BE) { 7863 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7864 if (!FinalExpr) { 7865 Info.FFDiag((*BI)->getBeginLoc(), 7866 diag::note_constexpr_stmt_expr_unsupported); 7867 return false; 7868 } 7869 return this->Visit(FinalExpr) && Scope.destroy(); 7870 } 7871 7872 APValue ReturnValue; 7873 StmtResult Result = { ReturnValue, nullptr }; 7874 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7875 if (ESR != ESR_Succeeded) { 7876 // FIXME: If the statement-expression terminated due to 'return', 7877 // 'break', or 'continue', it would be nice to propagate that to 7878 // the outer statement evaluation rather than bailing out. 7879 if (ESR != ESR_Failed) 7880 Info.FFDiag((*BI)->getBeginLoc(), 7881 diag::note_constexpr_stmt_expr_unsupported); 7882 return false; 7883 } 7884 } 7885 7886 llvm_unreachable("Return from function from the loop above."); 7887 } 7888 7889 /// Visit a value which is evaluated, but whose value is ignored. 7890 void VisitIgnoredValue(const Expr *E) { 7891 EvaluateIgnoredValue(Info, E); 7892 } 7893 7894 /// Potentially visit a MemberExpr's base expression. 7895 void VisitIgnoredBaseExpression(const Expr *E) { 7896 // While MSVC doesn't evaluate the base expression, it does diagnose the 7897 // presence of side-effecting behavior. 7898 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7899 return; 7900 VisitIgnoredValue(E); 7901 } 7902 }; 7903 7904 } // namespace 7905 7906 //===----------------------------------------------------------------------===// 7907 // Common base class for lvalue and temporary evaluation. 7908 //===----------------------------------------------------------------------===// 7909 namespace { 7910 template<class Derived> 7911 class LValueExprEvaluatorBase 7912 : public ExprEvaluatorBase<Derived> { 7913 protected: 7914 LValue &Result; 7915 bool InvalidBaseOK; 7916 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7917 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7918 7919 bool Success(APValue::LValueBase B) { 7920 Result.set(B); 7921 return true; 7922 } 7923 7924 bool evaluatePointer(const Expr *E, LValue &Result) { 7925 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7926 } 7927 7928 public: 7929 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7930 : ExprEvaluatorBaseTy(Info), Result(Result), 7931 InvalidBaseOK(InvalidBaseOK) {} 7932 7933 bool Success(const APValue &V, const Expr *E) { 7934 Result.setFrom(this->Info.Ctx, V); 7935 return true; 7936 } 7937 7938 bool VisitMemberExpr(const MemberExpr *E) { 7939 // Handle non-static data members. 7940 QualType BaseTy; 7941 bool EvalOK; 7942 if (E->isArrow()) { 7943 EvalOK = evaluatePointer(E->getBase(), Result); 7944 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7945 } else if (E->getBase()->isRValue()) { 7946 assert(E->getBase()->getType()->isRecordType()); 7947 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7948 BaseTy = E->getBase()->getType(); 7949 } else { 7950 EvalOK = this->Visit(E->getBase()); 7951 BaseTy = E->getBase()->getType(); 7952 } 7953 if (!EvalOK) { 7954 if (!InvalidBaseOK) 7955 return false; 7956 Result.setInvalid(E); 7957 return true; 7958 } 7959 7960 const ValueDecl *MD = E->getMemberDecl(); 7961 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7962 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7963 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7964 (void)BaseTy; 7965 if (!HandleLValueMember(this->Info, E, Result, FD)) 7966 return false; 7967 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7968 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7969 return false; 7970 } else 7971 return this->Error(E); 7972 7973 if (MD->getType()->isReferenceType()) { 7974 APValue RefValue; 7975 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7976 RefValue)) 7977 return false; 7978 return Success(RefValue, E); 7979 } 7980 return true; 7981 } 7982 7983 bool VisitBinaryOperator(const BinaryOperator *E) { 7984 switch (E->getOpcode()) { 7985 default: 7986 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7987 7988 case BO_PtrMemD: 7989 case BO_PtrMemI: 7990 return HandleMemberPointerAccess(this->Info, E, Result); 7991 } 7992 } 7993 7994 bool VisitCastExpr(const CastExpr *E) { 7995 switch (E->getCastKind()) { 7996 default: 7997 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7998 7999 case CK_DerivedToBase: 8000 case CK_UncheckedDerivedToBase: 8001 if (!this->Visit(E->getSubExpr())) 8002 return false; 8003 8004 // Now figure out the necessary offset to add to the base LV to get from 8005 // the derived class to the base class. 8006 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8007 Result); 8008 } 8009 } 8010 }; 8011 } 8012 8013 //===----------------------------------------------------------------------===// 8014 // LValue Evaluation 8015 // 8016 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8017 // function designators (in C), decl references to void objects (in C), and 8018 // temporaries (if building with -Wno-address-of-temporary). 8019 // 8020 // LValue evaluation produces values comprising a base expression of one of the 8021 // following types: 8022 // - Declarations 8023 // * VarDecl 8024 // * FunctionDecl 8025 // - Literals 8026 // * CompoundLiteralExpr in C (and in global scope in C++) 8027 // * StringLiteral 8028 // * PredefinedExpr 8029 // * ObjCStringLiteralExpr 8030 // * ObjCEncodeExpr 8031 // * AddrLabelExpr 8032 // * BlockExpr 8033 // * CallExpr for a MakeStringConstant builtin 8034 // - typeid(T) expressions, as TypeInfoLValues 8035 // - Locals and temporaries 8036 // * MaterializeTemporaryExpr 8037 // * Any Expr, with a CallIndex indicating the function in which the temporary 8038 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8039 // from the AST (FIXME). 8040 // * A MaterializeTemporaryExpr that has static storage duration, with no 8041 // CallIndex, for a lifetime-extended temporary. 8042 // * The ConstantExpr that is currently being evaluated during evaluation of an 8043 // immediate invocation. 8044 // plus an offset in bytes. 8045 //===----------------------------------------------------------------------===// 8046 namespace { 8047 class LValueExprEvaluator 8048 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8049 public: 8050 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8051 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8052 8053 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8054 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8055 8056 bool VisitDeclRefExpr(const DeclRefExpr *E); 8057 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8058 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8059 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8060 bool VisitMemberExpr(const MemberExpr *E); 8061 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8062 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8063 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8064 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8065 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8066 bool VisitUnaryDeref(const UnaryOperator *E); 8067 bool VisitUnaryReal(const UnaryOperator *E); 8068 bool VisitUnaryImag(const UnaryOperator *E); 8069 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8070 return VisitUnaryPreIncDec(UO); 8071 } 8072 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8073 return VisitUnaryPreIncDec(UO); 8074 } 8075 bool VisitBinAssign(const BinaryOperator *BO); 8076 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8077 8078 bool VisitCastExpr(const CastExpr *E) { 8079 switch (E->getCastKind()) { 8080 default: 8081 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8082 8083 case CK_LValueBitCast: 8084 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8085 if (!Visit(E->getSubExpr())) 8086 return false; 8087 Result.Designator.setInvalid(); 8088 return true; 8089 8090 case CK_BaseToDerived: 8091 if (!Visit(E->getSubExpr())) 8092 return false; 8093 return HandleBaseToDerivedCast(Info, E, Result); 8094 8095 case CK_Dynamic: 8096 if (!Visit(E->getSubExpr())) 8097 return false; 8098 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8099 } 8100 } 8101 }; 8102 } // end anonymous namespace 8103 8104 /// Evaluate an expression as an lvalue. This can be legitimately called on 8105 /// expressions which are not glvalues, in three cases: 8106 /// * function designators in C, and 8107 /// * "extern void" objects 8108 /// * @selector() expressions in Objective-C 8109 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8110 bool InvalidBaseOK) { 8111 assert(!E->isValueDependent()); 8112 assert(E->isGLValue() || E->getType()->isFunctionType() || 8113 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8114 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8115 } 8116 8117 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8118 const NamedDecl *D = E->getDecl(); 8119 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8120 return Success(cast<ValueDecl>(D)); 8121 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8122 return VisitVarDecl(E, VD); 8123 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8124 return Visit(BD->getBinding()); 8125 return Error(E); 8126 } 8127 8128 8129 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8130 8131 // If we are within a lambda's call operator, check whether the 'VD' referred 8132 // to within 'E' actually represents a lambda-capture that maps to a 8133 // data-member/field within the closure object, and if so, evaluate to the 8134 // field or what the field refers to. 8135 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8136 isa<DeclRefExpr>(E) && 8137 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8138 // We don't always have a complete capture-map when checking or inferring if 8139 // the function call operator meets the requirements of a constexpr function 8140 // - but we don't need to evaluate the captures to determine constexprness 8141 // (dcl.constexpr C++17). 8142 if (Info.checkingPotentialConstantExpression()) 8143 return false; 8144 8145 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8146 // Start with 'Result' referring to the complete closure object... 8147 Result = *Info.CurrentCall->This; 8148 // ... then update it to refer to the field of the closure object 8149 // that represents the capture. 8150 if (!HandleLValueMember(Info, E, Result, FD)) 8151 return false; 8152 // And if the field is of reference type, update 'Result' to refer to what 8153 // the field refers to. 8154 if (FD->getType()->isReferenceType()) { 8155 APValue RVal; 8156 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8157 RVal)) 8158 return false; 8159 Result.setFrom(Info.Ctx, RVal); 8160 } 8161 return true; 8162 } 8163 } 8164 8165 CallStackFrame *Frame = nullptr; 8166 unsigned Version = 0; 8167 if (VD->hasLocalStorage()) { 8168 // Only if a local variable was declared in the function currently being 8169 // evaluated, do we expect to be able to find its value in the current 8170 // frame. (Otherwise it was likely declared in an enclosing context and 8171 // could either have a valid evaluatable value (for e.g. a constexpr 8172 // variable) or be ill-formed (and trigger an appropriate evaluation 8173 // diagnostic)). 8174 CallStackFrame *CurrFrame = Info.CurrentCall; 8175 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8176 // Function parameters are stored in some caller's frame. (Usually the 8177 // immediate caller, but for an inherited constructor they may be more 8178 // distant.) 8179 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8180 if (CurrFrame->Arguments) { 8181 VD = CurrFrame->Arguments.getOrigParam(PVD); 8182 Frame = 8183 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8184 Version = CurrFrame->Arguments.Version; 8185 } 8186 } else { 8187 Frame = CurrFrame; 8188 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8189 } 8190 } 8191 } 8192 8193 if (!VD->getType()->isReferenceType()) { 8194 if (Frame) { 8195 Result.set({VD, Frame->Index, Version}); 8196 return true; 8197 } 8198 return Success(VD); 8199 } 8200 8201 if (!Info.getLangOpts().CPlusPlus11) { 8202 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8203 << VD << VD->getType(); 8204 Info.Note(VD->getLocation(), diag::note_declared_at); 8205 } 8206 8207 APValue *V; 8208 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8209 return false; 8210 if (!V->hasValue()) { 8211 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8212 // adjust the diagnostic to say that. 8213 if (!Info.checkingPotentialConstantExpression()) 8214 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8215 return false; 8216 } 8217 return Success(*V, E); 8218 } 8219 8220 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8221 const MaterializeTemporaryExpr *E) { 8222 // Walk through the expression to find the materialized temporary itself. 8223 SmallVector<const Expr *, 2> CommaLHSs; 8224 SmallVector<SubobjectAdjustment, 2> Adjustments; 8225 const Expr *Inner = 8226 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8227 8228 // If we passed any comma operators, evaluate their LHSs. 8229 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8230 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8231 return false; 8232 8233 // A materialized temporary with static storage duration can appear within the 8234 // result of a constant expression evaluation, so we need to preserve its 8235 // value for use outside this evaluation. 8236 APValue *Value; 8237 if (E->getStorageDuration() == SD_Static) { 8238 // FIXME: What about SD_Thread? 8239 Value = E->getOrCreateValue(true); 8240 *Value = APValue(); 8241 Result.set(E); 8242 } else { 8243 Value = &Info.CurrentCall->createTemporary( 8244 E, E->getType(), 8245 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8246 : ScopeKind::Block, 8247 Result); 8248 } 8249 8250 QualType Type = Inner->getType(); 8251 8252 // Materialize the temporary itself. 8253 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8254 *Value = APValue(); 8255 return false; 8256 } 8257 8258 // Adjust our lvalue to refer to the desired subobject. 8259 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8260 --I; 8261 switch (Adjustments[I].Kind) { 8262 case SubobjectAdjustment::DerivedToBaseAdjustment: 8263 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8264 Type, Result)) 8265 return false; 8266 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8267 break; 8268 8269 case SubobjectAdjustment::FieldAdjustment: 8270 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8271 return false; 8272 Type = Adjustments[I].Field->getType(); 8273 break; 8274 8275 case SubobjectAdjustment::MemberPointerAdjustment: 8276 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8277 Adjustments[I].Ptr.RHS)) 8278 return false; 8279 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8280 break; 8281 } 8282 } 8283 8284 return true; 8285 } 8286 8287 bool 8288 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8289 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8290 "lvalue compound literal in c++?"); 8291 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8292 // only see this when folding in C, so there's no standard to follow here. 8293 return Success(E); 8294 } 8295 8296 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8297 TypeInfoLValue TypeInfo; 8298 8299 if (!E->isPotentiallyEvaluated()) { 8300 if (E->isTypeOperand()) 8301 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8302 else 8303 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8304 } else { 8305 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8306 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8307 << E->getExprOperand()->getType() 8308 << E->getExprOperand()->getSourceRange(); 8309 } 8310 8311 if (!Visit(E->getExprOperand())) 8312 return false; 8313 8314 Optional<DynamicType> DynType = 8315 ComputeDynamicType(Info, E, Result, AK_TypeId); 8316 if (!DynType) 8317 return false; 8318 8319 TypeInfo = 8320 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8321 } 8322 8323 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8324 } 8325 8326 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8327 return Success(E->getGuidDecl()); 8328 } 8329 8330 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8331 // Handle static data members. 8332 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8333 VisitIgnoredBaseExpression(E->getBase()); 8334 return VisitVarDecl(E, VD); 8335 } 8336 8337 // Handle static member functions. 8338 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8339 if (MD->isStatic()) { 8340 VisitIgnoredBaseExpression(E->getBase()); 8341 return Success(MD); 8342 } 8343 } 8344 8345 // Handle non-static data members. 8346 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8347 } 8348 8349 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8350 // FIXME: Deal with vectors as array subscript bases. 8351 if (E->getBase()->getType()->isVectorType()) 8352 return Error(E); 8353 8354 APSInt Index; 8355 bool Success = true; 8356 8357 // C++17's rules require us to evaluate the LHS first, regardless of which 8358 // side is the base. 8359 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8360 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8361 : !EvaluateInteger(SubExpr, Index, Info)) { 8362 if (!Info.noteFailure()) 8363 return false; 8364 Success = false; 8365 } 8366 } 8367 8368 return Success && 8369 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8370 } 8371 8372 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8373 return evaluatePointer(E->getSubExpr(), Result); 8374 } 8375 8376 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8377 if (!Visit(E->getSubExpr())) 8378 return false; 8379 // __real is a no-op on scalar lvalues. 8380 if (E->getSubExpr()->getType()->isAnyComplexType()) 8381 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8382 return true; 8383 } 8384 8385 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8386 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8387 "lvalue __imag__ on scalar?"); 8388 if (!Visit(E->getSubExpr())) 8389 return false; 8390 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8391 return true; 8392 } 8393 8394 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8395 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8396 return Error(UO); 8397 8398 if (!this->Visit(UO->getSubExpr())) 8399 return false; 8400 8401 return handleIncDec( 8402 this->Info, UO, Result, UO->getSubExpr()->getType(), 8403 UO->isIncrementOp(), nullptr); 8404 } 8405 8406 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8407 const CompoundAssignOperator *CAO) { 8408 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8409 return Error(CAO); 8410 8411 bool Success = true; 8412 8413 // C++17 onwards require that we evaluate the RHS first. 8414 APValue RHS; 8415 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8416 if (!Info.noteFailure()) 8417 return false; 8418 Success = false; 8419 } 8420 8421 // The overall lvalue result is the result of evaluating the LHS. 8422 if (!this->Visit(CAO->getLHS()) || !Success) 8423 return false; 8424 8425 return handleCompoundAssignment( 8426 this->Info, CAO, 8427 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8428 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8429 } 8430 8431 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8432 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8433 return Error(E); 8434 8435 bool Success = true; 8436 8437 // C++17 onwards require that we evaluate the RHS first. 8438 APValue NewVal; 8439 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8440 if (!Info.noteFailure()) 8441 return false; 8442 Success = false; 8443 } 8444 8445 if (!this->Visit(E->getLHS()) || !Success) 8446 return false; 8447 8448 if (Info.getLangOpts().CPlusPlus20 && 8449 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8450 return false; 8451 8452 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8453 NewVal); 8454 } 8455 8456 //===----------------------------------------------------------------------===// 8457 // Pointer Evaluation 8458 //===----------------------------------------------------------------------===// 8459 8460 /// Attempts to compute the number of bytes available at the pointer 8461 /// returned by a function with the alloc_size attribute. Returns true if we 8462 /// were successful. Places an unsigned number into `Result`. 8463 /// 8464 /// This expects the given CallExpr to be a call to a function with an 8465 /// alloc_size attribute. 8466 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8467 const CallExpr *Call, 8468 llvm::APInt &Result) { 8469 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8470 8471 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8472 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8473 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8474 if (Call->getNumArgs() <= SizeArgNo) 8475 return false; 8476 8477 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8478 Expr::EvalResult ExprResult; 8479 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8480 return false; 8481 Into = ExprResult.Val.getInt(); 8482 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8483 return false; 8484 Into = Into.zextOrSelf(BitsInSizeT); 8485 return true; 8486 }; 8487 8488 APSInt SizeOfElem; 8489 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8490 return false; 8491 8492 if (!AllocSize->getNumElemsParam().isValid()) { 8493 Result = std::move(SizeOfElem); 8494 return true; 8495 } 8496 8497 APSInt NumberOfElems; 8498 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8499 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8500 return false; 8501 8502 bool Overflow; 8503 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8504 if (Overflow) 8505 return false; 8506 8507 Result = std::move(BytesAvailable); 8508 return true; 8509 } 8510 8511 /// Convenience function. LVal's base must be a call to an alloc_size 8512 /// function. 8513 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8514 const LValue &LVal, 8515 llvm::APInt &Result) { 8516 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8517 "Can't get the size of a non alloc_size function"); 8518 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8519 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8520 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8521 } 8522 8523 /// Attempts to evaluate the given LValueBase as the result of a call to 8524 /// a function with the alloc_size attribute. If it was possible to do so, this 8525 /// function will return true, make Result's Base point to said function call, 8526 /// and mark Result's Base as invalid. 8527 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8528 LValue &Result) { 8529 if (Base.isNull()) 8530 return false; 8531 8532 // Because we do no form of static analysis, we only support const variables. 8533 // 8534 // Additionally, we can't support parameters, nor can we support static 8535 // variables (in the latter case, use-before-assign isn't UB; in the former, 8536 // we have no clue what they'll be assigned to). 8537 const auto *VD = 8538 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8539 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8540 return false; 8541 8542 const Expr *Init = VD->getAnyInitializer(); 8543 if (!Init) 8544 return false; 8545 8546 const Expr *E = Init->IgnoreParens(); 8547 if (!tryUnwrapAllocSizeCall(E)) 8548 return false; 8549 8550 // Store E instead of E unwrapped so that the type of the LValue's base is 8551 // what the user wanted. 8552 Result.setInvalid(E); 8553 8554 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8555 Result.addUnsizedArray(Info, E, Pointee); 8556 return true; 8557 } 8558 8559 namespace { 8560 class PointerExprEvaluator 8561 : public ExprEvaluatorBase<PointerExprEvaluator> { 8562 LValue &Result; 8563 bool InvalidBaseOK; 8564 8565 bool Success(const Expr *E) { 8566 Result.set(E); 8567 return true; 8568 } 8569 8570 bool evaluateLValue(const Expr *E, LValue &Result) { 8571 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8572 } 8573 8574 bool evaluatePointer(const Expr *E, LValue &Result) { 8575 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8576 } 8577 8578 bool visitNonBuiltinCallExpr(const CallExpr *E); 8579 public: 8580 8581 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8582 : ExprEvaluatorBaseTy(info), Result(Result), 8583 InvalidBaseOK(InvalidBaseOK) {} 8584 8585 bool Success(const APValue &V, const Expr *E) { 8586 Result.setFrom(Info.Ctx, V); 8587 return true; 8588 } 8589 bool ZeroInitialization(const Expr *E) { 8590 Result.setNull(Info.Ctx, E->getType()); 8591 return true; 8592 } 8593 8594 bool VisitBinaryOperator(const BinaryOperator *E); 8595 bool VisitCastExpr(const CastExpr* E); 8596 bool VisitUnaryAddrOf(const UnaryOperator *E); 8597 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8598 { return Success(E); } 8599 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8600 if (E->isExpressibleAsConstantInitializer()) 8601 return Success(E); 8602 if (Info.noteFailure()) 8603 EvaluateIgnoredValue(Info, E->getSubExpr()); 8604 return Error(E); 8605 } 8606 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8607 { return Success(E); } 8608 bool VisitCallExpr(const CallExpr *E); 8609 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8610 bool VisitBlockExpr(const BlockExpr *E) { 8611 if (!E->getBlockDecl()->hasCaptures()) 8612 return Success(E); 8613 return Error(E); 8614 } 8615 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8616 // Can't look at 'this' when checking a potential constant expression. 8617 if (Info.checkingPotentialConstantExpression()) 8618 return false; 8619 if (!Info.CurrentCall->This) { 8620 if (Info.getLangOpts().CPlusPlus11) 8621 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8622 else 8623 Info.FFDiag(E); 8624 return false; 8625 } 8626 Result = *Info.CurrentCall->This; 8627 // If we are inside a lambda's call operator, the 'this' expression refers 8628 // to the enclosing '*this' object (either by value or reference) which is 8629 // either copied into the closure object's field that represents the '*this' 8630 // or refers to '*this'. 8631 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8632 // Ensure we actually have captured 'this'. (an error will have 8633 // been previously reported if not). 8634 if (!Info.CurrentCall->LambdaThisCaptureField) 8635 return false; 8636 8637 // Update 'Result' to refer to the data member/field of the closure object 8638 // that represents the '*this' capture. 8639 if (!HandleLValueMember(Info, E, Result, 8640 Info.CurrentCall->LambdaThisCaptureField)) 8641 return false; 8642 // If we captured '*this' by reference, replace the field with its referent. 8643 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8644 ->isPointerType()) { 8645 APValue RVal; 8646 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8647 RVal)) 8648 return false; 8649 8650 Result.setFrom(Info.Ctx, RVal); 8651 } 8652 } 8653 return true; 8654 } 8655 8656 bool VisitCXXNewExpr(const CXXNewExpr *E); 8657 8658 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8659 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8660 APValue LValResult = E->EvaluateInContext( 8661 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8662 Result.setFrom(Info.Ctx, LValResult); 8663 return true; 8664 } 8665 8666 // FIXME: Missing: @protocol, @selector 8667 }; 8668 } // end anonymous namespace 8669 8670 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8671 bool InvalidBaseOK) { 8672 assert(!E->isValueDependent()); 8673 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8674 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8675 } 8676 8677 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8678 if (E->getOpcode() != BO_Add && 8679 E->getOpcode() != BO_Sub) 8680 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8681 8682 const Expr *PExp = E->getLHS(); 8683 const Expr *IExp = E->getRHS(); 8684 if (IExp->getType()->isPointerType()) 8685 std::swap(PExp, IExp); 8686 8687 bool EvalPtrOK = evaluatePointer(PExp, Result); 8688 if (!EvalPtrOK && !Info.noteFailure()) 8689 return false; 8690 8691 llvm::APSInt Offset; 8692 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8693 return false; 8694 8695 if (E->getOpcode() == BO_Sub) 8696 negateAsSigned(Offset); 8697 8698 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8699 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8700 } 8701 8702 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8703 return evaluateLValue(E->getSubExpr(), Result); 8704 } 8705 8706 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8707 const Expr *SubExpr = E->getSubExpr(); 8708 8709 switch (E->getCastKind()) { 8710 default: 8711 break; 8712 case CK_BitCast: 8713 case CK_CPointerToObjCPointerCast: 8714 case CK_BlockPointerToObjCPointerCast: 8715 case CK_AnyPointerToBlockPointerCast: 8716 case CK_AddressSpaceConversion: 8717 if (!Visit(SubExpr)) 8718 return false; 8719 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8720 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8721 // also static_casts, but we disallow them as a resolution to DR1312. 8722 if (!E->getType()->isVoidPointerType()) { 8723 if (!Result.InvalidBase && !Result.Designator.Invalid && 8724 !Result.IsNullPtr && 8725 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8726 E->getType()->getPointeeType()) && 8727 Info.getStdAllocatorCaller("allocate")) { 8728 // Inside a call to std::allocator::allocate and friends, we permit 8729 // casting from void* back to cv1 T* for a pointer that points to a 8730 // cv2 T. 8731 } else { 8732 Result.Designator.setInvalid(); 8733 if (SubExpr->getType()->isVoidPointerType()) 8734 CCEDiag(E, diag::note_constexpr_invalid_cast) 8735 << 3 << SubExpr->getType(); 8736 else 8737 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8738 } 8739 } 8740 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8741 ZeroInitialization(E); 8742 return true; 8743 8744 case CK_DerivedToBase: 8745 case CK_UncheckedDerivedToBase: 8746 if (!evaluatePointer(E->getSubExpr(), Result)) 8747 return false; 8748 if (!Result.Base && Result.Offset.isZero()) 8749 return true; 8750 8751 // Now figure out the necessary offset to add to the base LV to get from 8752 // the derived class to the base class. 8753 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8754 castAs<PointerType>()->getPointeeType(), 8755 Result); 8756 8757 case CK_BaseToDerived: 8758 if (!Visit(E->getSubExpr())) 8759 return false; 8760 if (!Result.Base && Result.Offset.isZero()) 8761 return true; 8762 return HandleBaseToDerivedCast(Info, E, Result); 8763 8764 case CK_Dynamic: 8765 if (!Visit(E->getSubExpr())) 8766 return false; 8767 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8768 8769 case CK_NullToPointer: 8770 VisitIgnoredValue(E->getSubExpr()); 8771 return ZeroInitialization(E); 8772 8773 case CK_IntegralToPointer: { 8774 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8775 8776 APValue Value; 8777 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8778 break; 8779 8780 if (Value.isInt()) { 8781 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8782 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8783 Result.Base = (Expr*)nullptr; 8784 Result.InvalidBase = false; 8785 Result.Offset = CharUnits::fromQuantity(N); 8786 Result.Designator.setInvalid(); 8787 Result.IsNullPtr = false; 8788 return true; 8789 } else { 8790 // Cast is of an lvalue, no need to change value. 8791 Result.setFrom(Info.Ctx, Value); 8792 return true; 8793 } 8794 } 8795 8796 case CK_ArrayToPointerDecay: { 8797 if (SubExpr->isGLValue()) { 8798 if (!evaluateLValue(SubExpr, Result)) 8799 return false; 8800 } else { 8801 APValue &Value = Info.CurrentCall->createTemporary( 8802 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8803 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8804 return false; 8805 } 8806 // The result is a pointer to the first element of the array. 8807 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8808 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8809 Result.addArray(Info, E, CAT); 8810 else 8811 Result.addUnsizedArray(Info, E, AT->getElementType()); 8812 return true; 8813 } 8814 8815 case CK_FunctionToPointerDecay: 8816 return evaluateLValue(SubExpr, Result); 8817 8818 case CK_LValueToRValue: { 8819 LValue LVal; 8820 if (!evaluateLValue(E->getSubExpr(), LVal)) 8821 return false; 8822 8823 APValue RVal; 8824 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8825 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8826 LVal, RVal)) 8827 return InvalidBaseOK && 8828 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8829 return Success(RVal, E); 8830 } 8831 } 8832 8833 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8834 } 8835 8836 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8837 UnaryExprOrTypeTrait ExprKind) { 8838 // C++ [expr.alignof]p3: 8839 // When alignof is applied to a reference type, the result is the 8840 // alignment of the referenced type. 8841 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8842 T = Ref->getPointeeType(); 8843 8844 if (T.getQualifiers().hasUnaligned()) 8845 return CharUnits::One(); 8846 8847 const bool AlignOfReturnsPreferred = 8848 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8849 8850 // __alignof is defined to return the preferred alignment. 8851 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8852 // as well. 8853 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8854 return Info.Ctx.toCharUnitsFromBits( 8855 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8856 // alignof and _Alignof are defined to return the ABI alignment. 8857 else if (ExprKind == UETT_AlignOf) 8858 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8859 else 8860 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8861 } 8862 8863 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8864 UnaryExprOrTypeTrait ExprKind) { 8865 E = E->IgnoreParens(); 8866 8867 // The kinds of expressions that we have special-case logic here for 8868 // should be kept up to date with the special checks for those 8869 // expressions in Sema. 8870 8871 // alignof decl is always accepted, even if it doesn't make sense: we default 8872 // to 1 in those cases. 8873 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8874 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8875 /*RefAsPointee*/true); 8876 8877 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8878 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8879 /*RefAsPointee*/true); 8880 8881 return GetAlignOfType(Info, E->getType(), ExprKind); 8882 } 8883 8884 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8885 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8886 return Info.Ctx.getDeclAlign(VD); 8887 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8888 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8889 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8890 } 8891 8892 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8893 /// __builtin_is_aligned and __builtin_assume_aligned. 8894 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8895 EvalInfo &Info, APSInt &Alignment) { 8896 if (!EvaluateInteger(E, Alignment, Info)) 8897 return false; 8898 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8899 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8900 return false; 8901 } 8902 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8903 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8904 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8905 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8906 << MaxValue << ForType << Alignment; 8907 return false; 8908 } 8909 // Ensure both alignment and source value have the same bit width so that we 8910 // don't assert when computing the resulting value. 8911 APSInt ExtAlignment = 8912 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8913 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8914 "Alignment should not be changed by ext/trunc"); 8915 Alignment = ExtAlignment; 8916 assert(Alignment.getBitWidth() == SrcWidth); 8917 return true; 8918 } 8919 8920 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8921 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8922 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8923 return true; 8924 8925 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8926 return false; 8927 8928 Result.setInvalid(E); 8929 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8930 Result.addUnsizedArray(Info, E, PointeeTy); 8931 return true; 8932 } 8933 8934 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8935 if (IsStringLiteralCall(E)) 8936 return Success(E); 8937 8938 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8939 return VisitBuiltinCallExpr(E, BuiltinOp); 8940 8941 return visitNonBuiltinCallExpr(E); 8942 } 8943 8944 // Determine if T is a character type for which we guarantee that 8945 // sizeof(T) == 1. 8946 static bool isOneByteCharacterType(QualType T) { 8947 return T->isCharType() || T->isChar8Type(); 8948 } 8949 8950 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8951 unsigned BuiltinOp) { 8952 switch (BuiltinOp) { 8953 case Builtin::BI__builtin_addressof: 8954 return evaluateLValue(E->getArg(0), Result); 8955 case Builtin::BI__builtin_assume_aligned: { 8956 // We need to be very careful here because: if the pointer does not have the 8957 // asserted alignment, then the behavior is undefined, and undefined 8958 // behavior is non-constant. 8959 if (!evaluatePointer(E->getArg(0), Result)) 8960 return false; 8961 8962 LValue OffsetResult(Result); 8963 APSInt Alignment; 8964 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8965 Alignment)) 8966 return false; 8967 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8968 8969 if (E->getNumArgs() > 2) { 8970 APSInt Offset; 8971 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8972 return false; 8973 8974 int64_t AdditionalOffset = -Offset.getZExtValue(); 8975 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8976 } 8977 8978 // If there is a base object, then it must have the correct alignment. 8979 if (OffsetResult.Base) { 8980 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8981 8982 if (BaseAlignment < Align) { 8983 Result.Designator.setInvalid(); 8984 // FIXME: Add support to Diagnostic for long / long long. 8985 CCEDiag(E->getArg(0), 8986 diag::note_constexpr_baa_insufficient_alignment) << 0 8987 << (unsigned)BaseAlignment.getQuantity() 8988 << (unsigned)Align.getQuantity(); 8989 return false; 8990 } 8991 } 8992 8993 // The offset must also have the correct alignment. 8994 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8995 Result.Designator.setInvalid(); 8996 8997 (OffsetResult.Base 8998 ? CCEDiag(E->getArg(0), 8999 diag::note_constexpr_baa_insufficient_alignment) << 1 9000 : CCEDiag(E->getArg(0), 9001 diag::note_constexpr_baa_value_insufficient_alignment)) 9002 << (int)OffsetResult.Offset.getQuantity() 9003 << (unsigned)Align.getQuantity(); 9004 return false; 9005 } 9006 9007 return true; 9008 } 9009 case Builtin::BI__builtin_align_up: 9010 case Builtin::BI__builtin_align_down: { 9011 if (!evaluatePointer(E->getArg(0), Result)) 9012 return false; 9013 APSInt Alignment; 9014 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9015 Alignment)) 9016 return false; 9017 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9018 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9019 // For align_up/align_down, we can return the same value if the alignment 9020 // is known to be greater or equal to the requested value. 9021 if (PtrAlign.getQuantity() >= Alignment) 9022 return true; 9023 9024 // The alignment could be greater than the minimum at run-time, so we cannot 9025 // infer much about the resulting pointer value. One case is possible: 9026 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9027 // can infer the correct index if the requested alignment is smaller than 9028 // the base alignment so we can perform the computation on the offset. 9029 if (BaseAlignment.getQuantity() >= Alignment) { 9030 assert(Alignment.getBitWidth() <= 64 && 9031 "Cannot handle > 64-bit address-space"); 9032 uint64_t Alignment64 = Alignment.getZExtValue(); 9033 CharUnits NewOffset = CharUnits::fromQuantity( 9034 BuiltinOp == Builtin::BI__builtin_align_down 9035 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9036 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9037 Result.adjustOffset(NewOffset - Result.Offset); 9038 // TODO: diagnose out-of-bounds values/only allow for arrays? 9039 return true; 9040 } 9041 // Otherwise, we cannot constant-evaluate the result. 9042 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9043 << Alignment; 9044 return false; 9045 } 9046 case Builtin::BI__builtin_operator_new: 9047 return HandleOperatorNewCall(Info, E, Result); 9048 case Builtin::BI__builtin_launder: 9049 return evaluatePointer(E->getArg(0), Result); 9050 case Builtin::BIstrchr: 9051 case Builtin::BIwcschr: 9052 case Builtin::BImemchr: 9053 case Builtin::BIwmemchr: 9054 if (Info.getLangOpts().CPlusPlus11) 9055 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9056 << /*isConstexpr*/0 << /*isConstructor*/0 9057 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9058 else 9059 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9060 LLVM_FALLTHROUGH; 9061 case Builtin::BI__builtin_strchr: 9062 case Builtin::BI__builtin_wcschr: 9063 case Builtin::BI__builtin_memchr: 9064 case Builtin::BI__builtin_char_memchr: 9065 case Builtin::BI__builtin_wmemchr: { 9066 if (!Visit(E->getArg(0))) 9067 return false; 9068 APSInt Desired; 9069 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9070 return false; 9071 uint64_t MaxLength = uint64_t(-1); 9072 if (BuiltinOp != Builtin::BIstrchr && 9073 BuiltinOp != Builtin::BIwcschr && 9074 BuiltinOp != Builtin::BI__builtin_strchr && 9075 BuiltinOp != Builtin::BI__builtin_wcschr) { 9076 APSInt N; 9077 if (!EvaluateInteger(E->getArg(2), N, Info)) 9078 return false; 9079 MaxLength = N.getExtValue(); 9080 } 9081 // We cannot find the value if there are no candidates to match against. 9082 if (MaxLength == 0u) 9083 return ZeroInitialization(E); 9084 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9085 Result.Designator.Invalid) 9086 return false; 9087 QualType CharTy = Result.Designator.getType(Info.Ctx); 9088 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9089 BuiltinOp == Builtin::BI__builtin_memchr; 9090 assert(IsRawByte || 9091 Info.Ctx.hasSameUnqualifiedType( 9092 CharTy, E->getArg(0)->getType()->getPointeeType())); 9093 // Pointers to const void may point to objects of incomplete type. 9094 if (IsRawByte && CharTy->isIncompleteType()) { 9095 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9096 return false; 9097 } 9098 // Give up on byte-oriented matching against multibyte elements. 9099 // FIXME: We can compare the bytes in the correct order. 9100 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9101 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9102 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9103 << CharTy; 9104 return false; 9105 } 9106 // Figure out what value we're actually looking for (after converting to 9107 // the corresponding unsigned type if necessary). 9108 uint64_t DesiredVal; 9109 bool StopAtNull = false; 9110 switch (BuiltinOp) { 9111 case Builtin::BIstrchr: 9112 case Builtin::BI__builtin_strchr: 9113 // strchr compares directly to the passed integer, and therefore 9114 // always fails if given an int that is not a char. 9115 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9116 E->getArg(1)->getType(), 9117 Desired), 9118 Desired)) 9119 return ZeroInitialization(E); 9120 StopAtNull = true; 9121 LLVM_FALLTHROUGH; 9122 case Builtin::BImemchr: 9123 case Builtin::BI__builtin_memchr: 9124 case Builtin::BI__builtin_char_memchr: 9125 // memchr compares by converting both sides to unsigned char. That's also 9126 // correct for strchr if we get this far (to cope with plain char being 9127 // unsigned in the strchr case). 9128 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9129 break; 9130 9131 case Builtin::BIwcschr: 9132 case Builtin::BI__builtin_wcschr: 9133 StopAtNull = true; 9134 LLVM_FALLTHROUGH; 9135 case Builtin::BIwmemchr: 9136 case Builtin::BI__builtin_wmemchr: 9137 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9138 DesiredVal = Desired.getZExtValue(); 9139 break; 9140 } 9141 9142 for (; MaxLength; --MaxLength) { 9143 APValue Char; 9144 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9145 !Char.isInt()) 9146 return false; 9147 if (Char.getInt().getZExtValue() == DesiredVal) 9148 return true; 9149 if (StopAtNull && !Char.getInt()) 9150 break; 9151 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9152 return false; 9153 } 9154 // Not found: return nullptr. 9155 return ZeroInitialization(E); 9156 } 9157 9158 case Builtin::BImemcpy: 9159 case Builtin::BImemmove: 9160 case Builtin::BIwmemcpy: 9161 case Builtin::BIwmemmove: 9162 if (Info.getLangOpts().CPlusPlus11) 9163 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9164 << /*isConstexpr*/0 << /*isConstructor*/0 9165 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9166 else 9167 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9168 LLVM_FALLTHROUGH; 9169 case Builtin::BI__builtin_memcpy: 9170 case Builtin::BI__builtin_memmove: 9171 case Builtin::BI__builtin_wmemcpy: 9172 case Builtin::BI__builtin_wmemmove: { 9173 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9174 BuiltinOp == Builtin::BIwmemmove || 9175 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9176 BuiltinOp == Builtin::BI__builtin_wmemmove; 9177 bool Move = BuiltinOp == Builtin::BImemmove || 9178 BuiltinOp == Builtin::BIwmemmove || 9179 BuiltinOp == Builtin::BI__builtin_memmove || 9180 BuiltinOp == Builtin::BI__builtin_wmemmove; 9181 9182 // The result of mem* is the first argument. 9183 if (!Visit(E->getArg(0))) 9184 return false; 9185 LValue Dest = Result; 9186 9187 LValue Src; 9188 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9189 return false; 9190 9191 APSInt N; 9192 if (!EvaluateInteger(E->getArg(2), N, Info)) 9193 return false; 9194 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9195 9196 // If the size is zero, we treat this as always being a valid no-op. 9197 // (Even if one of the src and dest pointers is null.) 9198 if (!N) 9199 return true; 9200 9201 // Otherwise, if either of the operands is null, we can't proceed. Don't 9202 // try to determine the type of the copied objects, because there aren't 9203 // any. 9204 if (!Src.Base || !Dest.Base) { 9205 APValue Val; 9206 (!Src.Base ? Src : Dest).moveInto(Val); 9207 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9208 << Move << WChar << !!Src.Base 9209 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9210 return false; 9211 } 9212 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9213 return false; 9214 9215 // We require that Src and Dest are both pointers to arrays of 9216 // trivially-copyable type. (For the wide version, the designator will be 9217 // invalid if the designated object is not a wchar_t.) 9218 QualType T = Dest.Designator.getType(Info.Ctx); 9219 QualType SrcT = Src.Designator.getType(Info.Ctx); 9220 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9221 // FIXME: Consider using our bit_cast implementation to support this. 9222 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9223 return false; 9224 } 9225 if (T->isIncompleteType()) { 9226 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9227 return false; 9228 } 9229 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9230 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9231 return false; 9232 } 9233 9234 // Figure out how many T's we're copying. 9235 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9236 if (!WChar) { 9237 uint64_t Remainder; 9238 llvm::APInt OrigN = N; 9239 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9240 if (Remainder) { 9241 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9242 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9243 << (unsigned)TSize; 9244 return false; 9245 } 9246 } 9247 9248 // Check that the copying will remain within the arrays, just so that we 9249 // can give a more meaningful diagnostic. This implicitly also checks that 9250 // N fits into 64 bits. 9251 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9252 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9253 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9254 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9255 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9256 << N.toString(10, /*Signed*/false); 9257 return false; 9258 } 9259 uint64_t NElems = N.getZExtValue(); 9260 uint64_t NBytes = NElems * TSize; 9261 9262 // Check for overlap. 9263 int Direction = 1; 9264 if (HasSameBase(Src, Dest)) { 9265 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9266 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9267 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9268 // Dest is inside the source region. 9269 if (!Move) { 9270 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9271 return false; 9272 } 9273 // For memmove and friends, copy backwards. 9274 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9275 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9276 return false; 9277 Direction = -1; 9278 } else if (!Move && SrcOffset >= DestOffset && 9279 SrcOffset - DestOffset < NBytes) { 9280 // Src is inside the destination region for memcpy: invalid. 9281 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9282 return false; 9283 } 9284 } 9285 9286 while (true) { 9287 APValue Val; 9288 // FIXME: Set WantObjectRepresentation to true if we're copying a 9289 // char-like type? 9290 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9291 !handleAssignment(Info, E, Dest, T, Val)) 9292 return false; 9293 // Do not iterate past the last element; if we're copying backwards, that 9294 // might take us off the start of the array. 9295 if (--NElems == 0) 9296 return true; 9297 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9298 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9299 return false; 9300 } 9301 } 9302 9303 default: 9304 break; 9305 } 9306 9307 return visitNonBuiltinCallExpr(E); 9308 } 9309 9310 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9311 APValue &Result, const InitListExpr *ILE, 9312 QualType AllocType); 9313 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9314 APValue &Result, 9315 const CXXConstructExpr *CCE, 9316 QualType AllocType); 9317 9318 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9319 if (!Info.getLangOpts().CPlusPlus20) 9320 Info.CCEDiag(E, diag::note_constexpr_new); 9321 9322 // We cannot speculatively evaluate a delete expression. 9323 if (Info.SpeculativeEvaluationDepth) 9324 return false; 9325 9326 FunctionDecl *OperatorNew = E->getOperatorNew(); 9327 9328 bool IsNothrow = false; 9329 bool IsPlacement = false; 9330 if (OperatorNew->isReservedGlobalPlacementOperator() && 9331 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9332 // FIXME Support array placement new. 9333 assert(E->getNumPlacementArgs() == 1); 9334 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9335 return false; 9336 if (Result.Designator.Invalid) 9337 return false; 9338 IsPlacement = true; 9339 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9340 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9341 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9342 return false; 9343 } else if (E->getNumPlacementArgs()) { 9344 // The only new-placement list we support is of the form (std::nothrow). 9345 // 9346 // FIXME: There is no restriction on this, but it's not clear that any 9347 // other form makes any sense. We get here for cases such as: 9348 // 9349 // new (std::align_val_t{N}) X(int) 9350 // 9351 // (which should presumably be valid only if N is a multiple of 9352 // alignof(int), and in any case can't be deallocated unless N is 9353 // alignof(X) and X has new-extended alignment). 9354 if (E->getNumPlacementArgs() != 1 || 9355 !E->getPlacementArg(0)->getType()->isNothrowT()) 9356 return Error(E, diag::note_constexpr_new_placement); 9357 9358 LValue Nothrow; 9359 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9360 return false; 9361 IsNothrow = true; 9362 } 9363 9364 const Expr *Init = E->getInitializer(); 9365 const InitListExpr *ResizedArrayILE = nullptr; 9366 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9367 bool ValueInit = false; 9368 9369 QualType AllocType = E->getAllocatedType(); 9370 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9371 const Expr *Stripped = *ArraySize; 9372 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9373 Stripped = ICE->getSubExpr()) 9374 if (ICE->getCastKind() != CK_NoOp && 9375 ICE->getCastKind() != CK_IntegralCast) 9376 break; 9377 9378 llvm::APSInt ArrayBound; 9379 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9380 return false; 9381 9382 // C++ [expr.new]p9: 9383 // The expression is erroneous if: 9384 // -- [...] its value before converting to size_t [or] applying the 9385 // second standard conversion sequence is less than zero 9386 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9387 if (IsNothrow) 9388 return ZeroInitialization(E); 9389 9390 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9391 << ArrayBound << (*ArraySize)->getSourceRange(); 9392 return false; 9393 } 9394 9395 // -- its value is such that the size of the allocated object would 9396 // exceed the implementation-defined limit 9397 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9398 ArrayBound) > 9399 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9400 if (IsNothrow) 9401 return ZeroInitialization(E); 9402 9403 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9404 << ArrayBound << (*ArraySize)->getSourceRange(); 9405 return false; 9406 } 9407 9408 // -- the new-initializer is a braced-init-list and the number of 9409 // array elements for which initializers are provided [...] 9410 // exceeds the number of elements to initialize 9411 if (!Init) { 9412 // No initialization is performed. 9413 } else if (isa<CXXScalarValueInitExpr>(Init) || 9414 isa<ImplicitValueInitExpr>(Init)) { 9415 ValueInit = true; 9416 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9417 ResizedArrayCCE = CCE; 9418 } else { 9419 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9420 assert(CAT && "unexpected type for array initializer"); 9421 9422 unsigned Bits = 9423 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9424 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9425 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9426 if (InitBound.ugt(AllocBound)) { 9427 if (IsNothrow) 9428 return ZeroInitialization(E); 9429 9430 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9431 << AllocBound.toString(10, /*Signed=*/false) 9432 << InitBound.toString(10, /*Signed=*/false) 9433 << (*ArraySize)->getSourceRange(); 9434 return false; 9435 } 9436 9437 // If the sizes differ, we must have an initializer list, and we need 9438 // special handling for this case when we initialize. 9439 if (InitBound != AllocBound) 9440 ResizedArrayILE = cast<InitListExpr>(Init); 9441 } 9442 9443 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9444 ArrayType::Normal, 0); 9445 } else { 9446 assert(!AllocType->isArrayType() && 9447 "array allocation with non-array new"); 9448 } 9449 9450 APValue *Val; 9451 if (IsPlacement) { 9452 AccessKinds AK = AK_Construct; 9453 struct FindObjectHandler { 9454 EvalInfo &Info; 9455 const Expr *E; 9456 QualType AllocType; 9457 const AccessKinds AccessKind; 9458 APValue *Value; 9459 9460 typedef bool result_type; 9461 bool failed() { return false; } 9462 bool found(APValue &Subobj, QualType SubobjType) { 9463 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9464 // old name of the object to be used to name the new object. 9465 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9466 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9467 SubobjType << AllocType; 9468 return false; 9469 } 9470 Value = &Subobj; 9471 return true; 9472 } 9473 bool found(APSInt &Value, QualType SubobjType) { 9474 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9475 return false; 9476 } 9477 bool found(APFloat &Value, QualType SubobjType) { 9478 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9479 return false; 9480 } 9481 } Handler = {Info, E, AllocType, AK, nullptr}; 9482 9483 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9484 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9485 return false; 9486 9487 Val = Handler.Value; 9488 9489 // [basic.life]p1: 9490 // The lifetime of an object o of type T ends when [...] the storage 9491 // which the object occupies is [...] reused by an object that is not 9492 // nested within o (6.6.2). 9493 *Val = APValue(); 9494 } else { 9495 // Perform the allocation and obtain a pointer to the resulting object. 9496 Val = Info.createHeapAlloc(E, AllocType, Result); 9497 if (!Val) 9498 return false; 9499 } 9500 9501 if (ValueInit) { 9502 ImplicitValueInitExpr VIE(AllocType); 9503 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9504 return false; 9505 } else if (ResizedArrayILE) { 9506 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9507 AllocType)) 9508 return false; 9509 } else if (ResizedArrayCCE) { 9510 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9511 AllocType)) 9512 return false; 9513 } else if (Init) { 9514 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9515 return false; 9516 } else if (!getDefaultInitValue(AllocType, *Val)) { 9517 return false; 9518 } 9519 9520 // Array new returns a pointer to the first element, not a pointer to the 9521 // array. 9522 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9523 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9524 9525 return true; 9526 } 9527 //===----------------------------------------------------------------------===// 9528 // Member Pointer Evaluation 9529 //===----------------------------------------------------------------------===// 9530 9531 namespace { 9532 class MemberPointerExprEvaluator 9533 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9534 MemberPtr &Result; 9535 9536 bool Success(const ValueDecl *D) { 9537 Result = MemberPtr(D); 9538 return true; 9539 } 9540 public: 9541 9542 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9543 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9544 9545 bool Success(const APValue &V, const Expr *E) { 9546 Result.setFrom(V); 9547 return true; 9548 } 9549 bool ZeroInitialization(const Expr *E) { 9550 return Success((const ValueDecl*)nullptr); 9551 } 9552 9553 bool VisitCastExpr(const CastExpr *E); 9554 bool VisitUnaryAddrOf(const UnaryOperator *E); 9555 }; 9556 } // end anonymous namespace 9557 9558 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9559 EvalInfo &Info) { 9560 assert(!E->isValueDependent()); 9561 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9562 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9563 } 9564 9565 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9566 switch (E->getCastKind()) { 9567 default: 9568 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9569 9570 case CK_NullToMemberPointer: 9571 VisitIgnoredValue(E->getSubExpr()); 9572 return ZeroInitialization(E); 9573 9574 case CK_BaseToDerivedMemberPointer: { 9575 if (!Visit(E->getSubExpr())) 9576 return false; 9577 if (E->path_empty()) 9578 return true; 9579 // Base-to-derived member pointer casts store the path in derived-to-base 9580 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9581 // the wrong end of the derived->base arc, so stagger the path by one class. 9582 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9583 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9584 PathI != PathE; ++PathI) { 9585 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9586 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9587 if (!Result.castToDerived(Derived)) 9588 return Error(E); 9589 } 9590 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9591 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9592 return Error(E); 9593 return true; 9594 } 9595 9596 case CK_DerivedToBaseMemberPointer: 9597 if (!Visit(E->getSubExpr())) 9598 return false; 9599 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9600 PathE = E->path_end(); PathI != PathE; ++PathI) { 9601 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9602 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9603 if (!Result.castToBase(Base)) 9604 return Error(E); 9605 } 9606 return true; 9607 } 9608 } 9609 9610 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9611 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9612 // member can be formed. 9613 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9614 } 9615 9616 //===----------------------------------------------------------------------===// 9617 // Record Evaluation 9618 //===----------------------------------------------------------------------===// 9619 9620 namespace { 9621 class RecordExprEvaluator 9622 : public ExprEvaluatorBase<RecordExprEvaluator> { 9623 const LValue &This; 9624 APValue &Result; 9625 public: 9626 9627 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9628 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9629 9630 bool Success(const APValue &V, const Expr *E) { 9631 Result = V; 9632 return true; 9633 } 9634 bool ZeroInitialization(const Expr *E) { 9635 return ZeroInitialization(E, E->getType()); 9636 } 9637 bool ZeroInitialization(const Expr *E, QualType T); 9638 9639 bool VisitCallExpr(const CallExpr *E) { 9640 return handleCallExpr(E, Result, &This); 9641 } 9642 bool VisitCastExpr(const CastExpr *E); 9643 bool VisitInitListExpr(const InitListExpr *E); 9644 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9645 return VisitCXXConstructExpr(E, E->getType()); 9646 } 9647 bool VisitLambdaExpr(const LambdaExpr *E); 9648 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9649 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9650 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9651 bool VisitBinCmp(const BinaryOperator *E); 9652 }; 9653 } 9654 9655 /// Perform zero-initialization on an object of non-union class type. 9656 /// C++11 [dcl.init]p5: 9657 /// To zero-initialize an object or reference of type T means: 9658 /// [...] 9659 /// -- if T is a (possibly cv-qualified) non-union class type, 9660 /// each non-static data member and each base-class subobject is 9661 /// zero-initialized 9662 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9663 const RecordDecl *RD, 9664 const LValue &This, APValue &Result) { 9665 assert(!RD->isUnion() && "Expected non-union class type"); 9666 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9667 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9668 std::distance(RD->field_begin(), RD->field_end())); 9669 9670 if (RD->isInvalidDecl()) return false; 9671 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9672 9673 if (CD) { 9674 unsigned Index = 0; 9675 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9676 End = CD->bases_end(); I != End; ++I, ++Index) { 9677 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9678 LValue Subobject = This; 9679 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9680 return false; 9681 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9682 Result.getStructBase(Index))) 9683 return false; 9684 } 9685 } 9686 9687 for (const auto *I : RD->fields()) { 9688 // -- if T is a reference type, no initialization is performed. 9689 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9690 continue; 9691 9692 LValue Subobject = This; 9693 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9694 return false; 9695 9696 ImplicitValueInitExpr VIE(I->getType()); 9697 if (!EvaluateInPlace( 9698 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9699 return false; 9700 } 9701 9702 return true; 9703 } 9704 9705 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9706 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9707 if (RD->isInvalidDecl()) return false; 9708 if (RD->isUnion()) { 9709 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9710 // object's first non-static named data member is zero-initialized 9711 RecordDecl::field_iterator I = RD->field_begin(); 9712 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9713 ++I; 9714 if (I == RD->field_end()) { 9715 Result = APValue((const FieldDecl*)nullptr); 9716 return true; 9717 } 9718 9719 LValue Subobject = This; 9720 if (!HandleLValueMember(Info, E, Subobject, *I)) 9721 return false; 9722 Result = APValue(*I); 9723 ImplicitValueInitExpr VIE(I->getType()); 9724 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9725 } 9726 9727 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9728 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9729 return false; 9730 } 9731 9732 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9733 } 9734 9735 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9736 switch (E->getCastKind()) { 9737 default: 9738 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9739 9740 case CK_ConstructorConversion: 9741 return Visit(E->getSubExpr()); 9742 9743 case CK_DerivedToBase: 9744 case CK_UncheckedDerivedToBase: { 9745 APValue DerivedObject; 9746 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9747 return false; 9748 if (!DerivedObject.isStruct()) 9749 return Error(E->getSubExpr()); 9750 9751 // Derived-to-base rvalue conversion: just slice off the derived part. 9752 APValue *Value = &DerivedObject; 9753 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9754 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9755 PathE = E->path_end(); PathI != PathE; ++PathI) { 9756 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9757 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9758 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9759 RD = Base; 9760 } 9761 Result = *Value; 9762 return true; 9763 } 9764 } 9765 } 9766 9767 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9768 if (E->isTransparent()) 9769 return Visit(E->getInit(0)); 9770 9771 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9772 if (RD->isInvalidDecl()) return false; 9773 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9774 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9775 9776 EvalInfo::EvaluatingConstructorRAII EvalObj( 9777 Info, 9778 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9779 CXXRD && CXXRD->getNumBases()); 9780 9781 if (RD->isUnion()) { 9782 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9783 Result = APValue(Field); 9784 if (!Field) 9785 return true; 9786 9787 // If the initializer list for a union does not contain any elements, the 9788 // first element of the union is value-initialized. 9789 // FIXME: The element should be initialized from an initializer list. 9790 // Is this difference ever observable for initializer lists which 9791 // we don't build? 9792 ImplicitValueInitExpr VIE(Field->getType()); 9793 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9794 9795 LValue Subobject = This; 9796 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9797 return false; 9798 9799 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9800 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9801 isa<CXXDefaultInitExpr>(InitExpr)); 9802 9803 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9804 if (Field->isBitField()) 9805 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9806 Field); 9807 return true; 9808 } 9809 9810 return false; 9811 } 9812 9813 if (!Result.hasValue()) 9814 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9815 std::distance(RD->field_begin(), RD->field_end())); 9816 unsigned ElementNo = 0; 9817 bool Success = true; 9818 9819 // Initialize base classes. 9820 if (CXXRD && CXXRD->getNumBases()) { 9821 for (const auto &Base : CXXRD->bases()) { 9822 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9823 const Expr *Init = E->getInit(ElementNo); 9824 9825 LValue Subobject = This; 9826 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9827 return false; 9828 9829 APValue &FieldVal = Result.getStructBase(ElementNo); 9830 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9831 if (!Info.noteFailure()) 9832 return false; 9833 Success = false; 9834 } 9835 ++ElementNo; 9836 } 9837 9838 EvalObj.finishedConstructingBases(); 9839 } 9840 9841 // Initialize members. 9842 for (const auto *Field : RD->fields()) { 9843 // Anonymous bit-fields are not considered members of the class for 9844 // purposes of aggregate initialization. 9845 if (Field->isUnnamedBitfield()) 9846 continue; 9847 9848 LValue Subobject = This; 9849 9850 bool HaveInit = ElementNo < E->getNumInits(); 9851 9852 // FIXME: Diagnostics here should point to the end of the initializer 9853 // list, not the start. 9854 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9855 Subobject, Field, &Layout)) 9856 return false; 9857 9858 // Perform an implicit value-initialization for members beyond the end of 9859 // the initializer list. 9860 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9861 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9862 9863 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9864 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9865 isa<CXXDefaultInitExpr>(Init)); 9866 9867 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9868 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9869 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9870 FieldVal, Field))) { 9871 if (!Info.noteFailure()) 9872 return false; 9873 Success = false; 9874 } 9875 } 9876 9877 EvalObj.finishedConstructingFields(); 9878 9879 return Success; 9880 } 9881 9882 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9883 QualType T) { 9884 // Note that E's type is not necessarily the type of our class here; we might 9885 // be initializing an array element instead. 9886 const CXXConstructorDecl *FD = E->getConstructor(); 9887 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9888 9889 bool ZeroInit = E->requiresZeroInitialization(); 9890 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9891 // If we've already performed zero-initialization, we're already done. 9892 if (Result.hasValue()) 9893 return true; 9894 9895 if (ZeroInit) 9896 return ZeroInitialization(E, T); 9897 9898 return getDefaultInitValue(T, Result); 9899 } 9900 9901 const FunctionDecl *Definition = nullptr; 9902 auto Body = FD->getBody(Definition); 9903 9904 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9905 return false; 9906 9907 // Avoid materializing a temporary for an elidable copy/move constructor. 9908 if (E->isElidable() && !ZeroInit) 9909 if (const MaterializeTemporaryExpr *ME 9910 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9911 return Visit(ME->getSubExpr()); 9912 9913 if (ZeroInit && !ZeroInitialization(E, T)) 9914 return false; 9915 9916 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9917 return HandleConstructorCall(E, This, Args, 9918 cast<CXXConstructorDecl>(Definition), Info, 9919 Result); 9920 } 9921 9922 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9923 const CXXInheritedCtorInitExpr *E) { 9924 if (!Info.CurrentCall) { 9925 assert(Info.checkingPotentialConstantExpression()); 9926 return false; 9927 } 9928 9929 const CXXConstructorDecl *FD = E->getConstructor(); 9930 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9931 return false; 9932 9933 const FunctionDecl *Definition = nullptr; 9934 auto Body = FD->getBody(Definition); 9935 9936 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9937 return false; 9938 9939 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9940 cast<CXXConstructorDecl>(Definition), Info, 9941 Result); 9942 } 9943 9944 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9945 const CXXStdInitializerListExpr *E) { 9946 const ConstantArrayType *ArrayType = 9947 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9948 9949 LValue Array; 9950 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9951 return false; 9952 9953 // Get a pointer to the first element of the array. 9954 Array.addArray(Info, E, ArrayType); 9955 9956 auto InvalidType = [&] { 9957 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9958 << E->getType(); 9959 return false; 9960 }; 9961 9962 // FIXME: Perform the checks on the field types in SemaInit. 9963 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9964 RecordDecl::field_iterator Field = Record->field_begin(); 9965 if (Field == Record->field_end()) 9966 return InvalidType(); 9967 9968 // Start pointer. 9969 if (!Field->getType()->isPointerType() || 9970 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9971 ArrayType->getElementType())) 9972 return InvalidType(); 9973 9974 // FIXME: What if the initializer_list type has base classes, etc? 9975 Result = APValue(APValue::UninitStruct(), 0, 2); 9976 Array.moveInto(Result.getStructField(0)); 9977 9978 if (++Field == Record->field_end()) 9979 return InvalidType(); 9980 9981 if (Field->getType()->isPointerType() && 9982 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9983 ArrayType->getElementType())) { 9984 // End pointer. 9985 if (!HandleLValueArrayAdjustment(Info, E, Array, 9986 ArrayType->getElementType(), 9987 ArrayType->getSize().getZExtValue())) 9988 return false; 9989 Array.moveInto(Result.getStructField(1)); 9990 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9991 // Length. 9992 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9993 else 9994 return InvalidType(); 9995 9996 if (++Field != Record->field_end()) 9997 return InvalidType(); 9998 9999 return true; 10000 } 10001 10002 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10003 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10004 if (ClosureClass->isInvalidDecl()) 10005 return false; 10006 10007 const size_t NumFields = 10008 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10009 10010 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10011 E->capture_init_end()) && 10012 "The number of lambda capture initializers should equal the number of " 10013 "fields within the closure type"); 10014 10015 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10016 // Iterate through all the lambda's closure object's fields and initialize 10017 // them. 10018 auto *CaptureInitIt = E->capture_init_begin(); 10019 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10020 bool Success = true; 10021 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10022 for (const auto *Field : ClosureClass->fields()) { 10023 assert(CaptureInitIt != E->capture_init_end()); 10024 // Get the initializer for this field 10025 Expr *const CurFieldInit = *CaptureInitIt++; 10026 10027 // If there is no initializer, either this is a VLA or an error has 10028 // occurred. 10029 if (!CurFieldInit) 10030 return Error(E); 10031 10032 LValue Subobject = This; 10033 10034 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10035 return false; 10036 10037 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10038 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10039 if (!Info.keepEvaluatingAfterFailure()) 10040 return false; 10041 Success = false; 10042 } 10043 ++CaptureIt; 10044 } 10045 return Success; 10046 } 10047 10048 static bool EvaluateRecord(const Expr *E, const LValue &This, 10049 APValue &Result, EvalInfo &Info) { 10050 assert(!E->isValueDependent()); 10051 assert(E->isRValue() && E->getType()->isRecordType() && 10052 "can't evaluate expression as a record rvalue"); 10053 return RecordExprEvaluator(Info, This, Result).Visit(E); 10054 } 10055 10056 //===----------------------------------------------------------------------===// 10057 // Temporary Evaluation 10058 // 10059 // Temporaries are represented in the AST as rvalues, but generally behave like 10060 // lvalues. The full-object of which the temporary is a subobject is implicitly 10061 // materialized so that a reference can bind to it. 10062 //===----------------------------------------------------------------------===// 10063 namespace { 10064 class TemporaryExprEvaluator 10065 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10066 public: 10067 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10068 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10069 10070 /// Visit an expression which constructs the value of this temporary. 10071 bool VisitConstructExpr(const Expr *E) { 10072 APValue &Value = Info.CurrentCall->createTemporary( 10073 E, E->getType(), ScopeKind::FullExpression, Result); 10074 return EvaluateInPlace(Value, Info, Result, E); 10075 } 10076 10077 bool VisitCastExpr(const CastExpr *E) { 10078 switch (E->getCastKind()) { 10079 default: 10080 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10081 10082 case CK_ConstructorConversion: 10083 return VisitConstructExpr(E->getSubExpr()); 10084 } 10085 } 10086 bool VisitInitListExpr(const InitListExpr *E) { 10087 return VisitConstructExpr(E); 10088 } 10089 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10090 return VisitConstructExpr(E); 10091 } 10092 bool VisitCallExpr(const CallExpr *E) { 10093 return VisitConstructExpr(E); 10094 } 10095 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10096 return VisitConstructExpr(E); 10097 } 10098 bool VisitLambdaExpr(const LambdaExpr *E) { 10099 return VisitConstructExpr(E); 10100 } 10101 }; 10102 } // end anonymous namespace 10103 10104 /// Evaluate an expression of record type as a temporary. 10105 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10106 assert(!E->isValueDependent()); 10107 assert(E->isRValue() && E->getType()->isRecordType()); 10108 return TemporaryExprEvaluator(Info, Result).Visit(E); 10109 } 10110 10111 //===----------------------------------------------------------------------===// 10112 // Vector Evaluation 10113 //===----------------------------------------------------------------------===// 10114 10115 namespace { 10116 class VectorExprEvaluator 10117 : public ExprEvaluatorBase<VectorExprEvaluator> { 10118 APValue &Result; 10119 public: 10120 10121 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10122 : ExprEvaluatorBaseTy(info), Result(Result) {} 10123 10124 bool Success(ArrayRef<APValue> V, const Expr *E) { 10125 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10126 // FIXME: remove this APValue copy. 10127 Result = APValue(V.data(), V.size()); 10128 return true; 10129 } 10130 bool Success(const APValue &V, const Expr *E) { 10131 assert(V.isVector()); 10132 Result = V; 10133 return true; 10134 } 10135 bool ZeroInitialization(const Expr *E); 10136 10137 bool VisitUnaryReal(const UnaryOperator *E) 10138 { return Visit(E->getSubExpr()); } 10139 bool VisitCastExpr(const CastExpr* E); 10140 bool VisitInitListExpr(const InitListExpr *E); 10141 bool VisitUnaryImag(const UnaryOperator *E); 10142 bool VisitBinaryOperator(const BinaryOperator *E); 10143 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10144 // conditional select), shufflevector, ExtVectorElementExpr 10145 }; 10146 } // end anonymous namespace 10147 10148 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10149 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10150 return VectorExprEvaluator(Info, Result).Visit(E); 10151 } 10152 10153 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10154 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10155 unsigned NElts = VTy->getNumElements(); 10156 10157 const Expr *SE = E->getSubExpr(); 10158 QualType SETy = SE->getType(); 10159 10160 switch (E->getCastKind()) { 10161 case CK_VectorSplat: { 10162 APValue Val = APValue(); 10163 if (SETy->isIntegerType()) { 10164 APSInt IntResult; 10165 if (!EvaluateInteger(SE, IntResult, Info)) 10166 return false; 10167 Val = APValue(std::move(IntResult)); 10168 } else if (SETy->isRealFloatingType()) { 10169 APFloat FloatResult(0.0); 10170 if (!EvaluateFloat(SE, FloatResult, Info)) 10171 return false; 10172 Val = APValue(std::move(FloatResult)); 10173 } else { 10174 return Error(E); 10175 } 10176 10177 // Splat and create vector APValue. 10178 SmallVector<APValue, 4> Elts(NElts, Val); 10179 return Success(Elts, E); 10180 } 10181 case CK_BitCast: { 10182 // Evaluate the operand into an APInt we can extract from. 10183 llvm::APInt SValInt; 10184 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10185 return false; 10186 // Extract the elements 10187 QualType EltTy = VTy->getElementType(); 10188 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10189 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10190 SmallVector<APValue, 4> Elts; 10191 if (EltTy->isRealFloatingType()) { 10192 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10193 unsigned FloatEltSize = EltSize; 10194 if (&Sem == &APFloat::x87DoubleExtended()) 10195 FloatEltSize = 80; 10196 for (unsigned i = 0; i < NElts; i++) { 10197 llvm::APInt Elt; 10198 if (BigEndian) 10199 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10200 else 10201 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10202 Elts.push_back(APValue(APFloat(Sem, Elt))); 10203 } 10204 } else if (EltTy->isIntegerType()) { 10205 for (unsigned i = 0; i < NElts; i++) { 10206 llvm::APInt Elt; 10207 if (BigEndian) 10208 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10209 else 10210 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10211 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10212 } 10213 } else { 10214 return Error(E); 10215 } 10216 return Success(Elts, E); 10217 } 10218 default: 10219 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10220 } 10221 } 10222 10223 bool 10224 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10225 const VectorType *VT = E->getType()->castAs<VectorType>(); 10226 unsigned NumInits = E->getNumInits(); 10227 unsigned NumElements = VT->getNumElements(); 10228 10229 QualType EltTy = VT->getElementType(); 10230 SmallVector<APValue, 4> Elements; 10231 10232 // The number of initializers can be less than the number of 10233 // vector elements. For OpenCL, this can be due to nested vector 10234 // initialization. For GCC compatibility, missing trailing elements 10235 // should be initialized with zeroes. 10236 unsigned CountInits = 0, CountElts = 0; 10237 while (CountElts < NumElements) { 10238 // Handle nested vector initialization. 10239 if (CountInits < NumInits 10240 && E->getInit(CountInits)->getType()->isVectorType()) { 10241 APValue v; 10242 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10243 return Error(E); 10244 unsigned vlen = v.getVectorLength(); 10245 for (unsigned j = 0; j < vlen; j++) 10246 Elements.push_back(v.getVectorElt(j)); 10247 CountElts += vlen; 10248 } else if (EltTy->isIntegerType()) { 10249 llvm::APSInt sInt(32); 10250 if (CountInits < NumInits) { 10251 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10252 return false; 10253 } else // trailing integer zero. 10254 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10255 Elements.push_back(APValue(sInt)); 10256 CountElts++; 10257 } else { 10258 llvm::APFloat f(0.0); 10259 if (CountInits < NumInits) { 10260 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10261 return false; 10262 } else // trailing float zero. 10263 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10264 Elements.push_back(APValue(f)); 10265 CountElts++; 10266 } 10267 CountInits++; 10268 } 10269 return Success(Elements, E); 10270 } 10271 10272 bool 10273 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10274 const auto *VT = E->getType()->castAs<VectorType>(); 10275 QualType EltTy = VT->getElementType(); 10276 APValue ZeroElement; 10277 if (EltTy->isIntegerType()) 10278 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10279 else 10280 ZeroElement = 10281 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10282 10283 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10284 return Success(Elements, E); 10285 } 10286 10287 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10288 VisitIgnoredValue(E->getSubExpr()); 10289 return ZeroInitialization(E); 10290 } 10291 10292 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10293 BinaryOperatorKind Op = E->getOpcode(); 10294 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10295 "Operation not supported on vector types"); 10296 10297 if (Op == BO_Comma) 10298 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10299 10300 Expr *LHS = E->getLHS(); 10301 Expr *RHS = E->getRHS(); 10302 10303 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10304 "Must both be vector types"); 10305 // Checking JUST the types are the same would be fine, except shifts don't 10306 // need to have their types be the same (since you always shift by an int). 10307 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10308 E->getType()->getAs<VectorType>()->getNumElements() && 10309 RHS->getType()->getAs<VectorType>()->getNumElements() == 10310 E->getType()->getAs<VectorType>()->getNumElements() && 10311 "All operands must be the same size."); 10312 10313 APValue LHSValue; 10314 APValue RHSValue; 10315 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10316 if (!LHSOK && !Info.noteFailure()) 10317 return false; 10318 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10319 return false; 10320 10321 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10322 return false; 10323 10324 return Success(LHSValue, E); 10325 } 10326 10327 //===----------------------------------------------------------------------===// 10328 // Array Evaluation 10329 //===----------------------------------------------------------------------===// 10330 10331 namespace { 10332 class ArrayExprEvaluator 10333 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10334 const LValue &This; 10335 APValue &Result; 10336 public: 10337 10338 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10339 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10340 10341 bool Success(const APValue &V, const Expr *E) { 10342 assert(V.isArray() && "expected array"); 10343 Result = V; 10344 return true; 10345 } 10346 10347 bool ZeroInitialization(const Expr *E) { 10348 const ConstantArrayType *CAT = 10349 Info.Ctx.getAsConstantArrayType(E->getType()); 10350 if (!CAT) { 10351 if (E->getType()->isIncompleteArrayType()) { 10352 // We can be asked to zero-initialize a flexible array member; this 10353 // is represented as an ImplicitValueInitExpr of incomplete array 10354 // type. In this case, the array has zero elements. 10355 Result = APValue(APValue::UninitArray(), 0, 0); 10356 return true; 10357 } 10358 // FIXME: We could handle VLAs here. 10359 return Error(E); 10360 } 10361 10362 Result = APValue(APValue::UninitArray(), 0, 10363 CAT->getSize().getZExtValue()); 10364 if (!Result.hasArrayFiller()) return true; 10365 10366 // Zero-initialize all elements. 10367 LValue Subobject = This; 10368 Subobject.addArray(Info, E, CAT); 10369 ImplicitValueInitExpr VIE(CAT->getElementType()); 10370 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10371 } 10372 10373 bool VisitCallExpr(const CallExpr *E) { 10374 return handleCallExpr(E, Result, &This); 10375 } 10376 bool VisitInitListExpr(const InitListExpr *E, 10377 QualType AllocType = QualType()); 10378 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10379 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10380 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10381 const LValue &Subobject, 10382 APValue *Value, QualType Type); 10383 bool VisitStringLiteral(const StringLiteral *E, 10384 QualType AllocType = QualType()) { 10385 expandStringLiteral(Info, E, Result, AllocType); 10386 return true; 10387 } 10388 }; 10389 } // end anonymous namespace 10390 10391 static bool EvaluateArray(const Expr *E, const LValue &This, 10392 APValue &Result, EvalInfo &Info) { 10393 assert(!E->isValueDependent()); 10394 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10395 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10396 } 10397 10398 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10399 APValue &Result, const InitListExpr *ILE, 10400 QualType AllocType) { 10401 assert(!ILE->isValueDependent()); 10402 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10403 "not an array rvalue"); 10404 return ArrayExprEvaluator(Info, This, Result) 10405 .VisitInitListExpr(ILE, AllocType); 10406 } 10407 10408 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10409 APValue &Result, 10410 const CXXConstructExpr *CCE, 10411 QualType AllocType) { 10412 assert(!CCE->isValueDependent()); 10413 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10414 "not an array rvalue"); 10415 return ArrayExprEvaluator(Info, This, Result) 10416 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10417 } 10418 10419 // Return true iff the given array filler may depend on the element index. 10420 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10421 // For now, just allow non-class value-initialization and initialization 10422 // lists comprised of them. 10423 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10424 return false; 10425 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10426 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10427 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10428 return true; 10429 } 10430 return false; 10431 } 10432 return true; 10433 } 10434 10435 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10436 QualType AllocType) { 10437 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10438 AllocType.isNull() ? E->getType() : AllocType); 10439 if (!CAT) 10440 return Error(E); 10441 10442 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10443 // an appropriately-typed string literal enclosed in braces. 10444 if (E->isStringLiteralInit()) { 10445 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10446 // FIXME: Support ObjCEncodeExpr here once we support it in 10447 // ArrayExprEvaluator generally. 10448 if (!SL) 10449 return Error(E); 10450 return VisitStringLiteral(SL, AllocType); 10451 } 10452 10453 bool Success = true; 10454 10455 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10456 "zero-initialized array shouldn't have any initialized elts"); 10457 APValue Filler; 10458 if (Result.isArray() && Result.hasArrayFiller()) 10459 Filler = Result.getArrayFiller(); 10460 10461 unsigned NumEltsToInit = E->getNumInits(); 10462 unsigned NumElts = CAT->getSize().getZExtValue(); 10463 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10464 10465 // If the initializer might depend on the array index, run it for each 10466 // array element. 10467 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10468 NumEltsToInit = NumElts; 10469 10470 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10471 << NumEltsToInit << ".\n"); 10472 10473 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10474 10475 // If the array was previously zero-initialized, preserve the 10476 // zero-initialized values. 10477 if (Filler.hasValue()) { 10478 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10479 Result.getArrayInitializedElt(I) = Filler; 10480 if (Result.hasArrayFiller()) 10481 Result.getArrayFiller() = Filler; 10482 } 10483 10484 LValue Subobject = This; 10485 Subobject.addArray(Info, E, CAT); 10486 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10487 const Expr *Init = 10488 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10489 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10490 Info, Subobject, Init) || 10491 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10492 CAT->getElementType(), 1)) { 10493 if (!Info.noteFailure()) 10494 return false; 10495 Success = false; 10496 } 10497 } 10498 10499 if (!Result.hasArrayFiller()) 10500 return Success; 10501 10502 // If we get here, we have a trivial filler, which we can just evaluate 10503 // once and splat over the rest of the array elements. 10504 assert(FillerExpr && "no array filler for incomplete init list"); 10505 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10506 FillerExpr) && Success; 10507 } 10508 10509 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10510 LValue CommonLV; 10511 if (E->getCommonExpr() && 10512 !Evaluate(Info.CurrentCall->createTemporary( 10513 E->getCommonExpr(), 10514 getStorageType(Info.Ctx, E->getCommonExpr()), 10515 ScopeKind::FullExpression, CommonLV), 10516 Info, E->getCommonExpr()->getSourceExpr())) 10517 return false; 10518 10519 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10520 10521 uint64_t Elements = CAT->getSize().getZExtValue(); 10522 Result = APValue(APValue::UninitArray(), Elements, Elements); 10523 10524 LValue Subobject = This; 10525 Subobject.addArray(Info, E, CAT); 10526 10527 bool Success = true; 10528 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10529 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10530 Info, Subobject, E->getSubExpr()) || 10531 !HandleLValueArrayAdjustment(Info, E, Subobject, 10532 CAT->getElementType(), 1)) { 10533 if (!Info.noteFailure()) 10534 return false; 10535 Success = false; 10536 } 10537 } 10538 10539 return Success; 10540 } 10541 10542 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10543 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10544 } 10545 10546 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10547 const LValue &Subobject, 10548 APValue *Value, 10549 QualType Type) { 10550 bool HadZeroInit = Value->hasValue(); 10551 10552 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10553 unsigned N = CAT->getSize().getZExtValue(); 10554 10555 // Preserve the array filler if we had prior zero-initialization. 10556 APValue Filler = 10557 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10558 : APValue(); 10559 10560 *Value = APValue(APValue::UninitArray(), N, N); 10561 10562 if (HadZeroInit) 10563 for (unsigned I = 0; I != N; ++I) 10564 Value->getArrayInitializedElt(I) = Filler; 10565 10566 // Initialize the elements. 10567 LValue ArrayElt = Subobject; 10568 ArrayElt.addArray(Info, E, CAT); 10569 for (unsigned I = 0; I != N; ++I) 10570 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10571 CAT->getElementType()) || 10572 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10573 CAT->getElementType(), 1)) 10574 return false; 10575 10576 return true; 10577 } 10578 10579 if (!Type->isRecordType()) 10580 return Error(E); 10581 10582 return RecordExprEvaluator(Info, Subobject, *Value) 10583 .VisitCXXConstructExpr(E, Type); 10584 } 10585 10586 //===----------------------------------------------------------------------===// 10587 // Integer Evaluation 10588 // 10589 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10590 // types and back in constant folding. Integer values are thus represented 10591 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10592 //===----------------------------------------------------------------------===// 10593 10594 namespace { 10595 class IntExprEvaluator 10596 : public ExprEvaluatorBase<IntExprEvaluator> { 10597 APValue &Result; 10598 public: 10599 IntExprEvaluator(EvalInfo &info, APValue &result) 10600 : ExprEvaluatorBaseTy(info), Result(result) {} 10601 10602 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10603 assert(E->getType()->isIntegralOrEnumerationType() && 10604 "Invalid evaluation result."); 10605 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10606 "Invalid evaluation result."); 10607 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10608 "Invalid evaluation result."); 10609 Result = APValue(SI); 10610 return true; 10611 } 10612 bool Success(const llvm::APSInt &SI, const Expr *E) { 10613 return Success(SI, E, Result); 10614 } 10615 10616 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10617 assert(E->getType()->isIntegralOrEnumerationType() && 10618 "Invalid evaluation result."); 10619 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10620 "Invalid evaluation result."); 10621 Result = APValue(APSInt(I)); 10622 Result.getInt().setIsUnsigned( 10623 E->getType()->isUnsignedIntegerOrEnumerationType()); 10624 return true; 10625 } 10626 bool Success(const llvm::APInt &I, const Expr *E) { 10627 return Success(I, E, Result); 10628 } 10629 10630 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10631 assert(E->getType()->isIntegralOrEnumerationType() && 10632 "Invalid evaluation result."); 10633 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10634 return true; 10635 } 10636 bool Success(uint64_t Value, const Expr *E) { 10637 return Success(Value, E, Result); 10638 } 10639 10640 bool Success(CharUnits Size, const Expr *E) { 10641 return Success(Size.getQuantity(), E); 10642 } 10643 10644 bool Success(const APValue &V, const Expr *E) { 10645 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10646 Result = V; 10647 return true; 10648 } 10649 return Success(V.getInt(), E); 10650 } 10651 10652 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10653 10654 //===--------------------------------------------------------------------===// 10655 // Visitor Methods 10656 //===--------------------------------------------------------------------===// 10657 10658 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10659 return Success(E->getValue(), E); 10660 } 10661 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10662 return Success(E->getValue(), E); 10663 } 10664 10665 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10666 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10667 if (CheckReferencedDecl(E, E->getDecl())) 10668 return true; 10669 10670 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10671 } 10672 bool VisitMemberExpr(const MemberExpr *E) { 10673 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10674 VisitIgnoredBaseExpression(E->getBase()); 10675 return true; 10676 } 10677 10678 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10679 } 10680 10681 bool VisitCallExpr(const CallExpr *E); 10682 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10683 bool VisitBinaryOperator(const BinaryOperator *E); 10684 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10685 bool VisitUnaryOperator(const UnaryOperator *E); 10686 10687 bool VisitCastExpr(const CastExpr* E); 10688 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10689 10690 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10691 return Success(E->getValue(), E); 10692 } 10693 10694 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10695 return Success(E->getValue(), E); 10696 } 10697 10698 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10699 if (Info.ArrayInitIndex == uint64_t(-1)) { 10700 // We were asked to evaluate this subexpression independent of the 10701 // enclosing ArrayInitLoopExpr. We can't do that. 10702 Info.FFDiag(E); 10703 return false; 10704 } 10705 return Success(Info.ArrayInitIndex, E); 10706 } 10707 10708 // Note, GNU defines __null as an integer, not a pointer. 10709 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10710 return ZeroInitialization(E); 10711 } 10712 10713 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10714 return Success(E->getValue(), E); 10715 } 10716 10717 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10718 return Success(E->getValue(), E); 10719 } 10720 10721 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10722 return Success(E->getValue(), E); 10723 } 10724 10725 bool VisitUnaryReal(const UnaryOperator *E); 10726 bool VisitUnaryImag(const UnaryOperator *E); 10727 10728 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10729 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10730 bool VisitSourceLocExpr(const SourceLocExpr *E); 10731 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10732 bool VisitRequiresExpr(const RequiresExpr *E); 10733 // FIXME: Missing: array subscript of vector, member of vector 10734 }; 10735 10736 class FixedPointExprEvaluator 10737 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10738 APValue &Result; 10739 10740 public: 10741 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10742 : ExprEvaluatorBaseTy(info), Result(result) {} 10743 10744 bool Success(const llvm::APInt &I, const Expr *E) { 10745 return Success( 10746 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10747 } 10748 10749 bool Success(uint64_t Value, const Expr *E) { 10750 return Success( 10751 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10752 } 10753 10754 bool Success(const APValue &V, const Expr *E) { 10755 return Success(V.getFixedPoint(), E); 10756 } 10757 10758 bool Success(const APFixedPoint &V, const Expr *E) { 10759 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10760 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10761 "Invalid evaluation result."); 10762 Result = APValue(V); 10763 return true; 10764 } 10765 10766 //===--------------------------------------------------------------------===// 10767 // Visitor Methods 10768 //===--------------------------------------------------------------------===// 10769 10770 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10771 return Success(E->getValue(), E); 10772 } 10773 10774 bool VisitCastExpr(const CastExpr *E); 10775 bool VisitUnaryOperator(const UnaryOperator *E); 10776 bool VisitBinaryOperator(const BinaryOperator *E); 10777 }; 10778 } // end anonymous namespace 10779 10780 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10781 /// produce either the integer value or a pointer. 10782 /// 10783 /// GCC has a heinous extension which folds casts between pointer types and 10784 /// pointer-sized integral types. We support this by allowing the evaluation of 10785 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10786 /// Some simple arithmetic on such values is supported (they are treated much 10787 /// like char*). 10788 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10789 EvalInfo &Info) { 10790 assert(!E->isValueDependent()); 10791 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10792 return IntExprEvaluator(Info, Result).Visit(E); 10793 } 10794 10795 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10796 assert(!E->isValueDependent()); 10797 APValue Val; 10798 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10799 return false; 10800 if (!Val.isInt()) { 10801 // FIXME: It would be better to produce the diagnostic for casting 10802 // a pointer to an integer. 10803 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10804 return false; 10805 } 10806 Result = Val.getInt(); 10807 return true; 10808 } 10809 10810 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10811 APValue Evaluated = E->EvaluateInContext( 10812 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10813 return Success(Evaluated, E); 10814 } 10815 10816 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10817 EvalInfo &Info) { 10818 assert(!E->isValueDependent()); 10819 if (E->getType()->isFixedPointType()) { 10820 APValue Val; 10821 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10822 return false; 10823 if (!Val.isFixedPoint()) 10824 return false; 10825 10826 Result = Val.getFixedPoint(); 10827 return true; 10828 } 10829 return false; 10830 } 10831 10832 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10833 EvalInfo &Info) { 10834 assert(!E->isValueDependent()); 10835 if (E->getType()->isIntegerType()) { 10836 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10837 APSInt Val; 10838 if (!EvaluateInteger(E, Val, Info)) 10839 return false; 10840 Result = APFixedPoint(Val, FXSema); 10841 return true; 10842 } else if (E->getType()->isFixedPointType()) { 10843 return EvaluateFixedPoint(E, Result, Info); 10844 } 10845 return false; 10846 } 10847 10848 /// Check whether the given declaration can be directly converted to an integral 10849 /// rvalue. If not, no diagnostic is produced; there are other things we can 10850 /// try. 10851 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10852 // Enums are integer constant exprs. 10853 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10854 // Check for signedness/width mismatches between E type and ECD value. 10855 bool SameSign = (ECD->getInitVal().isSigned() 10856 == E->getType()->isSignedIntegerOrEnumerationType()); 10857 bool SameWidth = (ECD->getInitVal().getBitWidth() 10858 == Info.Ctx.getIntWidth(E->getType())); 10859 if (SameSign && SameWidth) 10860 return Success(ECD->getInitVal(), E); 10861 else { 10862 // Get rid of mismatch (otherwise Success assertions will fail) 10863 // by computing a new value matching the type of E. 10864 llvm::APSInt Val = ECD->getInitVal(); 10865 if (!SameSign) 10866 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10867 if (!SameWidth) 10868 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10869 return Success(Val, E); 10870 } 10871 } 10872 return false; 10873 } 10874 10875 /// Values returned by __builtin_classify_type, chosen to match the values 10876 /// produced by GCC's builtin. 10877 enum class GCCTypeClass { 10878 None = -1, 10879 Void = 0, 10880 Integer = 1, 10881 // GCC reserves 2 for character types, but instead classifies them as 10882 // integers. 10883 Enum = 3, 10884 Bool = 4, 10885 Pointer = 5, 10886 // GCC reserves 6 for references, but appears to never use it (because 10887 // expressions never have reference type, presumably). 10888 PointerToDataMember = 7, 10889 RealFloat = 8, 10890 Complex = 9, 10891 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10892 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10893 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10894 // uses 12 for that purpose, same as for a class or struct. Maybe it 10895 // internally implements a pointer to member as a struct? Who knows. 10896 PointerToMemberFunction = 12, // Not a bug, see above. 10897 ClassOrStruct = 12, 10898 Union = 13, 10899 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10900 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10901 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10902 // literals. 10903 }; 10904 10905 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10906 /// as GCC. 10907 static GCCTypeClass 10908 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10909 assert(!T->isDependentType() && "unexpected dependent type"); 10910 10911 QualType CanTy = T.getCanonicalType(); 10912 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10913 10914 switch (CanTy->getTypeClass()) { 10915 #define TYPE(ID, BASE) 10916 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10917 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10918 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10919 #include "clang/AST/TypeNodes.inc" 10920 case Type::Auto: 10921 case Type::DeducedTemplateSpecialization: 10922 llvm_unreachable("unexpected non-canonical or dependent type"); 10923 10924 case Type::Builtin: 10925 switch (BT->getKind()) { 10926 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10927 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10928 case BuiltinType::ID: return GCCTypeClass::Integer; 10929 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10930 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10931 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10932 case BuiltinType::ID: break; 10933 #include "clang/AST/BuiltinTypes.def" 10934 case BuiltinType::Void: 10935 return GCCTypeClass::Void; 10936 10937 case BuiltinType::Bool: 10938 return GCCTypeClass::Bool; 10939 10940 case BuiltinType::Char_U: 10941 case BuiltinType::UChar: 10942 case BuiltinType::WChar_U: 10943 case BuiltinType::Char8: 10944 case BuiltinType::Char16: 10945 case BuiltinType::Char32: 10946 case BuiltinType::UShort: 10947 case BuiltinType::UInt: 10948 case BuiltinType::ULong: 10949 case BuiltinType::ULongLong: 10950 case BuiltinType::UInt128: 10951 return GCCTypeClass::Integer; 10952 10953 case BuiltinType::UShortAccum: 10954 case BuiltinType::UAccum: 10955 case BuiltinType::ULongAccum: 10956 case BuiltinType::UShortFract: 10957 case BuiltinType::UFract: 10958 case BuiltinType::ULongFract: 10959 case BuiltinType::SatUShortAccum: 10960 case BuiltinType::SatUAccum: 10961 case BuiltinType::SatULongAccum: 10962 case BuiltinType::SatUShortFract: 10963 case BuiltinType::SatUFract: 10964 case BuiltinType::SatULongFract: 10965 return GCCTypeClass::None; 10966 10967 case BuiltinType::NullPtr: 10968 10969 case BuiltinType::ObjCId: 10970 case BuiltinType::ObjCClass: 10971 case BuiltinType::ObjCSel: 10972 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10973 case BuiltinType::Id: 10974 #include "clang/Basic/OpenCLImageTypes.def" 10975 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10976 case BuiltinType::Id: 10977 #include "clang/Basic/OpenCLExtensionTypes.def" 10978 case BuiltinType::OCLSampler: 10979 case BuiltinType::OCLEvent: 10980 case BuiltinType::OCLClkEvent: 10981 case BuiltinType::OCLQueue: 10982 case BuiltinType::OCLReserveID: 10983 #define SVE_TYPE(Name, Id, SingletonId) \ 10984 case BuiltinType::Id: 10985 #include "clang/Basic/AArch64SVEACLETypes.def" 10986 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 10987 case BuiltinType::Id: 10988 #include "clang/Basic/PPCTypes.def" 10989 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 10990 #include "clang/Basic/RISCVVTypes.def" 10991 return GCCTypeClass::None; 10992 10993 case BuiltinType::Dependent: 10994 llvm_unreachable("unexpected dependent type"); 10995 }; 10996 llvm_unreachable("unexpected placeholder type"); 10997 10998 case Type::Enum: 10999 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11000 11001 case Type::Pointer: 11002 case Type::ConstantArray: 11003 case Type::VariableArray: 11004 case Type::IncompleteArray: 11005 case Type::FunctionNoProto: 11006 case Type::FunctionProto: 11007 return GCCTypeClass::Pointer; 11008 11009 case Type::MemberPointer: 11010 return CanTy->isMemberDataPointerType() 11011 ? GCCTypeClass::PointerToDataMember 11012 : GCCTypeClass::PointerToMemberFunction; 11013 11014 case Type::Complex: 11015 return GCCTypeClass::Complex; 11016 11017 case Type::Record: 11018 return CanTy->isUnionType() ? GCCTypeClass::Union 11019 : GCCTypeClass::ClassOrStruct; 11020 11021 case Type::Atomic: 11022 // GCC classifies _Atomic T the same as T. 11023 return EvaluateBuiltinClassifyType( 11024 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11025 11026 case Type::BlockPointer: 11027 case Type::Vector: 11028 case Type::ExtVector: 11029 case Type::ConstantMatrix: 11030 case Type::ObjCObject: 11031 case Type::ObjCInterface: 11032 case Type::ObjCObjectPointer: 11033 case Type::Pipe: 11034 case Type::ExtInt: 11035 // GCC classifies vectors as None. We follow its lead and classify all 11036 // other types that don't fit into the regular classification the same way. 11037 return GCCTypeClass::None; 11038 11039 case Type::LValueReference: 11040 case Type::RValueReference: 11041 llvm_unreachable("invalid type for expression"); 11042 } 11043 11044 llvm_unreachable("unexpected type class"); 11045 } 11046 11047 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11048 /// as GCC. 11049 static GCCTypeClass 11050 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11051 // If no argument was supplied, default to None. This isn't 11052 // ideal, however it is what gcc does. 11053 if (E->getNumArgs() == 0) 11054 return GCCTypeClass::None; 11055 11056 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11057 // being an ICE, but still folds it to a constant using the type of the first 11058 // argument. 11059 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11060 } 11061 11062 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11063 /// __builtin_constant_p when applied to the given pointer. 11064 /// 11065 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11066 /// or it points to the first character of a string literal. 11067 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11068 APValue::LValueBase Base = LV.getLValueBase(); 11069 if (Base.isNull()) { 11070 // A null base is acceptable. 11071 return true; 11072 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11073 if (!isa<StringLiteral>(E)) 11074 return false; 11075 return LV.getLValueOffset().isZero(); 11076 } else if (Base.is<TypeInfoLValue>()) { 11077 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11078 // evaluate to true. 11079 return true; 11080 } else { 11081 // Any other base is not constant enough for GCC. 11082 return false; 11083 } 11084 } 11085 11086 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11087 /// GCC as we can manage. 11088 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11089 // This evaluation is not permitted to have side-effects, so evaluate it in 11090 // a speculative evaluation context. 11091 SpeculativeEvaluationRAII SpeculativeEval(Info); 11092 11093 // Constant-folding is always enabled for the operand of __builtin_constant_p 11094 // (even when the enclosing evaluation context otherwise requires a strict 11095 // language-specific constant expression). 11096 FoldConstant Fold(Info, true); 11097 11098 QualType ArgType = Arg->getType(); 11099 11100 // __builtin_constant_p always has one operand. The rules which gcc follows 11101 // are not precisely documented, but are as follows: 11102 // 11103 // - If the operand is of integral, floating, complex or enumeration type, 11104 // and can be folded to a known value of that type, it returns 1. 11105 // - If the operand can be folded to a pointer to the first character 11106 // of a string literal (or such a pointer cast to an integral type) 11107 // or to a null pointer or an integer cast to a pointer, it returns 1. 11108 // 11109 // Otherwise, it returns 0. 11110 // 11111 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11112 // its support for this did not work prior to GCC 9 and is not yet well 11113 // understood. 11114 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11115 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11116 ArgType->isNullPtrType()) { 11117 APValue V; 11118 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11119 Fold.keepDiagnostics(); 11120 return false; 11121 } 11122 11123 // For a pointer (possibly cast to integer), there are special rules. 11124 if (V.getKind() == APValue::LValue) 11125 return EvaluateBuiltinConstantPForLValue(V); 11126 11127 // Otherwise, any constant value is good enough. 11128 return V.hasValue(); 11129 } 11130 11131 // Anything else isn't considered to be sufficiently constant. 11132 return false; 11133 } 11134 11135 /// Retrieves the "underlying object type" of the given expression, 11136 /// as used by __builtin_object_size. 11137 static QualType getObjectType(APValue::LValueBase B) { 11138 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11139 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11140 return VD->getType(); 11141 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11142 if (isa<CompoundLiteralExpr>(E)) 11143 return E->getType(); 11144 } else if (B.is<TypeInfoLValue>()) { 11145 return B.getTypeInfoType(); 11146 } else if (B.is<DynamicAllocLValue>()) { 11147 return B.getDynamicAllocType(); 11148 } 11149 11150 return QualType(); 11151 } 11152 11153 /// A more selective version of E->IgnoreParenCasts for 11154 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11155 /// to change the type of E. 11156 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11157 /// 11158 /// Always returns an RValue with a pointer representation. 11159 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11160 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11161 11162 auto *NoParens = E->IgnoreParens(); 11163 auto *Cast = dyn_cast<CastExpr>(NoParens); 11164 if (Cast == nullptr) 11165 return NoParens; 11166 11167 // We only conservatively allow a few kinds of casts, because this code is 11168 // inherently a simple solution that seeks to support the common case. 11169 auto CastKind = Cast->getCastKind(); 11170 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11171 CastKind != CK_AddressSpaceConversion) 11172 return NoParens; 11173 11174 auto *SubExpr = Cast->getSubExpr(); 11175 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11176 return NoParens; 11177 return ignorePointerCastsAndParens(SubExpr); 11178 } 11179 11180 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11181 /// record layout. e.g. 11182 /// struct { struct { int a, b; } fst, snd; } obj; 11183 /// obj.fst // no 11184 /// obj.snd // yes 11185 /// obj.fst.a // no 11186 /// obj.fst.b // no 11187 /// obj.snd.a // no 11188 /// obj.snd.b // yes 11189 /// 11190 /// Please note: this function is specialized for how __builtin_object_size 11191 /// views "objects". 11192 /// 11193 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11194 /// correct result, it will always return true. 11195 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11196 assert(!LVal.Designator.Invalid); 11197 11198 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11199 const RecordDecl *Parent = FD->getParent(); 11200 Invalid = Parent->isInvalidDecl(); 11201 if (Invalid || Parent->isUnion()) 11202 return true; 11203 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11204 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11205 }; 11206 11207 auto &Base = LVal.getLValueBase(); 11208 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11209 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11210 bool Invalid; 11211 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11212 return Invalid; 11213 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11214 for (auto *FD : IFD->chain()) { 11215 bool Invalid; 11216 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11217 return Invalid; 11218 } 11219 } 11220 } 11221 11222 unsigned I = 0; 11223 QualType BaseType = getType(Base); 11224 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11225 // If we don't know the array bound, conservatively assume we're looking at 11226 // the final array element. 11227 ++I; 11228 if (BaseType->isIncompleteArrayType()) 11229 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11230 else 11231 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11232 } 11233 11234 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11235 const auto &Entry = LVal.Designator.Entries[I]; 11236 if (BaseType->isArrayType()) { 11237 // Because __builtin_object_size treats arrays as objects, we can ignore 11238 // the index iff this is the last array in the Designator. 11239 if (I + 1 == E) 11240 return true; 11241 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11242 uint64_t Index = Entry.getAsArrayIndex(); 11243 if (Index + 1 != CAT->getSize()) 11244 return false; 11245 BaseType = CAT->getElementType(); 11246 } else if (BaseType->isAnyComplexType()) { 11247 const auto *CT = BaseType->castAs<ComplexType>(); 11248 uint64_t Index = Entry.getAsArrayIndex(); 11249 if (Index != 1) 11250 return false; 11251 BaseType = CT->getElementType(); 11252 } else if (auto *FD = getAsField(Entry)) { 11253 bool Invalid; 11254 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11255 return Invalid; 11256 BaseType = FD->getType(); 11257 } else { 11258 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11259 return false; 11260 } 11261 } 11262 return true; 11263 } 11264 11265 /// Tests to see if the LValue has a user-specified designator (that isn't 11266 /// necessarily valid). Note that this always returns 'true' if the LValue has 11267 /// an unsized array as its first designator entry, because there's currently no 11268 /// way to tell if the user typed *foo or foo[0]. 11269 static bool refersToCompleteObject(const LValue &LVal) { 11270 if (LVal.Designator.Invalid) 11271 return false; 11272 11273 if (!LVal.Designator.Entries.empty()) 11274 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11275 11276 if (!LVal.InvalidBase) 11277 return true; 11278 11279 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11280 // the LValueBase. 11281 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11282 return !E || !isa<MemberExpr>(E); 11283 } 11284 11285 /// Attempts to detect a user writing into a piece of memory that's impossible 11286 /// to figure out the size of by just using types. 11287 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11288 const SubobjectDesignator &Designator = LVal.Designator; 11289 // Notes: 11290 // - Users can only write off of the end when we have an invalid base. Invalid 11291 // bases imply we don't know where the memory came from. 11292 // - We used to be a bit more aggressive here; we'd only be conservative if 11293 // the array at the end was flexible, or if it had 0 or 1 elements. This 11294 // broke some common standard library extensions (PR30346), but was 11295 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11296 // with some sort of list. OTOH, it seems that GCC is always 11297 // conservative with the last element in structs (if it's an array), so our 11298 // current behavior is more compatible than an explicit list approach would 11299 // be. 11300 return LVal.InvalidBase && 11301 Designator.Entries.size() == Designator.MostDerivedPathLength && 11302 Designator.MostDerivedIsArrayElement && 11303 isDesignatorAtObjectEnd(Ctx, LVal); 11304 } 11305 11306 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11307 /// Fails if the conversion would cause loss of precision. 11308 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11309 CharUnits &Result) { 11310 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11311 if (Int.ugt(CharUnitsMax)) 11312 return false; 11313 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11314 return true; 11315 } 11316 11317 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11318 /// determine how many bytes exist from the beginning of the object to either 11319 /// the end of the current subobject, or the end of the object itself, depending 11320 /// on what the LValue looks like + the value of Type. 11321 /// 11322 /// If this returns false, the value of Result is undefined. 11323 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11324 unsigned Type, const LValue &LVal, 11325 CharUnits &EndOffset) { 11326 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11327 11328 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11329 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11330 return false; 11331 return HandleSizeof(Info, ExprLoc, Ty, Result); 11332 }; 11333 11334 // We want to evaluate the size of the entire object. This is a valid fallback 11335 // for when Type=1 and the designator is invalid, because we're asked for an 11336 // upper-bound. 11337 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11338 // Type=3 wants a lower bound, so we can't fall back to this. 11339 if (Type == 3 && !DetermineForCompleteObject) 11340 return false; 11341 11342 llvm::APInt APEndOffset; 11343 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11344 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11345 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11346 11347 if (LVal.InvalidBase) 11348 return false; 11349 11350 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11351 return CheckedHandleSizeof(BaseTy, EndOffset); 11352 } 11353 11354 // We want to evaluate the size of a subobject. 11355 const SubobjectDesignator &Designator = LVal.Designator; 11356 11357 // The following is a moderately common idiom in C: 11358 // 11359 // struct Foo { int a; char c[1]; }; 11360 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11361 // strcpy(&F->c[0], Bar); 11362 // 11363 // In order to not break too much legacy code, we need to support it. 11364 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11365 // If we can resolve this to an alloc_size call, we can hand that back, 11366 // because we know for certain how many bytes there are to write to. 11367 llvm::APInt APEndOffset; 11368 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11369 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11370 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11371 11372 // If we cannot determine the size of the initial allocation, then we can't 11373 // given an accurate upper-bound. However, we are still able to give 11374 // conservative lower-bounds for Type=3. 11375 if (Type == 1) 11376 return false; 11377 } 11378 11379 CharUnits BytesPerElem; 11380 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11381 return false; 11382 11383 // According to the GCC documentation, we want the size of the subobject 11384 // denoted by the pointer. But that's not quite right -- what we actually 11385 // want is the size of the immediately-enclosing array, if there is one. 11386 int64_t ElemsRemaining; 11387 if (Designator.MostDerivedIsArrayElement && 11388 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11389 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11390 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11391 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11392 } else { 11393 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11394 } 11395 11396 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11397 return true; 11398 } 11399 11400 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11401 /// returns true and stores the result in @p Size. 11402 /// 11403 /// If @p WasError is non-null, this will report whether the failure to evaluate 11404 /// is to be treated as an Error in IntExprEvaluator. 11405 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11406 EvalInfo &Info, uint64_t &Size) { 11407 // Determine the denoted object. 11408 LValue LVal; 11409 { 11410 // The operand of __builtin_object_size is never evaluated for side-effects. 11411 // If there are any, but we can determine the pointed-to object anyway, then 11412 // ignore the side-effects. 11413 SpeculativeEvaluationRAII SpeculativeEval(Info); 11414 IgnoreSideEffectsRAII Fold(Info); 11415 11416 if (E->isGLValue()) { 11417 // It's possible for us to be given GLValues if we're called via 11418 // Expr::tryEvaluateObjectSize. 11419 APValue RVal; 11420 if (!EvaluateAsRValue(Info, E, RVal)) 11421 return false; 11422 LVal.setFrom(Info.Ctx, RVal); 11423 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11424 /*InvalidBaseOK=*/true)) 11425 return false; 11426 } 11427 11428 // If we point to before the start of the object, there are no accessible 11429 // bytes. 11430 if (LVal.getLValueOffset().isNegative()) { 11431 Size = 0; 11432 return true; 11433 } 11434 11435 CharUnits EndOffset; 11436 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11437 return false; 11438 11439 // If we've fallen outside of the end offset, just pretend there's nothing to 11440 // write to/read from. 11441 if (EndOffset <= LVal.getLValueOffset()) 11442 Size = 0; 11443 else 11444 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11445 return true; 11446 } 11447 11448 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11449 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11450 return VisitBuiltinCallExpr(E, BuiltinOp); 11451 11452 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11453 } 11454 11455 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11456 APValue &Val, APSInt &Alignment) { 11457 QualType SrcTy = E->getArg(0)->getType(); 11458 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11459 return false; 11460 // Even though we are evaluating integer expressions we could get a pointer 11461 // argument for the __builtin_is_aligned() case. 11462 if (SrcTy->isPointerType()) { 11463 LValue Ptr; 11464 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11465 return false; 11466 Ptr.moveInto(Val); 11467 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11468 Info.FFDiag(E->getArg(0)); 11469 return false; 11470 } else { 11471 APSInt SrcInt; 11472 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11473 return false; 11474 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11475 "Bit widths must be the same"); 11476 Val = APValue(SrcInt); 11477 } 11478 assert(Val.hasValue()); 11479 return true; 11480 } 11481 11482 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11483 unsigned BuiltinOp) { 11484 switch (BuiltinOp) { 11485 default: 11486 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11487 11488 case Builtin::BI__builtin_dynamic_object_size: 11489 case Builtin::BI__builtin_object_size: { 11490 // The type was checked when we built the expression. 11491 unsigned Type = 11492 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11493 assert(Type <= 3 && "unexpected type"); 11494 11495 uint64_t Size; 11496 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11497 return Success(Size, E); 11498 11499 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11500 return Success((Type & 2) ? 0 : -1, E); 11501 11502 // Expression had no side effects, but we couldn't statically determine the 11503 // size of the referenced object. 11504 switch (Info.EvalMode) { 11505 case EvalInfo::EM_ConstantExpression: 11506 case EvalInfo::EM_ConstantFold: 11507 case EvalInfo::EM_IgnoreSideEffects: 11508 // Leave it to IR generation. 11509 return Error(E); 11510 case EvalInfo::EM_ConstantExpressionUnevaluated: 11511 // Reduce it to a constant now. 11512 return Success((Type & 2) ? 0 : -1, E); 11513 } 11514 11515 llvm_unreachable("unexpected EvalMode"); 11516 } 11517 11518 case Builtin::BI__builtin_os_log_format_buffer_size: { 11519 analyze_os_log::OSLogBufferLayout Layout; 11520 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11521 return Success(Layout.size().getQuantity(), E); 11522 } 11523 11524 case Builtin::BI__builtin_is_aligned: { 11525 APValue Src; 11526 APSInt Alignment; 11527 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11528 return false; 11529 if (Src.isLValue()) { 11530 // If we evaluated a pointer, check the minimum known alignment. 11531 LValue Ptr; 11532 Ptr.setFrom(Info.Ctx, Src); 11533 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11534 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11535 // We can return true if the known alignment at the computed offset is 11536 // greater than the requested alignment. 11537 assert(PtrAlign.isPowerOfTwo()); 11538 assert(Alignment.isPowerOf2()); 11539 if (PtrAlign.getQuantity() >= Alignment) 11540 return Success(1, E); 11541 // If the alignment is not known to be sufficient, some cases could still 11542 // be aligned at run time. However, if the requested alignment is less or 11543 // equal to the base alignment and the offset is not aligned, we know that 11544 // the run-time value can never be aligned. 11545 if (BaseAlignment.getQuantity() >= Alignment && 11546 PtrAlign.getQuantity() < Alignment) 11547 return Success(0, E); 11548 // Otherwise we can't infer whether the value is sufficiently aligned. 11549 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11550 // in cases where we can't fully evaluate the pointer. 11551 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11552 << Alignment; 11553 return false; 11554 } 11555 assert(Src.isInt()); 11556 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11557 } 11558 case Builtin::BI__builtin_align_up: { 11559 APValue Src; 11560 APSInt Alignment; 11561 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11562 return false; 11563 if (!Src.isInt()) 11564 return Error(E); 11565 APSInt AlignedVal = 11566 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11567 Src.getInt().isUnsigned()); 11568 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11569 return Success(AlignedVal, E); 11570 } 11571 case Builtin::BI__builtin_align_down: { 11572 APValue Src; 11573 APSInt Alignment; 11574 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11575 return false; 11576 if (!Src.isInt()) 11577 return Error(E); 11578 APSInt AlignedVal = 11579 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11580 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11581 return Success(AlignedVal, E); 11582 } 11583 11584 case Builtin::BI__builtin_bitreverse8: 11585 case Builtin::BI__builtin_bitreverse16: 11586 case Builtin::BI__builtin_bitreverse32: 11587 case Builtin::BI__builtin_bitreverse64: { 11588 APSInt Val; 11589 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11590 return false; 11591 11592 return Success(Val.reverseBits(), E); 11593 } 11594 11595 case Builtin::BI__builtin_bswap16: 11596 case Builtin::BI__builtin_bswap32: 11597 case Builtin::BI__builtin_bswap64: { 11598 APSInt Val; 11599 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11600 return false; 11601 11602 return Success(Val.byteSwap(), E); 11603 } 11604 11605 case Builtin::BI__builtin_classify_type: 11606 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11607 11608 case Builtin::BI__builtin_clrsb: 11609 case Builtin::BI__builtin_clrsbl: 11610 case Builtin::BI__builtin_clrsbll: { 11611 APSInt Val; 11612 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11613 return false; 11614 11615 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11616 } 11617 11618 case Builtin::BI__builtin_clz: 11619 case Builtin::BI__builtin_clzl: 11620 case Builtin::BI__builtin_clzll: 11621 case Builtin::BI__builtin_clzs: { 11622 APSInt Val; 11623 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11624 return false; 11625 if (!Val) 11626 return Error(E); 11627 11628 return Success(Val.countLeadingZeros(), E); 11629 } 11630 11631 case Builtin::BI__builtin_constant_p: { 11632 const Expr *Arg = E->getArg(0); 11633 if (EvaluateBuiltinConstantP(Info, Arg)) 11634 return Success(true, E); 11635 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11636 // Outside a constant context, eagerly evaluate to false in the presence 11637 // of side-effects in order to avoid -Wunsequenced false-positives in 11638 // a branch on __builtin_constant_p(expr). 11639 return Success(false, E); 11640 } 11641 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11642 return false; 11643 } 11644 11645 case Builtin::BI__builtin_is_constant_evaluated: { 11646 const auto *Callee = Info.CurrentCall->getCallee(); 11647 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11648 (Info.CallStackDepth == 1 || 11649 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11650 Callee->getIdentifier() && 11651 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11652 // FIXME: Find a better way to avoid duplicated diagnostics. 11653 if (Info.EvalStatus.Diag) 11654 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11655 : Info.CurrentCall->CallLoc, 11656 diag::warn_is_constant_evaluated_always_true_constexpr) 11657 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11658 : "std::is_constant_evaluated"); 11659 } 11660 11661 return Success(Info.InConstantContext, E); 11662 } 11663 11664 case Builtin::BI__builtin_ctz: 11665 case Builtin::BI__builtin_ctzl: 11666 case Builtin::BI__builtin_ctzll: 11667 case Builtin::BI__builtin_ctzs: { 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.countTrailingZeros(), E); 11675 } 11676 11677 case Builtin::BI__builtin_eh_return_data_regno: { 11678 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11679 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11680 return Success(Operand, E); 11681 } 11682 11683 case Builtin::BI__builtin_expect: 11684 case Builtin::BI__builtin_expect_with_probability: 11685 return Visit(E->getArg(0)); 11686 11687 case Builtin::BI__builtin_ffs: 11688 case Builtin::BI__builtin_ffsl: 11689 case Builtin::BI__builtin_ffsll: { 11690 APSInt Val; 11691 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11692 return false; 11693 11694 unsigned N = Val.countTrailingZeros(); 11695 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11696 } 11697 11698 case Builtin::BI__builtin_fpclassify: { 11699 APFloat Val(0.0); 11700 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11701 return false; 11702 unsigned Arg; 11703 switch (Val.getCategory()) { 11704 case APFloat::fcNaN: Arg = 0; break; 11705 case APFloat::fcInfinity: Arg = 1; break; 11706 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11707 case APFloat::fcZero: Arg = 4; break; 11708 } 11709 return Visit(E->getArg(Arg)); 11710 } 11711 11712 case Builtin::BI__builtin_isinf_sign: { 11713 APFloat Val(0.0); 11714 return EvaluateFloat(E->getArg(0), Val, Info) && 11715 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11716 } 11717 11718 case Builtin::BI__builtin_isinf: { 11719 APFloat Val(0.0); 11720 return EvaluateFloat(E->getArg(0), Val, Info) && 11721 Success(Val.isInfinity() ? 1 : 0, E); 11722 } 11723 11724 case Builtin::BI__builtin_isfinite: { 11725 APFloat Val(0.0); 11726 return EvaluateFloat(E->getArg(0), Val, Info) && 11727 Success(Val.isFinite() ? 1 : 0, E); 11728 } 11729 11730 case Builtin::BI__builtin_isnan: { 11731 APFloat Val(0.0); 11732 return EvaluateFloat(E->getArg(0), Val, Info) && 11733 Success(Val.isNaN() ? 1 : 0, E); 11734 } 11735 11736 case Builtin::BI__builtin_isnormal: { 11737 APFloat Val(0.0); 11738 return EvaluateFloat(E->getArg(0), Val, Info) && 11739 Success(Val.isNormal() ? 1 : 0, E); 11740 } 11741 11742 case Builtin::BI__builtin_parity: 11743 case Builtin::BI__builtin_parityl: 11744 case Builtin::BI__builtin_parityll: { 11745 APSInt Val; 11746 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11747 return false; 11748 11749 return Success(Val.countPopulation() % 2, E); 11750 } 11751 11752 case Builtin::BI__builtin_popcount: 11753 case Builtin::BI__builtin_popcountl: 11754 case Builtin::BI__builtin_popcountll: { 11755 APSInt Val; 11756 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11757 return false; 11758 11759 return Success(Val.countPopulation(), E); 11760 } 11761 11762 case Builtin::BI__builtin_rotateleft8: 11763 case Builtin::BI__builtin_rotateleft16: 11764 case Builtin::BI__builtin_rotateleft32: 11765 case Builtin::BI__builtin_rotateleft64: 11766 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11767 case Builtin::BI_rotl16: 11768 case Builtin::BI_rotl: 11769 case Builtin::BI_lrotl: 11770 case Builtin::BI_rotl64: { 11771 APSInt Val, Amt; 11772 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11773 !EvaluateInteger(E->getArg(1), Amt, Info)) 11774 return false; 11775 11776 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11777 } 11778 11779 case Builtin::BI__builtin_rotateright8: 11780 case Builtin::BI__builtin_rotateright16: 11781 case Builtin::BI__builtin_rotateright32: 11782 case Builtin::BI__builtin_rotateright64: 11783 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11784 case Builtin::BI_rotr16: 11785 case Builtin::BI_rotr: 11786 case Builtin::BI_lrotr: 11787 case Builtin::BI_rotr64: { 11788 APSInt Val, Amt; 11789 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11790 !EvaluateInteger(E->getArg(1), Amt, Info)) 11791 return false; 11792 11793 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11794 } 11795 11796 case Builtin::BIstrlen: 11797 case Builtin::BIwcslen: 11798 // A call to strlen is not a constant expression. 11799 if (Info.getLangOpts().CPlusPlus11) 11800 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11801 << /*isConstexpr*/0 << /*isConstructor*/0 11802 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11803 else 11804 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11805 LLVM_FALLTHROUGH; 11806 case Builtin::BI__builtin_strlen: 11807 case Builtin::BI__builtin_wcslen: { 11808 // As an extension, we support __builtin_strlen() as a constant expression, 11809 // and support folding strlen() to a constant. 11810 LValue String; 11811 if (!EvaluatePointer(E->getArg(0), String, Info)) 11812 return false; 11813 11814 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11815 11816 // Fast path: if it's a string literal, search the string value. 11817 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11818 String.getLValueBase().dyn_cast<const Expr *>())) { 11819 // The string literal may have embedded null characters. Find the first 11820 // one and truncate there. 11821 StringRef Str = S->getBytes(); 11822 int64_t Off = String.Offset.getQuantity(); 11823 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11824 S->getCharByteWidth() == 1 && 11825 // FIXME: Add fast-path for wchar_t too. 11826 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11827 Str = Str.substr(Off); 11828 11829 StringRef::size_type Pos = Str.find(0); 11830 if (Pos != StringRef::npos) 11831 Str = Str.substr(0, Pos); 11832 11833 return Success(Str.size(), E); 11834 } 11835 11836 // Fall through to slow path to issue appropriate diagnostic. 11837 } 11838 11839 // Slow path: scan the bytes of the string looking for the terminating 0. 11840 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11841 APValue Char; 11842 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11843 !Char.isInt()) 11844 return false; 11845 if (!Char.getInt()) 11846 return Success(Strlen, E); 11847 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11848 return false; 11849 } 11850 } 11851 11852 case Builtin::BIstrcmp: 11853 case Builtin::BIwcscmp: 11854 case Builtin::BIstrncmp: 11855 case Builtin::BIwcsncmp: 11856 case Builtin::BImemcmp: 11857 case Builtin::BIbcmp: 11858 case Builtin::BIwmemcmp: 11859 // A call to strlen is not a constant expression. 11860 if (Info.getLangOpts().CPlusPlus11) 11861 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11862 << /*isConstexpr*/0 << /*isConstructor*/0 11863 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11864 else 11865 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11866 LLVM_FALLTHROUGH; 11867 case Builtin::BI__builtin_strcmp: 11868 case Builtin::BI__builtin_wcscmp: 11869 case Builtin::BI__builtin_strncmp: 11870 case Builtin::BI__builtin_wcsncmp: 11871 case Builtin::BI__builtin_memcmp: 11872 case Builtin::BI__builtin_bcmp: 11873 case Builtin::BI__builtin_wmemcmp: { 11874 LValue String1, String2; 11875 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11876 !EvaluatePointer(E->getArg(1), String2, Info)) 11877 return false; 11878 11879 uint64_t MaxLength = uint64_t(-1); 11880 if (BuiltinOp != Builtin::BIstrcmp && 11881 BuiltinOp != Builtin::BIwcscmp && 11882 BuiltinOp != Builtin::BI__builtin_strcmp && 11883 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11884 APSInt N; 11885 if (!EvaluateInteger(E->getArg(2), N, Info)) 11886 return false; 11887 MaxLength = N.getExtValue(); 11888 } 11889 11890 // Empty substrings compare equal by definition. 11891 if (MaxLength == 0u) 11892 return Success(0, E); 11893 11894 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11895 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11896 String1.Designator.Invalid || String2.Designator.Invalid) 11897 return false; 11898 11899 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11900 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11901 11902 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11903 BuiltinOp == Builtin::BIbcmp || 11904 BuiltinOp == Builtin::BI__builtin_memcmp || 11905 BuiltinOp == Builtin::BI__builtin_bcmp; 11906 11907 assert(IsRawByte || 11908 (Info.Ctx.hasSameUnqualifiedType( 11909 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11910 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11911 11912 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11913 // 'char8_t', but no other types. 11914 if (IsRawByte && 11915 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11916 // FIXME: Consider using our bit_cast implementation to support this. 11917 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11918 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11919 << CharTy1 << CharTy2; 11920 return false; 11921 } 11922 11923 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11924 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11925 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11926 Char1.isInt() && Char2.isInt(); 11927 }; 11928 const auto &AdvanceElems = [&] { 11929 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11930 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11931 }; 11932 11933 bool StopAtNull = 11934 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11935 BuiltinOp != Builtin::BIwmemcmp && 11936 BuiltinOp != Builtin::BI__builtin_memcmp && 11937 BuiltinOp != Builtin::BI__builtin_bcmp && 11938 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11939 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11940 BuiltinOp == Builtin::BIwcsncmp || 11941 BuiltinOp == Builtin::BIwmemcmp || 11942 BuiltinOp == Builtin::BI__builtin_wcscmp || 11943 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11944 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11945 11946 for (; MaxLength; --MaxLength) { 11947 APValue Char1, Char2; 11948 if (!ReadCurElems(Char1, Char2)) 11949 return false; 11950 if (Char1.getInt().ne(Char2.getInt())) { 11951 if (IsWide) // wmemcmp compares with wchar_t signedness. 11952 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11953 // memcmp always compares unsigned chars. 11954 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11955 } 11956 if (StopAtNull && !Char1.getInt()) 11957 return Success(0, E); 11958 assert(!(StopAtNull && !Char2.getInt())); 11959 if (!AdvanceElems()) 11960 return false; 11961 } 11962 // We hit the strncmp / memcmp limit. 11963 return Success(0, E); 11964 } 11965 11966 case Builtin::BI__atomic_always_lock_free: 11967 case Builtin::BI__atomic_is_lock_free: 11968 case Builtin::BI__c11_atomic_is_lock_free: { 11969 APSInt SizeVal; 11970 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11971 return false; 11972 11973 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11974 // of two less than or equal to the maximum inline atomic width, we know it 11975 // is lock-free. If the size isn't a power of two, or greater than the 11976 // maximum alignment where we promote atomics, we know it is not lock-free 11977 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11978 // the answer can only be determined at runtime; for example, 16-byte 11979 // atomics have lock-free implementations on some, but not all, 11980 // x86-64 processors. 11981 11982 // Check power-of-two. 11983 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11984 if (Size.isPowerOfTwo()) { 11985 // Check against inlining width. 11986 unsigned InlineWidthBits = 11987 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11988 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11989 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11990 Size == CharUnits::One() || 11991 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11992 Expr::NPC_NeverValueDependent)) 11993 // OK, we will inline appropriately-aligned operations of this size, 11994 // and _Atomic(T) is appropriately-aligned. 11995 return Success(1, E); 11996 11997 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11998 castAs<PointerType>()->getPointeeType(); 11999 if (!PointeeType->isIncompleteType() && 12000 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12001 // OK, we will inline operations on this object. 12002 return Success(1, E); 12003 } 12004 } 12005 } 12006 12007 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12008 Success(0, E) : Error(E); 12009 } 12010 case Builtin::BIomp_is_initial_device: 12011 // We can decide statically which value the runtime would return if called. 12012 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 12013 case Builtin::BI__builtin_add_overflow: 12014 case Builtin::BI__builtin_sub_overflow: 12015 case Builtin::BI__builtin_mul_overflow: 12016 case Builtin::BI__builtin_sadd_overflow: 12017 case Builtin::BI__builtin_uadd_overflow: 12018 case Builtin::BI__builtin_uaddl_overflow: 12019 case Builtin::BI__builtin_uaddll_overflow: 12020 case Builtin::BI__builtin_usub_overflow: 12021 case Builtin::BI__builtin_usubl_overflow: 12022 case Builtin::BI__builtin_usubll_overflow: 12023 case Builtin::BI__builtin_umul_overflow: 12024 case Builtin::BI__builtin_umull_overflow: 12025 case Builtin::BI__builtin_umulll_overflow: 12026 case Builtin::BI__builtin_saddl_overflow: 12027 case Builtin::BI__builtin_saddll_overflow: 12028 case Builtin::BI__builtin_ssub_overflow: 12029 case Builtin::BI__builtin_ssubl_overflow: 12030 case Builtin::BI__builtin_ssubll_overflow: 12031 case Builtin::BI__builtin_smul_overflow: 12032 case Builtin::BI__builtin_smull_overflow: 12033 case Builtin::BI__builtin_smulll_overflow: { 12034 LValue ResultLValue; 12035 APSInt LHS, RHS; 12036 12037 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12038 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12039 !EvaluateInteger(E->getArg(1), RHS, Info) || 12040 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12041 return false; 12042 12043 APSInt Result; 12044 bool DidOverflow = false; 12045 12046 // If the types don't have to match, enlarge all 3 to the largest of them. 12047 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12048 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12049 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12050 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12051 ResultType->isSignedIntegerOrEnumerationType(); 12052 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12053 ResultType->isSignedIntegerOrEnumerationType(); 12054 uint64_t LHSSize = LHS.getBitWidth(); 12055 uint64_t RHSSize = RHS.getBitWidth(); 12056 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12057 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12058 12059 // Add an additional bit if the signedness isn't uniformly agreed to. We 12060 // could do this ONLY if there is a signed and an unsigned that both have 12061 // MaxBits, but the code to check that is pretty nasty. The issue will be 12062 // caught in the shrink-to-result later anyway. 12063 if (IsSigned && !AllSigned) 12064 ++MaxBits; 12065 12066 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12067 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12068 Result = APSInt(MaxBits, !IsSigned); 12069 } 12070 12071 // Find largest int. 12072 switch (BuiltinOp) { 12073 default: 12074 llvm_unreachable("Invalid value for BuiltinOp"); 12075 case Builtin::BI__builtin_add_overflow: 12076 case Builtin::BI__builtin_sadd_overflow: 12077 case Builtin::BI__builtin_saddl_overflow: 12078 case Builtin::BI__builtin_saddll_overflow: 12079 case Builtin::BI__builtin_uadd_overflow: 12080 case Builtin::BI__builtin_uaddl_overflow: 12081 case Builtin::BI__builtin_uaddll_overflow: 12082 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12083 : LHS.uadd_ov(RHS, DidOverflow); 12084 break; 12085 case Builtin::BI__builtin_sub_overflow: 12086 case Builtin::BI__builtin_ssub_overflow: 12087 case Builtin::BI__builtin_ssubl_overflow: 12088 case Builtin::BI__builtin_ssubll_overflow: 12089 case Builtin::BI__builtin_usub_overflow: 12090 case Builtin::BI__builtin_usubl_overflow: 12091 case Builtin::BI__builtin_usubll_overflow: 12092 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12093 : LHS.usub_ov(RHS, DidOverflow); 12094 break; 12095 case Builtin::BI__builtin_mul_overflow: 12096 case Builtin::BI__builtin_smul_overflow: 12097 case Builtin::BI__builtin_smull_overflow: 12098 case Builtin::BI__builtin_smulll_overflow: 12099 case Builtin::BI__builtin_umul_overflow: 12100 case Builtin::BI__builtin_umull_overflow: 12101 case Builtin::BI__builtin_umulll_overflow: 12102 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12103 : LHS.umul_ov(RHS, DidOverflow); 12104 break; 12105 } 12106 12107 // In the case where multiple sizes are allowed, truncate and see if 12108 // the values are the same. 12109 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12110 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12111 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12112 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12113 // since it will give us the behavior of a TruncOrSelf in the case where 12114 // its parameter <= its size. We previously set Result to be at least the 12115 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12116 // will work exactly like TruncOrSelf. 12117 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12118 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12119 12120 if (!APSInt::isSameValue(Temp, Result)) 12121 DidOverflow = true; 12122 Result = Temp; 12123 } 12124 12125 APValue APV{Result}; 12126 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12127 return false; 12128 return Success(DidOverflow, E); 12129 } 12130 } 12131 } 12132 12133 /// Determine whether this is a pointer past the end of the complete 12134 /// object referred to by the lvalue. 12135 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12136 const LValue &LV) { 12137 // A null pointer can be viewed as being "past the end" but we don't 12138 // choose to look at it that way here. 12139 if (!LV.getLValueBase()) 12140 return false; 12141 12142 // If the designator is valid and refers to a subobject, we're not pointing 12143 // past the end. 12144 if (!LV.getLValueDesignator().Invalid && 12145 !LV.getLValueDesignator().isOnePastTheEnd()) 12146 return false; 12147 12148 // A pointer to an incomplete type might be past-the-end if the type's size is 12149 // zero. We cannot tell because the type is incomplete. 12150 QualType Ty = getType(LV.getLValueBase()); 12151 if (Ty->isIncompleteType()) 12152 return true; 12153 12154 // We're a past-the-end pointer if we point to the byte after the object, 12155 // no matter what our type or path is. 12156 auto Size = Ctx.getTypeSizeInChars(Ty); 12157 return LV.getLValueOffset() == Size; 12158 } 12159 12160 namespace { 12161 12162 /// Data recursive integer evaluator of certain binary operators. 12163 /// 12164 /// We use a data recursive algorithm for binary operators so that we are able 12165 /// to handle extreme cases of chained binary operators without causing stack 12166 /// overflow. 12167 class DataRecursiveIntBinOpEvaluator { 12168 struct EvalResult { 12169 APValue Val; 12170 bool Failed; 12171 12172 EvalResult() : Failed(false) { } 12173 12174 void swap(EvalResult &RHS) { 12175 Val.swap(RHS.Val); 12176 Failed = RHS.Failed; 12177 RHS.Failed = false; 12178 } 12179 }; 12180 12181 struct Job { 12182 const Expr *E; 12183 EvalResult LHSResult; // meaningful only for binary operator expression. 12184 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12185 12186 Job() = default; 12187 Job(Job &&) = default; 12188 12189 void startSpeculativeEval(EvalInfo &Info) { 12190 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12191 } 12192 12193 private: 12194 SpeculativeEvaluationRAII SpecEvalRAII; 12195 }; 12196 12197 SmallVector<Job, 16> Queue; 12198 12199 IntExprEvaluator &IntEval; 12200 EvalInfo &Info; 12201 APValue &FinalResult; 12202 12203 public: 12204 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12205 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12206 12207 /// True if \param E is a binary operator that we are going to handle 12208 /// data recursively. 12209 /// We handle binary operators that are comma, logical, or that have operands 12210 /// with integral or enumeration type. 12211 static bool shouldEnqueue(const BinaryOperator *E) { 12212 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12213 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12214 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12215 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12216 } 12217 12218 bool Traverse(const BinaryOperator *E) { 12219 enqueue(E); 12220 EvalResult PrevResult; 12221 while (!Queue.empty()) 12222 process(PrevResult); 12223 12224 if (PrevResult.Failed) return false; 12225 12226 FinalResult.swap(PrevResult.Val); 12227 return true; 12228 } 12229 12230 private: 12231 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12232 return IntEval.Success(Value, E, Result); 12233 } 12234 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12235 return IntEval.Success(Value, E, Result); 12236 } 12237 bool Error(const Expr *E) { 12238 return IntEval.Error(E); 12239 } 12240 bool Error(const Expr *E, diag::kind D) { 12241 return IntEval.Error(E, D); 12242 } 12243 12244 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12245 return Info.CCEDiag(E, D); 12246 } 12247 12248 // Returns true if visiting the RHS is necessary, false otherwise. 12249 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12250 bool &SuppressRHSDiags); 12251 12252 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12253 const BinaryOperator *E, APValue &Result); 12254 12255 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12256 Result.Failed = !Evaluate(Result.Val, Info, E); 12257 if (Result.Failed) 12258 Result.Val = APValue(); 12259 } 12260 12261 void process(EvalResult &Result); 12262 12263 void enqueue(const Expr *E) { 12264 E = E->IgnoreParens(); 12265 Queue.resize(Queue.size()+1); 12266 Queue.back().E = E; 12267 Queue.back().Kind = Job::AnyExprKind; 12268 } 12269 }; 12270 12271 } 12272 12273 bool DataRecursiveIntBinOpEvaluator:: 12274 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12275 bool &SuppressRHSDiags) { 12276 if (E->getOpcode() == BO_Comma) { 12277 // Ignore LHS but note if we could not evaluate it. 12278 if (LHSResult.Failed) 12279 return Info.noteSideEffect(); 12280 return true; 12281 } 12282 12283 if (E->isLogicalOp()) { 12284 bool LHSAsBool; 12285 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12286 // We were able to evaluate the LHS, see if we can get away with not 12287 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12288 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12289 Success(LHSAsBool, E, LHSResult.Val); 12290 return false; // Ignore RHS 12291 } 12292 } else { 12293 LHSResult.Failed = true; 12294 12295 // Since we weren't able to evaluate the left hand side, it 12296 // might have had side effects. 12297 if (!Info.noteSideEffect()) 12298 return false; 12299 12300 // We can't evaluate the LHS; however, sometimes the result 12301 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12302 // Don't ignore RHS and suppress diagnostics from this arm. 12303 SuppressRHSDiags = true; 12304 } 12305 12306 return true; 12307 } 12308 12309 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12310 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12311 12312 if (LHSResult.Failed && !Info.noteFailure()) 12313 return false; // Ignore RHS; 12314 12315 return true; 12316 } 12317 12318 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12319 bool IsSub) { 12320 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12321 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12322 // offsets. 12323 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12324 CharUnits &Offset = LVal.getLValueOffset(); 12325 uint64_t Offset64 = Offset.getQuantity(); 12326 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12327 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12328 : Offset64 + Index64); 12329 } 12330 12331 bool DataRecursiveIntBinOpEvaluator:: 12332 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12333 const BinaryOperator *E, APValue &Result) { 12334 if (E->getOpcode() == BO_Comma) { 12335 if (RHSResult.Failed) 12336 return false; 12337 Result = RHSResult.Val; 12338 return true; 12339 } 12340 12341 if (E->isLogicalOp()) { 12342 bool lhsResult, rhsResult; 12343 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12344 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12345 12346 if (LHSIsOK) { 12347 if (RHSIsOK) { 12348 if (E->getOpcode() == BO_LOr) 12349 return Success(lhsResult || rhsResult, E, Result); 12350 else 12351 return Success(lhsResult && rhsResult, E, Result); 12352 } 12353 } else { 12354 if (RHSIsOK) { 12355 // We can't evaluate the LHS; however, sometimes the result 12356 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12357 if (rhsResult == (E->getOpcode() == BO_LOr)) 12358 return Success(rhsResult, E, Result); 12359 } 12360 } 12361 12362 return false; 12363 } 12364 12365 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12366 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12367 12368 if (LHSResult.Failed || RHSResult.Failed) 12369 return false; 12370 12371 const APValue &LHSVal = LHSResult.Val; 12372 const APValue &RHSVal = RHSResult.Val; 12373 12374 // Handle cases like (unsigned long)&a + 4. 12375 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12376 Result = LHSVal; 12377 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12378 return true; 12379 } 12380 12381 // Handle cases like 4 + (unsigned long)&a 12382 if (E->getOpcode() == BO_Add && 12383 RHSVal.isLValue() && LHSVal.isInt()) { 12384 Result = RHSVal; 12385 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12386 return true; 12387 } 12388 12389 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12390 // Handle (intptr_t)&&A - (intptr_t)&&B. 12391 if (!LHSVal.getLValueOffset().isZero() || 12392 !RHSVal.getLValueOffset().isZero()) 12393 return false; 12394 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12395 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12396 if (!LHSExpr || !RHSExpr) 12397 return false; 12398 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12399 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12400 if (!LHSAddrExpr || !RHSAddrExpr) 12401 return false; 12402 // Make sure both labels come from the same function. 12403 if (LHSAddrExpr->getLabel()->getDeclContext() != 12404 RHSAddrExpr->getLabel()->getDeclContext()) 12405 return false; 12406 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12407 return true; 12408 } 12409 12410 // All the remaining cases expect both operands to be an integer 12411 if (!LHSVal.isInt() || !RHSVal.isInt()) 12412 return Error(E); 12413 12414 // Set up the width and signedness manually, in case it can't be deduced 12415 // from the operation we're performing. 12416 // FIXME: Don't do this in the cases where we can deduce it. 12417 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12418 E->getType()->isUnsignedIntegerOrEnumerationType()); 12419 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12420 RHSVal.getInt(), Value)) 12421 return false; 12422 return Success(Value, E, Result); 12423 } 12424 12425 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12426 Job &job = Queue.back(); 12427 12428 switch (job.Kind) { 12429 case Job::AnyExprKind: { 12430 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12431 if (shouldEnqueue(Bop)) { 12432 job.Kind = Job::BinOpKind; 12433 enqueue(Bop->getLHS()); 12434 return; 12435 } 12436 } 12437 12438 EvaluateExpr(job.E, Result); 12439 Queue.pop_back(); 12440 return; 12441 } 12442 12443 case Job::BinOpKind: { 12444 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12445 bool SuppressRHSDiags = false; 12446 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12447 Queue.pop_back(); 12448 return; 12449 } 12450 if (SuppressRHSDiags) 12451 job.startSpeculativeEval(Info); 12452 job.LHSResult.swap(Result); 12453 job.Kind = Job::BinOpVisitedLHSKind; 12454 enqueue(Bop->getRHS()); 12455 return; 12456 } 12457 12458 case Job::BinOpVisitedLHSKind: { 12459 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12460 EvalResult RHS; 12461 RHS.swap(Result); 12462 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12463 Queue.pop_back(); 12464 return; 12465 } 12466 } 12467 12468 llvm_unreachable("Invalid Job::Kind!"); 12469 } 12470 12471 namespace { 12472 /// Used when we determine that we should fail, but can keep evaluating prior to 12473 /// noting that we had a failure. 12474 class DelayedNoteFailureRAII { 12475 EvalInfo &Info; 12476 bool NoteFailure; 12477 12478 public: 12479 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12480 : Info(Info), NoteFailure(NoteFailure) {} 12481 ~DelayedNoteFailureRAII() { 12482 if (NoteFailure) { 12483 bool ContinueAfterFailure = Info.noteFailure(); 12484 (void)ContinueAfterFailure; 12485 assert(ContinueAfterFailure && 12486 "Shouldn't have kept evaluating on failure."); 12487 } 12488 } 12489 }; 12490 12491 enum class CmpResult { 12492 Unequal, 12493 Less, 12494 Equal, 12495 Greater, 12496 Unordered, 12497 }; 12498 } 12499 12500 template <class SuccessCB, class AfterCB> 12501 static bool 12502 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12503 SuccessCB &&Success, AfterCB &&DoAfter) { 12504 assert(!E->isValueDependent()); 12505 assert(E->isComparisonOp() && "expected comparison operator"); 12506 assert((E->getOpcode() == BO_Cmp || 12507 E->getType()->isIntegralOrEnumerationType()) && 12508 "unsupported binary expression evaluation"); 12509 auto Error = [&](const Expr *E) { 12510 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12511 return false; 12512 }; 12513 12514 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12515 bool IsEquality = E->isEqualityOp(); 12516 12517 QualType LHSTy = E->getLHS()->getType(); 12518 QualType RHSTy = E->getRHS()->getType(); 12519 12520 if (LHSTy->isIntegralOrEnumerationType() && 12521 RHSTy->isIntegralOrEnumerationType()) { 12522 APSInt LHS, RHS; 12523 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12524 if (!LHSOK && !Info.noteFailure()) 12525 return false; 12526 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12527 return false; 12528 if (LHS < RHS) 12529 return Success(CmpResult::Less, E); 12530 if (LHS > RHS) 12531 return Success(CmpResult::Greater, E); 12532 return Success(CmpResult::Equal, E); 12533 } 12534 12535 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12536 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12537 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12538 12539 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12540 if (!LHSOK && !Info.noteFailure()) 12541 return false; 12542 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12543 return false; 12544 if (LHSFX < RHSFX) 12545 return Success(CmpResult::Less, E); 12546 if (LHSFX > RHSFX) 12547 return Success(CmpResult::Greater, E); 12548 return Success(CmpResult::Equal, E); 12549 } 12550 12551 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12552 ComplexValue LHS, RHS; 12553 bool LHSOK; 12554 if (E->isAssignmentOp()) { 12555 LValue LV; 12556 EvaluateLValue(E->getLHS(), LV, Info); 12557 LHSOK = false; 12558 } else if (LHSTy->isRealFloatingType()) { 12559 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12560 if (LHSOK) { 12561 LHS.makeComplexFloat(); 12562 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12563 } 12564 } else { 12565 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12566 } 12567 if (!LHSOK && !Info.noteFailure()) 12568 return false; 12569 12570 if (E->getRHS()->getType()->isRealFloatingType()) { 12571 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12572 return false; 12573 RHS.makeComplexFloat(); 12574 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12575 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12576 return false; 12577 12578 if (LHS.isComplexFloat()) { 12579 APFloat::cmpResult CR_r = 12580 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12581 APFloat::cmpResult CR_i = 12582 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12583 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12584 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12585 } else { 12586 assert(IsEquality && "invalid complex comparison"); 12587 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12588 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12589 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12590 } 12591 } 12592 12593 if (LHSTy->isRealFloatingType() && 12594 RHSTy->isRealFloatingType()) { 12595 APFloat RHS(0.0), LHS(0.0); 12596 12597 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12598 if (!LHSOK && !Info.noteFailure()) 12599 return false; 12600 12601 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12602 return false; 12603 12604 assert(E->isComparisonOp() && "Invalid binary operator!"); 12605 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12606 if (!Info.InConstantContext && 12607 APFloatCmpResult == APFloat::cmpUnordered && 12608 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12609 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12610 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12611 return false; 12612 } 12613 auto GetCmpRes = [&]() { 12614 switch (APFloatCmpResult) { 12615 case APFloat::cmpEqual: 12616 return CmpResult::Equal; 12617 case APFloat::cmpLessThan: 12618 return CmpResult::Less; 12619 case APFloat::cmpGreaterThan: 12620 return CmpResult::Greater; 12621 case APFloat::cmpUnordered: 12622 return CmpResult::Unordered; 12623 } 12624 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12625 }; 12626 return Success(GetCmpRes(), E); 12627 } 12628 12629 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12630 LValue LHSValue, RHSValue; 12631 12632 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12633 if (!LHSOK && !Info.noteFailure()) 12634 return false; 12635 12636 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12637 return false; 12638 12639 // Reject differing bases from the normal codepath; we special-case 12640 // comparisons to null. 12641 if (!HasSameBase(LHSValue, RHSValue)) { 12642 // Inequalities and subtractions between unrelated pointers have 12643 // unspecified or undefined behavior. 12644 if (!IsEquality) { 12645 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12646 return false; 12647 } 12648 // A constant address may compare equal to the address of a symbol. 12649 // The one exception is that address of an object cannot compare equal 12650 // to a null pointer constant. 12651 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12652 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12653 return Error(E); 12654 // It's implementation-defined whether distinct literals will have 12655 // distinct addresses. In clang, the result of such a comparison is 12656 // unspecified, so it is not a constant expression. However, we do know 12657 // that the address of a literal will be non-null. 12658 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12659 LHSValue.Base && RHSValue.Base) 12660 return Error(E); 12661 // We can't tell whether weak symbols will end up pointing to the same 12662 // object. 12663 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12664 return Error(E); 12665 // We can't compare the address of the start of one object with the 12666 // past-the-end address of another object, per C++ DR1652. 12667 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12668 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12669 (RHSValue.Base && RHSValue.Offset.isZero() && 12670 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12671 return Error(E); 12672 // We can't tell whether an object is at the same address as another 12673 // zero sized object. 12674 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12675 (LHSValue.Base && isZeroSized(RHSValue))) 12676 return Error(E); 12677 return Success(CmpResult::Unequal, E); 12678 } 12679 12680 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12681 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12682 12683 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12684 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12685 12686 // C++11 [expr.rel]p3: 12687 // Pointers to void (after pointer conversions) can be compared, with a 12688 // result defined as follows: If both pointers represent the same 12689 // address or are both the null pointer value, the result is true if the 12690 // operator is <= or >= and false otherwise; otherwise the result is 12691 // unspecified. 12692 // We interpret this as applying to pointers to *cv* void. 12693 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12694 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12695 12696 // C++11 [expr.rel]p2: 12697 // - If two pointers point to non-static data members of the same object, 12698 // or to subobjects or array elements fo such members, recursively, the 12699 // pointer to the later declared member compares greater provided the 12700 // two members have the same access control and provided their class is 12701 // not a union. 12702 // [...] 12703 // - Otherwise pointer comparisons are unspecified. 12704 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12705 bool WasArrayIndex; 12706 unsigned Mismatch = FindDesignatorMismatch( 12707 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12708 // At the point where the designators diverge, the comparison has a 12709 // specified value if: 12710 // - we are comparing array indices 12711 // - we are comparing fields of a union, or fields with the same access 12712 // Otherwise, the result is unspecified and thus the comparison is not a 12713 // constant expression. 12714 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12715 Mismatch < RHSDesignator.Entries.size()) { 12716 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12717 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12718 if (!LF && !RF) 12719 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12720 else if (!LF) 12721 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12722 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12723 << RF->getParent() << RF; 12724 else if (!RF) 12725 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12726 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12727 << LF->getParent() << LF; 12728 else if (!LF->getParent()->isUnion() && 12729 LF->getAccess() != RF->getAccess()) 12730 Info.CCEDiag(E, 12731 diag::note_constexpr_pointer_comparison_differing_access) 12732 << LF << LF->getAccess() << RF << RF->getAccess() 12733 << LF->getParent(); 12734 } 12735 } 12736 12737 // The comparison here must be unsigned, and performed with the same 12738 // width as the pointer. 12739 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12740 uint64_t CompareLHS = LHSOffset.getQuantity(); 12741 uint64_t CompareRHS = RHSOffset.getQuantity(); 12742 assert(PtrSize <= 64 && "Unexpected pointer width"); 12743 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12744 CompareLHS &= Mask; 12745 CompareRHS &= Mask; 12746 12747 // If there is a base and this is a relational operator, we can only 12748 // compare pointers within the object in question; otherwise, the result 12749 // depends on where the object is located in memory. 12750 if (!LHSValue.Base.isNull() && IsRelational) { 12751 QualType BaseTy = getType(LHSValue.Base); 12752 if (BaseTy->isIncompleteType()) 12753 return Error(E); 12754 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12755 uint64_t OffsetLimit = Size.getQuantity(); 12756 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12757 return Error(E); 12758 } 12759 12760 if (CompareLHS < CompareRHS) 12761 return Success(CmpResult::Less, E); 12762 if (CompareLHS > CompareRHS) 12763 return Success(CmpResult::Greater, E); 12764 return Success(CmpResult::Equal, E); 12765 } 12766 12767 if (LHSTy->isMemberPointerType()) { 12768 assert(IsEquality && "unexpected member pointer operation"); 12769 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12770 12771 MemberPtr LHSValue, RHSValue; 12772 12773 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12774 if (!LHSOK && !Info.noteFailure()) 12775 return false; 12776 12777 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12778 return false; 12779 12780 // C++11 [expr.eq]p2: 12781 // If both operands are null, they compare equal. Otherwise if only one is 12782 // null, they compare unequal. 12783 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12784 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12785 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12786 } 12787 12788 // Otherwise if either is a pointer to a virtual member function, the 12789 // result is unspecified. 12790 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12791 if (MD->isVirtual()) 12792 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12793 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12794 if (MD->isVirtual()) 12795 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12796 12797 // Otherwise they compare equal if and only if they would refer to the 12798 // same member of the same most derived object or the same subobject if 12799 // they were dereferenced with a hypothetical object of the associated 12800 // class type. 12801 bool Equal = LHSValue == RHSValue; 12802 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12803 } 12804 12805 if (LHSTy->isNullPtrType()) { 12806 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12807 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12808 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12809 // are compared, the result is true of the operator is <=, >= or ==, and 12810 // false otherwise. 12811 return Success(CmpResult::Equal, E); 12812 } 12813 12814 return DoAfter(); 12815 } 12816 12817 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12818 if (!CheckLiteralType(Info, E)) 12819 return false; 12820 12821 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12822 ComparisonCategoryResult CCR; 12823 switch (CR) { 12824 case CmpResult::Unequal: 12825 llvm_unreachable("should never produce Unequal for three-way comparison"); 12826 case CmpResult::Less: 12827 CCR = ComparisonCategoryResult::Less; 12828 break; 12829 case CmpResult::Equal: 12830 CCR = ComparisonCategoryResult::Equal; 12831 break; 12832 case CmpResult::Greater: 12833 CCR = ComparisonCategoryResult::Greater; 12834 break; 12835 case CmpResult::Unordered: 12836 CCR = ComparisonCategoryResult::Unordered; 12837 break; 12838 } 12839 // Evaluation succeeded. Lookup the information for the comparison category 12840 // type and fetch the VarDecl for the result. 12841 const ComparisonCategoryInfo &CmpInfo = 12842 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12843 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12844 // Check and evaluate the result as a constant expression. 12845 LValue LV; 12846 LV.set(VD); 12847 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12848 return false; 12849 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12850 ConstantExprKind::Normal); 12851 }; 12852 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12853 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12854 }); 12855 } 12856 12857 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12858 // We don't call noteFailure immediately because the assignment happens after 12859 // we evaluate LHS and RHS. 12860 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12861 return Error(E); 12862 12863 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12864 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12865 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12866 12867 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12868 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12869 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12870 12871 if (E->isComparisonOp()) { 12872 // Evaluate builtin binary comparisons by evaluating them as three-way 12873 // comparisons and then translating the result. 12874 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12875 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12876 "should only produce Unequal for equality comparisons"); 12877 bool IsEqual = CR == CmpResult::Equal, 12878 IsLess = CR == CmpResult::Less, 12879 IsGreater = CR == CmpResult::Greater; 12880 auto Op = E->getOpcode(); 12881 switch (Op) { 12882 default: 12883 llvm_unreachable("unsupported binary operator"); 12884 case BO_EQ: 12885 case BO_NE: 12886 return Success(IsEqual == (Op == BO_EQ), E); 12887 case BO_LT: 12888 return Success(IsLess, E); 12889 case BO_GT: 12890 return Success(IsGreater, E); 12891 case BO_LE: 12892 return Success(IsEqual || IsLess, E); 12893 case BO_GE: 12894 return Success(IsEqual || IsGreater, E); 12895 } 12896 }; 12897 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12898 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12899 }); 12900 } 12901 12902 QualType LHSTy = E->getLHS()->getType(); 12903 QualType RHSTy = E->getRHS()->getType(); 12904 12905 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12906 E->getOpcode() == BO_Sub) { 12907 LValue LHSValue, RHSValue; 12908 12909 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12910 if (!LHSOK && !Info.noteFailure()) 12911 return false; 12912 12913 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12914 return false; 12915 12916 // Reject differing bases from the normal codepath; we special-case 12917 // comparisons to null. 12918 if (!HasSameBase(LHSValue, RHSValue)) { 12919 // Handle &&A - &&B. 12920 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12921 return Error(E); 12922 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12923 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12924 if (!LHSExpr || !RHSExpr) 12925 return Error(E); 12926 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12927 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12928 if (!LHSAddrExpr || !RHSAddrExpr) 12929 return Error(E); 12930 // Make sure both labels come from the same function. 12931 if (LHSAddrExpr->getLabel()->getDeclContext() != 12932 RHSAddrExpr->getLabel()->getDeclContext()) 12933 return Error(E); 12934 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12935 } 12936 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12937 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12938 12939 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12940 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12941 12942 // C++11 [expr.add]p6: 12943 // Unless both pointers point to elements of the same array object, or 12944 // one past the last element of the array object, the behavior is 12945 // undefined. 12946 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12947 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12948 RHSDesignator)) 12949 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12950 12951 QualType Type = E->getLHS()->getType(); 12952 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12953 12954 CharUnits ElementSize; 12955 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12956 return false; 12957 12958 // As an extension, a type may have zero size (empty struct or union in 12959 // C, array of zero length). Pointer subtraction in such cases has 12960 // undefined behavior, so is not constant. 12961 if (ElementSize.isZero()) { 12962 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12963 << ElementType; 12964 return false; 12965 } 12966 12967 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12968 // and produce incorrect results when it overflows. Such behavior 12969 // appears to be non-conforming, but is common, so perhaps we should 12970 // assume the standard intended for such cases to be undefined behavior 12971 // and check for them. 12972 12973 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12974 // overflow in the final conversion to ptrdiff_t. 12975 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12976 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12977 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12978 false); 12979 APSInt TrueResult = (LHS - RHS) / ElemSize; 12980 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12981 12982 if (Result.extend(65) != TrueResult && 12983 !HandleOverflow(Info, E, TrueResult, E->getType())) 12984 return false; 12985 return Success(Result, E); 12986 } 12987 12988 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12989 } 12990 12991 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12992 /// a result as the expression's type. 12993 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12994 const UnaryExprOrTypeTraitExpr *E) { 12995 switch(E->getKind()) { 12996 case UETT_PreferredAlignOf: 12997 case UETT_AlignOf: { 12998 if (E->isArgumentType()) 12999 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13000 E); 13001 else 13002 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13003 E); 13004 } 13005 13006 case UETT_VecStep: { 13007 QualType Ty = E->getTypeOfArgument(); 13008 13009 if (Ty->isVectorType()) { 13010 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13011 13012 // The vec_step built-in functions that take a 3-component 13013 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13014 if (n == 3) 13015 n = 4; 13016 13017 return Success(n, E); 13018 } else 13019 return Success(1, E); 13020 } 13021 13022 case UETT_SizeOf: { 13023 QualType SrcTy = E->getTypeOfArgument(); 13024 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13025 // the result is the size of the referenced type." 13026 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13027 SrcTy = Ref->getPointeeType(); 13028 13029 CharUnits Sizeof; 13030 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13031 return false; 13032 return Success(Sizeof, E); 13033 } 13034 case UETT_OpenMPRequiredSimdAlign: 13035 assert(E->isArgumentType()); 13036 return Success( 13037 Info.Ctx.toCharUnitsFromBits( 13038 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13039 .getQuantity(), 13040 E); 13041 } 13042 13043 llvm_unreachable("unknown expr/type trait"); 13044 } 13045 13046 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13047 CharUnits Result; 13048 unsigned n = OOE->getNumComponents(); 13049 if (n == 0) 13050 return Error(OOE); 13051 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13052 for (unsigned i = 0; i != n; ++i) { 13053 OffsetOfNode ON = OOE->getComponent(i); 13054 switch (ON.getKind()) { 13055 case OffsetOfNode::Array: { 13056 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13057 APSInt IdxResult; 13058 if (!EvaluateInteger(Idx, IdxResult, Info)) 13059 return false; 13060 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13061 if (!AT) 13062 return Error(OOE); 13063 CurrentType = AT->getElementType(); 13064 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13065 Result += IdxResult.getSExtValue() * ElementSize; 13066 break; 13067 } 13068 13069 case OffsetOfNode::Field: { 13070 FieldDecl *MemberDecl = ON.getField(); 13071 const RecordType *RT = CurrentType->getAs<RecordType>(); 13072 if (!RT) 13073 return Error(OOE); 13074 RecordDecl *RD = RT->getDecl(); 13075 if (RD->isInvalidDecl()) return false; 13076 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13077 unsigned i = MemberDecl->getFieldIndex(); 13078 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13079 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13080 CurrentType = MemberDecl->getType().getNonReferenceType(); 13081 break; 13082 } 13083 13084 case OffsetOfNode::Identifier: 13085 llvm_unreachable("dependent __builtin_offsetof"); 13086 13087 case OffsetOfNode::Base: { 13088 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13089 if (BaseSpec->isVirtual()) 13090 return Error(OOE); 13091 13092 // Find the layout of the class whose base we are looking into. 13093 const RecordType *RT = CurrentType->getAs<RecordType>(); 13094 if (!RT) 13095 return Error(OOE); 13096 RecordDecl *RD = RT->getDecl(); 13097 if (RD->isInvalidDecl()) return false; 13098 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13099 13100 // Find the base class itself. 13101 CurrentType = BaseSpec->getType(); 13102 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13103 if (!BaseRT) 13104 return Error(OOE); 13105 13106 // Add the offset to the base. 13107 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13108 break; 13109 } 13110 } 13111 } 13112 return Success(Result, OOE); 13113 } 13114 13115 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13116 switch (E->getOpcode()) { 13117 default: 13118 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13119 // See C99 6.6p3. 13120 return Error(E); 13121 case UO_Extension: 13122 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13123 // If so, we could clear the diagnostic ID. 13124 return Visit(E->getSubExpr()); 13125 case UO_Plus: 13126 // The result is just the value. 13127 return Visit(E->getSubExpr()); 13128 case UO_Minus: { 13129 if (!Visit(E->getSubExpr())) 13130 return false; 13131 if (!Result.isInt()) return Error(E); 13132 const APSInt &Value = Result.getInt(); 13133 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13134 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13135 E->getType())) 13136 return false; 13137 return Success(-Value, E); 13138 } 13139 case UO_Not: { 13140 if (!Visit(E->getSubExpr())) 13141 return false; 13142 if (!Result.isInt()) return Error(E); 13143 return Success(~Result.getInt(), E); 13144 } 13145 case UO_LNot: { 13146 bool bres; 13147 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13148 return false; 13149 return Success(!bres, E); 13150 } 13151 } 13152 } 13153 13154 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13155 /// result type is integer. 13156 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13157 const Expr *SubExpr = E->getSubExpr(); 13158 QualType DestType = E->getType(); 13159 QualType SrcType = SubExpr->getType(); 13160 13161 switch (E->getCastKind()) { 13162 case CK_BaseToDerived: 13163 case CK_DerivedToBase: 13164 case CK_UncheckedDerivedToBase: 13165 case CK_Dynamic: 13166 case CK_ToUnion: 13167 case CK_ArrayToPointerDecay: 13168 case CK_FunctionToPointerDecay: 13169 case CK_NullToPointer: 13170 case CK_NullToMemberPointer: 13171 case CK_BaseToDerivedMemberPointer: 13172 case CK_DerivedToBaseMemberPointer: 13173 case CK_ReinterpretMemberPointer: 13174 case CK_ConstructorConversion: 13175 case CK_IntegralToPointer: 13176 case CK_ToVoid: 13177 case CK_VectorSplat: 13178 case CK_IntegralToFloating: 13179 case CK_FloatingCast: 13180 case CK_CPointerToObjCPointerCast: 13181 case CK_BlockPointerToObjCPointerCast: 13182 case CK_AnyPointerToBlockPointerCast: 13183 case CK_ObjCObjectLValueCast: 13184 case CK_FloatingRealToComplex: 13185 case CK_FloatingComplexToReal: 13186 case CK_FloatingComplexCast: 13187 case CK_FloatingComplexToIntegralComplex: 13188 case CK_IntegralRealToComplex: 13189 case CK_IntegralComplexCast: 13190 case CK_IntegralComplexToFloatingComplex: 13191 case CK_BuiltinFnToFnPtr: 13192 case CK_ZeroToOCLOpaqueType: 13193 case CK_NonAtomicToAtomic: 13194 case CK_AddressSpaceConversion: 13195 case CK_IntToOCLSampler: 13196 case CK_FloatingToFixedPoint: 13197 case CK_FixedPointToFloating: 13198 case CK_FixedPointCast: 13199 case CK_IntegralToFixedPoint: 13200 llvm_unreachable("invalid cast kind for integral value"); 13201 13202 case CK_BitCast: 13203 case CK_Dependent: 13204 case CK_LValueBitCast: 13205 case CK_ARCProduceObject: 13206 case CK_ARCConsumeObject: 13207 case CK_ARCReclaimReturnedObject: 13208 case CK_ARCExtendBlockObject: 13209 case CK_CopyAndAutoreleaseBlockObject: 13210 return Error(E); 13211 13212 case CK_UserDefinedConversion: 13213 case CK_LValueToRValue: 13214 case CK_AtomicToNonAtomic: 13215 case CK_NoOp: 13216 case CK_LValueToRValueBitCast: 13217 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13218 13219 case CK_MemberPointerToBoolean: 13220 case CK_PointerToBoolean: 13221 case CK_IntegralToBoolean: 13222 case CK_FloatingToBoolean: 13223 case CK_BooleanToSignedIntegral: 13224 case CK_FloatingComplexToBoolean: 13225 case CK_IntegralComplexToBoolean: { 13226 bool BoolResult; 13227 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13228 return false; 13229 uint64_t IntResult = BoolResult; 13230 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13231 IntResult = (uint64_t)-1; 13232 return Success(IntResult, E); 13233 } 13234 13235 case CK_FixedPointToIntegral: { 13236 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13237 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13238 return false; 13239 bool Overflowed; 13240 llvm::APSInt Result = Src.convertToInt( 13241 Info.Ctx.getIntWidth(DestType), 13242 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13243 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13244 return false; 13245 return Success(Result, E); 13246 } 13247 13248 case CK_FixedPointToBoolean: { 13249 // Unsigned padding does not affect this. 13250 APValue Val; 13251 if (!Evaluate(Val, Info, SubExpr)) 13252 return false; 13253 return Success(Val.getFixedPoint().getBoolValue(), E); 13254 } 13255 13256 case CK_IntegralCast: { 13257 if (!Visit(SubExpr)) 13258 return false; 13259 13260 if (!Result.isInt()) { 13261 // Allow casts of address-of-label differences if they are no-ops 13262 // or narrowing. (The narrowing case isn't actually guaranteed to 13263 // be constant-evaluatable except in some narrow cases which are hard 13264 // to detect here. We let it through on the assumption the user knows 13265 // what they are doing.) 13266 if (Result.isAddrLabelDiff()) 13267 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13268 // Only allow casts of lvalues if they are lossless. 13269 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13270 } 13271 13272 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13273 Result.getInt()), E); 13274 } 13275 13276 case CK_PointerToIntegral: { 13277 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13278 13279 LValue LV; 13280 if (!EvaluatePointer(SubExpr, LV, Info)) 13281 return false; 13282 13283 if (LV.getLValueBase()) { 13284 // Only allow based lvalue casts if they are lossless. 13285 // FIXME: Allow a larger integer size than the pointer size, and allow 13286 // narrowing back down to pointer width in subsequent integral casts. 13287 // FIXME: Check integer type's active bits, not its type size. 13288 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13289 return Error(E); 13290 13291 LV.Designator.setInvalid(); 13292 LV.moveInto(Result); 13293 return true; 13294 } 13295 13296 APSInt AsInt; 13297 APValue V; 13298 LV.moveInto(V); 13299 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13300 llvm_unreachable("Can't cast this!"); 13301 13302 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13303 } 13304 13305 case CK_IntegralComplexToReal: { 13306 ComplexValue C; 13307 if (!EvaluateComplex(SubExpr, C, Info)) 13308 return false; 13309 return Success(C.getComplexIntReal(), E); 13310 } 13311 13312 case CK_FloatingToIntegral: { 13313 APFloat F(0.0); 13314 if (!EvaluateFloat(SubExpr, F, Info)) 13315 return false; 13316 13317 APSInt Value; 13318 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13319 return false; 13320 return Success(Value, E); 13321 } 13322 } 13323 13324 llvm_unreachable("unknown cast resulting in integral value"); 13325 } 13326 13327 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13328 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13329 ComplexValue LV; 13330 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13331 return false; 13332 if (!LV.isComplexInt()) 13333 return Error(E); 13334 return Success(LV.getComplexIntReal(), E); 13335 } 13336 13337 return Visit(E->getSubExpr()); 13338 } 13339 13340 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13341 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13342 ComplexValue LV; 13343 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13344 return false; 13345 if (!LV.isComplexInt()) 13346 return Error(E); 13347 return Success(LV.getComplexIntImag(), E); 13348 } 13349 13350 VisitIgnoredValue(E->getSubExpr()); 13351 return Success(0, E); 13352 } 13353 13354 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13355 return Success(E->getPackLength(), E); 13356 } 13357 13358 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13359 return Success(E->getValue(), E); 13360 } 13361 13362 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13363 const ConceptSpecializationExpr *E) { 13364 return Success(E->isSatisfied(), E); 13365 } 13366 13367 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13368 return Success(E->isSatisfied(), E); 13369 } 13370 13371 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13372 switch (E->getOpcode()) { 13373 default: 13374 // Invalid unary operators 13375 return Error(E); 13376 case UO_Plus: 13377 // The result is just the value. 13378 return Visit(E->getSubExpr()); 13379 case UO_Minus: { 13380 if (!Visit(E->getSubExpr())) return false; 13381 if (!Result.isFixedPoint()) 13382 return Error(E); 13383 bool Overflowed; 13384 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13385 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13386 return false; 13387 return Success(Negated, E); 13388 } 13389 case UO_LNot: { 13390 bool bres; 13391 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13392 return false; 13393 return Success(!bres, E); 13394 } 13395 } 13396 } 13397 13398 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13399 const Expr *SubExpr = E->getSubExpr(); 13400 QualType DestType = E->getType(); 13401 assert(DestType->isFixedPointType() && 13402 "Expected destination type to be a fixed point type"); 13403 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13404 13405 switch (E->getCastKind()) { 13406 case CK_FixedPointCast: { 13407 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13408 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13409 return false; 13410 bool Overflowed; 13411 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13412 if (Overflowed) { 13413 if (Info.checkingForUndefinedBehavior()) 13414 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13415 diag::warn_fixedpoint_constant_overflow) 13416 << Result.toString() << E->getType(); 13417 if (!HandleOverflow(Info, E, Result, E->getType())) 13418 return false; 13419 } 13420 return Success(Result, E); 13421 } 13422 case CK_IntegralToFixedPoint: { 13423 APSInt Src; 13424 if (!EvaluateInteger(SubExpr, Src, Info)) 13425 return false; 13426 13427 bool Overflowed; 13428 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13429 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13430 13431 if (Overflowed) { 13432 if (Info.checkingForUndefinedBehavior()) 13433 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13434 diag::warn_fixedpoint_constant_overflow) 13435 << IntResult.toString() << E->getType(); 13436 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13437 return false; 13438 } 13439 13440 return Success(IntResult, E); 13441 } 13442 case CK_FloatingToFixedPoint: { 13443 APFloat Src(0.0); 13444 if (!EvaluateFloat(SubExpr, Src, Info)) 13445 return false; 13446 13447 bool Overflowed; 13448 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13449 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13450 13451 if (Overflowed) { 13452 if (Info.checkingForUndefinedBehavior()) 13453 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13454 diag::warn_fixedpoint_constant_overflow) 13455 << Result.toString() << E->getType(); 13456 if (!HandleOverflow(Info, E, Result, E->getType())) 13457 return false; 13458 } 13459 13460 return Success(Result, E); 13461 } 13462 case CK_NoOp: 13463 case CK_LValueToRValue: 13464 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13465 default: 13466 return Error(E); 13467 } 13468 } 13469 13470 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13471 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13472 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13473 13474 const Expr *LHS = E->getLHS(); 13475 const Expr *RHS = E->getRHS(); 13476 FixedPointSemantics ResultFXSema = 13477 Info.Ctx.getFixedPointSemantics(E->getType()); 13478 13479 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13480 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13481 return false; 13482 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13483 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13484 return false; 13485 13486 bool OpOverflow = false, ConversionOverflow = false; 13487 APFixedPoint Result(LHSFX.getSemantics()); 13488 switch (E->getOpcode()) { 13489 case BO_Add: { 13490 Result = LHSFX.add(RHSFX, &OpOverflow) 13491 .convert(ResultFXSema, &ConversionOverflow); 13492 break; 13493 } 13494 case BO_Sub: { 13495 Result = LHSFX.sub(RHSFX, &OpOverflow) 13496 .convert(ResultFXSema, &ConversionOverflow); 13497 break; 13498 } 13499 case BO_Mul: { 13500 Result = LHSFX.mul(RHSFX, &OpOverflow) 13501 .convert(ResultFXSema, &ConversionOverflow); 13502 break; 13503 } 13504 case BO_Div: { 13505 if (RHSFX.getValue() == 0) { 13506 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13507 return false; 13508 } 13509 Result = LHSFX.div(RHSFX, &OpOverflow) 13510 .convert(ResultFXSema, &ConversionOverflow); 13511 break; 13512 } 13513 case BO_Shl: 13514 case BO_Shr: { 13515 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13516 llvm::APSInt RHSVal = RHSFX.getValue(); 13517 13518 unsigned ShiftBW = 13519 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13520 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13521 // Embedded-C 4.1.6.2.2: 13522 // The right operand must be nonnegative and less than the total number 13523 // of (nonpadding) bits of the fixed-point operand ... 13524 if (RHSVal.isNegative()) 13525 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13526 else if (Amt != RHSVal) 13527 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13528 << RHSVal << E->getType() << ShiftBW; 13529 13530 if (E->getOpcode() == BO_Shl) 13531 Result = LHSFX.shl(Amt, &OpOverflow); 13532 else 13533 Result = LHSFX.shr(Amt, &OpOverflow); 13534 break; 13535 } 13536 default: 13537 return false; 13538 } 13539 if (OpOverflow || ConversionOverflow) { 13540 if (Info.checkingForUndefinedBehavior()) 13541 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13542 diag::warn_fixedpoint_constant_overflow) 13543 << Result.toString() << E->getType(); 13544 if (!HandleOverflow(Info, E, Result, E->getType())) 13545 return false; 13546 } 13547 return Success(Result, E); 13548 } 13549 13550 //===----------------------------------------------------------------------===// 13551 // Float Evaluation 13552 //===----------------------------------------------------------------------===// 13553 13554 namespace { 13555 class FloatExprEvaluator 13556 : public ExprEvaluatorBase<FloatExprEvaluator> { 13557 APFloat &Result; 13558 public: 13559 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13560 : ExprEvaluatorBaseTy(info), Result(result) {} 13561 13562 bool Success(const APValue &V, const Expr *e) { 13563 Result = V.getFloat(); 13564 return true; 13565 } 13566 13567 bool ZeroInitialization(const Expr *E) { 13568 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13569 return true; 13570 } 13571 13572 bool VisitCallExpr(const CallExpr *E); 13573 13574 bool VisitUnaryOperator(const UnaryOperator *E); 13575 bool VisitBinaryOperator(const BinaryOperator *E); 13576 bool VisitFloatingLiteral(const FloatingLiteral *E); 13577 bool VisitCastExpr(const CastExpr *E); 13578 13579 bool VisitUnaryReal(const UnaryOperator *E); 13580 bool VisitUnaryImag(const UnaryOperator *E); 13581 13582 // FIXME: Missing: array subscript of vector, member of vector 13583 }; 13584 } // end anonymous namespace 13585 13586 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13587 assert(!E->isValueDependent()); 13588 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13589 return FloatExprEvaluator(Info, Result).Visit(E); 13590 } 13591 13592 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13593 QualType ResultTy, 13594 const Expr *Arg, 13595 bool SNaN, 13596 llvm::APFloat &Result) { 13597 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13598 if (!S) return false; 13599 13600 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13601 13602 llvm::APInt fill; 13603 13604 // Treat empty strings as if they were zero. 13605 if (S->getString().empty()) 13606 fill = llvm::APInt(32, 0); 13607 else if (S->getString().getAsInteger(0, fill)) 13608 return false; 13609 13610 if (Context.getTargetInfo().isNan2008()) { 13611 if (SNaN) 13612 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13613 else 13614 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13615 } else { 13616 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13617 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13618 // a different encoding to what became a standard in 2008, and for pre- 13619 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13620 // sNaN. This is now known as "legacy NaN" encoding. 13621 if (SNaN) 13622 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13623 else 13624 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13625 } 13626 13627 return true; 13628 } 13629 13630 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13631 switch (E->getBuiltinCallee()) { 13632 default: 13633 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13634 13635 case Builtin::BI__builtin_huge_val: 13636 case Builtin::BI__builtin_huge_valf: 13637 case Builtin::BI__builtin_huge_vall: 13638 case Builtin::BI__builtin_huge_valf128: 13639 case Builtin::BI__builtin_inf: 13640 case Builtin::BI__builtin_inff: 13641 case Builtin::BI__builtin_infl: 13642 case Builtin::BI__builtin_inff128: { 13643 const llvm::fltSemantics &Sem = 13644 Info.Ctx.getFloatTypeSemantics(E->getType()); 13645 Result = llvm::APFloat::getInf(Sem); 13646 return true; 13647 } 13648 13649 case Builtin::BI__builtin_nans: 13650 case Builtin::BI__builtin_nansf: 13651 case Builtin::BI__builtin_nansl: 13652 case Builtin::BI__builtin_nansf128: 13653 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13654 true, Result)) 13655 return Error(E); 13656 return true; 13657 13658 case Builtin::BI__builtin_nan: 13659 case Builtin::BI__builtin_nanf: 13660 case Builtin::BI__builtin_nanl: 13661 case Builtin::BI__builtin_nanf128: 13662 // If this is __builtin_nan() turn this into a nan, otherwise we 13663 // can't constant fold it. 13664 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13665 false, Result)) 13666 return Error(E); 13667 return true; 13668 13669 case Builtin::BI__builtin_fabs: 13670 case Builtin::BI__builtin_fabsf: 13671 case Builtin::BI__builtin_fabsl: 13672 case Builtin::BI__builtin_fabsf128: 13673 // The C standard says "fabs raises no floating-point exceptions, 13674 // even if x is a signaling NaN. The returned value is independent of 13675 // the current rounding direction mode." Therefore constant folding can 13676 // proceed without regard to the floating point settings. 13677 // Reference, WG14 N2478 F.10.4.3 13678 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13679 return false; 13680 13681 if (Result.isNegative()) 13682 Result.changeSign(); 13683 return true; 13684 13685 // FIXME: Builtin::BI__builtin_powi 13686 // FIXME: Builtin::BI__builtin_powif 13687 // FIXME: Builtin::BI__builtin_powil 13688 13689 case Builtin::BI__builtin_copysign: 13690 case Builtin::BI__builtin_copysignf: 13691 case Builtin::BI__builtin_copysignl: 13692 case Builtin::BI__builtin_copysignf128: { 13693 APFloat RHS(0.); 13694 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13695 !EvaluateFloat(E->getArg(1), RHS, Info)) 13696 return false; 13697 Result.copySign(RHS); 13698 return true; 13699 } 13700 } 13701 } 13702 13703 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13704 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13705 ComplexValue CV; 13706 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13707 return false; 13708 Result = CV.FloatReal; 13709 return true; 13710 } 13711 13712 return Visit(E->getSubExpr()); 13713 } 13714 13715 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13716 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13717 ComplexValue CV; 13718 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13719 return false; 13720 Result = CV.FloatImag; 13721 return true; 13722 } 13723 13724 VisitIgnoredValue(E->getSubExpr()); 13725 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13726 Result = llvm::APFloat::getZero(Sem); 13727 return true; 13728 } 13729 13730 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13731 switch (E->getOpcode()) { 13732 default: return Error(E); 13733 case UO_Plus: 13734 return EvaluateFloat(E->getSubExpr(), Result, Info); 13735 case UO_Minus: 13736 // In C standard, WG14 N2478 F.3 p4 13737 // "the unary - raises no floating point exceptions, 13738 // even if the operand is signalling." 13739 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13740 return false; 13741 Result.changeSign(); 13742 return true; 13743 } 13744 } 13745 13746 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13747 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13748 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13749 13750 APFloat RHS(0.0); 13751 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13752 if (!LHSOK && !Info.noteFailure()) 13753 return false; 13754 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13755 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13756 } 13757 13758 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13759 Result = E->getValue(); 13760 return true; 13761 } 13762 13763 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13764 const Expr* SubExpr = E->getSubExpr(); 13765 13766 switch (E->getCastKind()) { 13767 default: 13768 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13769 13770 case CK_IntegralToFloating: { 13771 APSInt IntResult; 13772 const FPOptions FPO = E->getFPFeaturesInEffect( 13773 Info.Ctx.getLangOpts()); 13774 return EvaluateInteger(SubExpr, IntResult, Info) && 13775 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13776 IntResult, E->getType(), Result); 13777 } 13778 13779 case CK_FixedPointToFloating: { 13780 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13781 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13782 return false; 13783 Result = 13784 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13785 return true; 13786 } 13787 13788 case CK_FloatingCast: { 13789 if (!Visit(SubExpr)) 13790 return false; 13791 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13792 Result); 13793 } 13794 13795 case CK_FloatingComplexToReal: { 13796 ComplexValue V; 13797 if (!EvaluateComplex(SubExpr, V, Info)) 13798 return false; 13799 Result = V.getComplexFloatReal(); 13800 return true; 13801 } 13802 } 13803 } 13804 13805 //===----------------------------------------------------------------------===// 13806 // Complex Evaluation (for float and integer) 13807 //===----------------------------------------------------------------------===// 13808 13809 namespace { 13810 class ComplexExprEvaluator 13811 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13812 ComplexValue &Result; 13813 13814 public: 13815 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13816 : ExprEvaluatorBaseTy(info), Result(Result) {} 13817 13818 bool Success(const APValue &V, const Expr *e) { 13819 Result.setFrom(V); 13820 return true; 13821 } 13822 13823 bool ZeroInitialization(const Expr *E); 13824 13825 //===--------------------------------------------------------------------===// 13826 // Visitor Methods 13827 //===--------------------------------------------------------------------===// 13828 13829 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13830 bool VisitCastExpr(const CastExpr *E); 13831 bool VisitBinaryOperator(const BinaryOperator *E); 13832 bool VisitUnaryOperator(const UnaryOperator *E); 13833 bool VisitInitListExpr(const InitListExpr *E); 13834 bool VisitCallExpr(const CallExpr *E); 13835 }; 13836 } // end anonymous namespace 13837 13838 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13839 EvalInfo &Info) { 13840 assert(!E->isValueDependent()); 13841 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13842 return ComplexExprEvaluator(Info, Result).Visit(E); 13843 } 13844 13845 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13846 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13847 if (ElemTy->isRealFloatingType()) { 13848 Result.makeComplexFloat(); 13849 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13850 Result.FloatReal = Zero; 13851 Result.FloatImag = Zero; 13852 } else { 13853 Result.makeComplexInt(); 13854 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13855 Result.IntReal = Zero; 13856 Result.IntImag = Zero; 13857 } 13858 return true; 13859 } 13860 13861 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13862 const Expr* SubExpr = E->getSubExpr(); 13863 13864 if (SubExpr->getType()->isRealFloatingType()) { 13865 Result.makeComplexFloat(); 13866 APFloat &Imag = Result.FloatImag; 13867 if (!EvaluateFloat(SubExpr, Imag, Info)) 13868 return false; 13869 13870 Result.FloatReal = APFloat(Imag.getSemantics()); 13871 return true; 13872 } else { 13873 assert(SubExpr->getType()->isIntegerType() && 13874 "Unexpected imaginary literal."); 13875 13876 Result.makeComplexInt(); 13877 APSInt &Imag = Result.IntImag; 13878 if (!EvaluateInteger(SubExpr, Imag, Info)) 13879 return false; 13880 13881 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13882 return true; 13883 } 13884 } 13885 13886 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13887 13888 switch (E->getCastKind()) { 13889 case CK_BitCast: 13890 case CK_BaseToDerived: 13891 case CK_DerivedToBase: 13892 case CK_UncheckedDerivedToBase: 13893 case CK_Dynamic: 13894 case CK_ToUnion: 13895 case CK_ArrayToPointerDecay: 13896 case CK_FunctionToPointerDecay: 13897 case CK_NullToPointer: 13898 case CK_NullToMemberPointer: 13899 case CK_BaseToDerivedMemberPointer: 13900 case CK_DerivedToBaseMemberPointer: 13901 case CK_MemberPointerToBoolean: 13902 case CK_ReinterpretMemberPointer: 13903 case CK_ConstructorConversion: 13904 case CK_IntegralToPointer: 13905 case CK_PointerToIntegral: 13906 case CK_PointerToBoolean: 13907 case CK_ToVoid: 13908 case CK_VectorSplat: 13909 case CK_IntegralCast: 13910 case CK_BooleanToSignedIntegral: 13911 case CK_IntegralToBoolean: 13912 case CK_IntegralToFloating: 13913 case CK_FloatingToIntegral: 13914 case CK_FloatingToBoolean: 13915 case CK_FloatingCast: 13916 case CK_CPointerToObjCPointerCast: 13917 case CK_BlockPointerToObjCPointerCast: 13918 case CK_AnyPointerToBlockPointerCast: 13919 case CK_ObjCObjectLValueCast: 13920 case CK_FloatingComplexToReal: 13921 case CK_FloatingComplexToBoolean: 13922 case CK_IntegralComplexToReal: 13923 case CK_IntegralComplexToBoolean: 13924 case CK_ARCProduceObject: 13925 case CK_ARCConsumeObject: 13926 case CK_ARCReclaimReturnedObject: 13927 case CK_ARCExtendBlockObject: 13928 case CK_CopyAndAutoreleaseBlockObject: 13929 case CK_BuiltinFnToFnPtr: 13930 case CK_ZeroToOCLOpaqueType: 13931 case CK_NonAtomicToAtomic: 13932 case CK_AddressSpaceConversion: 13933 case CK_IntToOCLSampler: 13934 case CK_FloatingToFixedPoint: 13935 case CK_FixedPointToFloating: 13936 case CK_FixedPointCast: 13937 case CK_FixedPointToBoolean: 13938 case CK_FixedPointToIntegral: 13939 case CK_IntegralToFixedPoint: 13940 llvm_unreachable("invalid cast kind for complex value"); 13941 13942 case CK_LValueToRValue: 13943 case CK_AtomicToNonAtomic: 13944 case CK_NoOp: 13945 case CK_LValueToRValueBitCast: 13946 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13947 13948 case CK_Dependent: 13949 case CK_LValueBitCast: 13950 case CK_UserDefinedConversion: 13951 return Error(E); 13952 13953 case CK_FloatingRealToComplex: { 13954 APFloat &Real = Result.FloatReal; 13955 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13956 return false; 13957 13958 Result.makeComplexFloat(); 13959 Result.FloatImag = APFloat(Real.getSemantics()); 13960 return true; 13961 } 13962 13963 case CK_FloatingComplexCast: { 13964 if (!Visit(E->getSubExpr())) 13965 return false; 13966 13967 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13968 QualType From 13969 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13970 13971 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13972 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13973 } 13974 13975 case CK_FloatingComplexToIntegralComplex: { 13976 if (!Visit(E->getSubExpr())) 13977 return false; 13978 13979 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13980 QualType From 13981 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13982 Result.makeComplexInt(); 13983 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13984 To, Result.IntReal) && 13985 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13986 To, Result.IntImag); 13987 } 13988 13989 case CK_IntegralRealToComplex: { 13990 APSInt &Real = Result.IntReal; 13991 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13992 return false; 13993 13994 Result.makeComplexInt(); 13995 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13996 return true; 13997 } 13998 13999 case CK_IntegralComplexCast: { 14000 if (!Visit(E->getSubExpr())) 14001 return false; 14002 14003 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14004 QualType From 14005 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14006 14007 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14008 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14009 return true; 14010 } 14011 14012 case CK_IntegralComplexToFloatingComplex: { 14013 if (!Visit(E->getSubExpr())) 14014 return false; 14015 14016 const FPOptions FPO = E->getFPFeaturesInEffect( 14017 Info.Ctx.getLangOpts()); 14018 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14019 QualType From 14020 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14021 Result.makeComplexFloat(); 14022 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14023 To, Result.FloatReal) && 14024 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14025 To, Result.FloatImag); 14026 } 14027 } 14028 14029 llvm_unreachable("unknown cast resulting in complex value"); 14030 } 14031 14032 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14033 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14034 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14035 14036 // Track whether the LHS or RHS is real at the type system level. When this is 14037 // the case we can simplify our evaluation strategy. 14038 bool LHSReal = false, RHSReal = false; 14039 14040 bool LHSOK; 14041 if (E->getLHS()->getType()->isRealFloatingType()) { 14042 LHSReal = true; 14043 APFloat &Real = Result.FloatReal; 14044 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14045 if (LHSOK) { 14046 Result.makeComplexFloat(); 14047 Result.FloatImag = APFloat(Real.getSemantics()); 14048 } 14049 } else { 14050 LHSOK = Visit(E->getLHS()); 14051 } 14052 if (!LHSOK && !Info.noteFailure()) 14053 return false; 14054 14055 ComplexValue RHS; 14056 if (E->getRHS()->getType()->isRealFloatingType()) { 14057 RHSReal = true; 14058 APFloat &Real = RHS.FloatReal; 14059 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14060 return false; 14061 RHS.makeComplexFloat(); 14062 RHS.FloatImag = APFloat(Real.getSemantics()); 14063 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14064 return false; 14065 14066 assert(!(LHSReal && RHSReal) && 14067 "Cannot have both operands of a complex operation be real."); 14068 switch (E->getOpcode()) { 14069 default: return Error(E); 14070 case BO_Add: 14071 if (Result.isComplexFloat()) { 14072 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14073 APFloat::rmNearestTiesToEven); 14074 if (LHSReal) 14075 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14076 else if (!RHSReal) 14077 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14078 APFloat::rmNearestTiesToEven); 14079 } else { 14080 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14081 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14082 } 14083 break; 14084 case BO_Sub: 14085 if (Result.isComplexFloat()) { 14086 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14087 APFloat::rmNearestTiesToEven); 14088 if (LHSReal) { 14089 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14090 Result.getComplexFloatImag().changeSign(); 14091 } else if (!RHSReal) { 14092 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14093 APFloat::rmNearestTiesToEven); 14094 } 14095 } else { 14096 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14097 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14098 } 14099 break; 14100 case BO_Mul: 14101 if (Result.isComplexFloat()) { 14102 // This is an implementation of complex multiplication according to the 14103 // constraints laid out in C11 Annex G. The implementation uses the 14104 // following naming scheme: 14105 // (a + ib) * (c + id) 14106 ComplexValue LHS = Result; 14107 APFloat &A = LHS.getComplexFloatReal(); 14108 APFloat &B = LHS.getComplexFloatImag(); 14109 APFloat &C = RHS.getComplexFloatReal(); 14110 APFloat &D = RHS.getComplexFloatImag(); 14111 APFloat &ResR = Result.getComplexFloatReal(); 14112 APFloat &ResI = Result.getComplexFloatImag(); 14113 if (LHSReal) { 14114 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14115 ResR = A * C; 14116 ResI = A * D; 14117 } else if (RHSReal) { 14118 ResR = C * A; 14119 ResI = C * B; 14120 } else { 14121 // In the fully general case, we need to handle NaNs and infinities 14122 // robustly. 14123 APFloat AC = A * C; 14124 APFloat BD = B * D; 14125 APFloat AD = A * D; 14126 APFloat BC = B * C; 14127 ResR = AC - BD; 14128 ResI = AD + BC; 14129 if (ResR.isNaN() && ResI.isNaN()) { 14130 bool Recalc = false; 14131 if (A.isInfinity() || B.isInfinity()) { 14132 A = APFloat::copySign( 14133 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14134 B = APFloat::copySign( 14135 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14136 if (C.isNaN()) 14137 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14138 if (D.isNaN()) 14139 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14140 Recalc = true; 14141 } 14142 if (C.isInfinity() || D.isInfinity()) { 14143 C = APFloat::copySign( 14144 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14145 D = APFloat::copySign( 14146 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14147 if (A.isNaN()) 14148 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14149 if (B.isNaN()) 14150 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14151 Recalc = true; 14152 } 14153 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14154 AD.isInfinity() || BC.isInfinity())) { 14155 if (A.isNaN()) 14156 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14157 if (B.isNaN()) 14158 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14159 if (C.isNaN()) 14160 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14161 if (D.isNaN()) 14162 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14163 Recalc = true; 14164 } 14165 if (Recalc) { 14166 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14167 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14168 } 14169 } 14170 } 14171 } else { 14172 ComplexValue LHS = Result; 14173 Result.getComplexIntReal() = 14174 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14175 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14176 Result.getComplexIntImag() = 14177 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14178 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14179 } 14180 break; 14181 case BO_Div: 14182 if (Result.isComplexFloat()) { 14183 // This is an implementation of complex division according to the 14184 // constraints laid out in C11 Annex G. The implementation uses the 14185 // following naming scheme: 14186 // (a + ib) / (c + id) 14187 ComplexValue LHS = Result; 14188 APFloat &A = LHS.getComplexFloatReal(); 14189 APFloat &B = LHS.getComplexFloatImag(); 14190 APFloat &C = RHS.getComplexFloatReal(); 14191 APFloat &D = RHS.getComplexFloatImag(); 14192 APFloat &ResR = Result.getComplexFloatReal(); 14193 APFloat &ResI = Result.getComplexFloatImag(); 14194 if (RHSReal) { 14195 ResR = A / C; 14196 ResI = B / C; 14197 } else { 14198 if (LHSReal) { 14199 // No real optimizations we can do here, stub out with zero. 14200 B = APFloat::getZero(A.getSemantics()); 14201 } 14202 int DenomLogB = 0; 14203 APFloat MaxCD = maxnum(abs(C), abs(D)); 14204 if (MaxCD.isFinite()) { 14205 DenomLogB = ilogb(MaxCD); 14206 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14207 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14208 } 14209 APFloat Denom = C * C + D * D; 14210 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14211 APFloat::rmNearestTiesToEven); 14212 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14213 APFloat::rmNearestTiesToEven); 14214 if (ResR.isNaN() && ResI.isNaN()) { 14215 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14216 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14217 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14218 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14219 D.isFinite()) { 14220 A = APFloat::copySign( 14221 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14222 B = APFloat::copySign( 14223 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14224 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14225 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14226 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14227 C = APFloat::copySign( 14228 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14229 D = APFloat::copySign( 14230 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14231 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14232 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14233 } 14234 } 14235 } 14236 } else { 14237 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14238 return Error(E, diag::note_expr_divide_by_zero); 14239 14240 ComplexValue LHS = Result; 14241 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14242 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14243 Result.getComplexIntReal() = 14244 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14245 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14246 Result.getComplexIntImag() = 14247 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14248 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14249 } 14250 break; 14251 } 14252 14253 return true; 14254 } 14255 14256 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14257 // Get the operand value into 'Result'. 14258 if (!Visit(E->getSubExpr())) 14259 return false; 14260 14261 switch (E->getOpcode()) { 14262 default: 14263 return Error(E); 14264 case UO_Extension: 14265 return true; 14266 case UO_Plus: 14267 // The result is always just the subexpr. 14268 return true; 14269 case UO_Minus: 14270 if (Result.isComplexFloat()) { 14271 Result.getComplexFloatReal().changeSign(); 14272 Result.getComplexFloatImag().changeSign(); 14273 } 14274 else { 14275 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14276 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14277 } 14278 return true; 14279 case UO_Not: 14280 if (Result.isComplexFloat()) 14281 Result.getComplexFloatImag().changeSign(); 14282 else 14283 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14284 return true; 14285 } 14286 } 14287 14288 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14289 if (E->getNumInits() == 2) { 14290 if (E->getType()->isComplexType()) { 14291 Result.makeComplexFloat(); 14292 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14293 return false; 14294 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14295 return false; 14296 } else { 14297 Result.makeComplexInt(); 14298 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14299 return false; 14300 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14301 return false; 14302 } 14303 return true; 14304 } 14305 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14306 } 14307 14308 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14309 switch (E->getBuiltinCallee()) { 14310 case Builtin::BI__builtin_complex: 14311 Result.makeComplexFloat(); 14312 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14313 return false; 14314 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14315 return false; 14316 return true; 14317 14318 default: 14319 break; 14320 } 14321 14322 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14323 } 14324 14325 //===----------------------------------------------------------------------===// 14326 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14327 // implicit conversion. 14328 //===----------------------------------------------------------------------===// 14329 14330 namespace { 14331 class AtomicExprEvaluator : 14332 public ExprEvaluatorBase<AtomicExprEvaluator> { 14333 const LValue *This; 14334 APValue &Result; 14335 public: 14336 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14337 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14338 14339 bool Success(const APValue &V, const Expr *E) { 14340 Result = V; 14341 return true; 14342 } 14343 14344 bool ZeroInitialization(const Expr *E) { 14345 ImplicitValueInitExpr VIE( 14346 E->getType()->castAs<AtomicType>()->getValueType()); 14347 // For atomic-qualified class (and array) types in C++, initialize the 14348 // _Atomic-wrapped subobject directly, in-place. 14349 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14350 : Evaluate(Result, Info, &VIE); 14351 } 14352 14353 bool VisitCastExpr(const CastExpr *E) { 14354 switch (E->getCastKind()) { 14355 default: 14356 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14357 case CK_NonAtomicToAtomic: 14358 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14359 : Evaluate(Result, Info, E->getSubExpr()); 14360 } 14361 } 14362 }; 14363 } // end anonymous namespace 14364 14365 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14366 EvalInfo &Info) { 14367 assert(!E->isValueDependent()); 14368 assert(E->isRValue() && E->getType()->isAtomicType()); 14369 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14370 } 14371 14372 //===----------------------------------------------------------------------===// 14373 // Void expression evaluation, primarily for a cast to void on the LHS of a 14374 // comma operator 14375 //===----------------------------------------------------------------------===// 14376 14377 namespace { 14378 class VoidExprEvaluator 14379 : public ExprEvaluatorBase<VoidExprEvaluator> { 14380 public: 14381 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14382 14383 bool Success(const APValue &V, const Expr *e) { return true; } 14384 14385 bool ZeroInitialization(const Expr *E) { return true; } 14386 14387 bool VisitCastExpr(const CastExpr *E) { 14388 switch (E->getCastKind()) { 14389 default: 14390 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14391 case CK_ToVoid: 14392 VisitIgnoredValue(E->getSubExpr()); 14393 return true; 14394 } 14395 } 14396 14397 bool VisitCallExpr(const CallExpr *E) { 14398 switch (E->getBuiltinCallee()) { 14399 case Builtin::BI__assume: 14400 case Builtin::BI__builtin_assume: 14401 // The argument is not evaluated! 14402 return true; 14403 14404 case Builtin::BI__builtin_operator_delete: 14405 return HandleOperatorDeleteCall(Info, E); 14406 14407 default: 14408 break; 14409 } 14410 14411 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14412 } 14413 14414 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14415 }; 14416 } // end anonymous namespace 14417 14418 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14419 // We cannot speculatively evaluate a delete expression. 14420 if (Info.SpeculativeEvaluationDepth) 14421 return false; 14422 14423 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14424 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14425 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14426 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14427 return false; 14428 } 14429 14430 const Expr *Arg = E->getArgument(); 14431 14432 LValue Pointer; 14433 if (!EvaluatePointer(Arg, Pointer, Info)) 14434 return false; 14435 if (Pointer.Designator.Invalid) 14436 return false; 14437 14438 // Deleting a null pointer has no effect. 14439 if (Pointer.isNullPointer()) { 14440 // This is the only case where we need to produce an extension warning: 14441 // the only other way we can succeed is if we find a dynamic allocation, 14442 // and we will have warned when we allocated it in that case. 14443 if (!Info.getLangOpts().CPlusPlus20) 14444 Info.CCEDiag(E, diag::note_constexpr_new); 14445 return true; 14446 } 14447 14448 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14449 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14450 if (!Alloc) 14451 return false; 14452 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14453 14454 // For the non-array case, the designator must be empty if the static type 14455 // does not have a virtual destructor. 14456 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14457 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14458 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14459 << Arg->getType()->getPointeeType() << AllocType; 14460 return false; 14461 } 14462 14463 // For a class type with a virtual destructor, the selected operator delete 14464 // is the one looked up when building the destructor. 14465 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14466 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14467 if (VirtualDelete && 14468 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14469 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14470 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14471 return false; 14472 } 14473 } 14474 14475 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14476 (*Alloc)->Value, AllocType)) 14477 return false; 14478 14479 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14480 // The element was already erased. This means the destructor call also 14481 // deleted the object. 14482 // FIXME: This probably results in undefined behavior before we get this 14483 // far, and should be diagnosed elsewhere first. 14484 Info.FFDiag(E, diag::note_constexpr_double_delete); 14485 return false; 14486 } 14487 14488 return true; 14489 } 14490 14491 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14492 assert(!E->isValueDependent()); 14493 assert(E->isRValue() && E->getType()->isVoidType()); 14494 return VoidExprEvaluator(Info).Visit(E); 14495 } 14496 14497 //===----------------------------------------------------------------------===// 14498 // Top level Expr::EvaluateAsRValue method. 14499 //===----------------------------------------------------------------------===// 14500 14501 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14502 assert(!E->isValueDependent()); 14503 // In C, function designators are not lvalues, but we evaluate them as if they 14504 // are. 14505 QualType T = E->getType(); 14506 if (E->isGLValue() || T->isFunctionType()) { 14507 LValue LV; 14508 if (!EvaluateLValue(E, LV, Info)) 14509 return false; 14510 LV.moveInto(Result); 14511 } else if (T->isVectorType()) { 14512 if (!EvaluateVector(E, Result, Info)) 14513 return false; 14514 } else if (T->isIntegralOrEnumerationType()) { 14515 if (!IntExprEvaluator(Info, Result).Visit(E)) 14516 return false; 14517 } else if (T->hasPointerRepresentation()) { 14518 LValue LV; 14519 if (!EvaluatePointer(E, LV, Info)) 14520 return false; 14521 LV.moveInto(Result); 14522 } else if (T->isRealFloatingType()) { 14523 llvm::APFloat F(0.0); 14524 if (!EvaluateFloat(E, F, Info)) 14525 return false; 14526 Result = APValue(F); 14527 } else if (T->isAnyComplexType()) { 14528 ComplexValue C; 14529 if (!EvaluateComplex(E, C, Info)) 14530 return false; 14531 C.moveInto(Result); 14532 } else if (T->isFixedPointType()) { 14533 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14534 } else if (T->isMemberPointerType()) { 14535 MemberPtr P; 14536 if (!EvaluateMemberPointer(E, P, Info)) 14537 return false; 14538 P.moveInto(Result); 14539 return true; 14540 } else if (T->isArrayType()) { 14541 LValue LV; 14542 APValue &Value = 14543 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14544 if (!EvaluateArray(E, LV, Value, Info)) 14545 return false; 14546 Result = Value; 14547 } else if (T->isRecordType()) { 14548 LValue LV; 14549 APValue &Value = 14550 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14551 if (!EvaluateRecord(E, LV, Value, Info)) 14552 return false; 14553 Result = Value; 14554 } else if (T->isVoidType()) { 14555 if (!Info.getLangOpts().CPlusPlus11) 14556 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14557 << E->getType(); 14558 if (!EvaluateVoid(E, Info)) 14559 return false; 14560 } else if (T->isAtomicType()) { 14561 QualType Unqual = T.getAtomicUnqualifiedType(); 14562 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14563 LValue LV; 14564 APValue &Value = Info.CurrentCall->createTemporary( 14565 E, Unqual, ScopeKind::FullExpression, LV); 14566 if (!EvaluateAtomic(E, &LV, Value, Info)) 14567 return false; 14568 } else { 14569 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14570 return false; 14571 } 14572 } else if (Info.getLangOpts().CPlusPlus11) { 14573 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14574 return false; 14575 } else { 14576 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14577 return false; 14578 } 14579 14580 return true; 14581 } 14582 14583 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14584 /// cases, the in-place evaluation is essential, since later initializers for 14585 /// an object can indirectly refer to subobjects which were initialized earlier. 14586 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14587 const Expr *E, bool AllowNonLiteralTypes) { 14588 assert(!E->isValueDependent()); 14589 14590 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14591 return false; 14592 14593 if (E->isRValue()) { 14594 // Evaluate arrays and record types in-place, so that later initializers can 14595 // refer to earlier-initialized members of the object. 14596 QualType T = E->getType(); 14597 if (T->isArrayType()) 14598 return EvaluateArray(E, This, Result, Info); 14599 else if (T->isRecordType()) 14600 return EvaluateRecord(E, This, Result, Info); 14601 else if (T->isAtomicType()) { 14602 QualType Unqual = T.getAtomicUnqualifiedType(); 14603 if (Unqual->isArrayType() || Unqual->isRecordType()) 14604 return EvaluateAtomic(E, &This, Result, Info); 14605 } 14606 } 14607 14608 // For any other type, in-place evaluation is unimportant. 14609 return Evaluate(Result, Info, E); 14610 } 14611 14612 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14613 /// lvalue-to-rvalue cast if it is an lvalue. 14614 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14615 assert(!E->isValueDependent()); 14616 if (Info.EnableNewConstInterp) { 14617 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14618 return false; 14619 } else { 14620 if (E->getType().isNull()) 14621 return false; 14622 14623 if (!CheckLiteralType(Info, E)) 14624 return false; 14625 14626 if (!::Evaluate(Result, Info, E)) 14627 return false; 14628 14629 if (E->isGLValue()) { 14630 LValue LV; 14631 LV.setFrom(Info.Ctx, Result); 14632 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14633 return false; 14634 } 14635 } 14636 14637 // Check this core constant expression is a constant expression. 14638 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14639 ConstantExprKind::Normal) && 14640 CheckMemoryLeaks(Info); 14641 } 14642 14643 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14644 const ASTContext &Ctx, bool &IsConst) { 14645 // Fast-path evaluations of integer literals, since we sometimes see files 14646 // containing vast quantities of these. 14647 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14648 Result.Val = APValue(APSInt(L->getValue(), 14649 L->getType()->isUnsignedIntegerType())); 14650 IsConst = true; 14651 return true; 14652 } 14653 14654 // This case should be rare, but we need to check it before we check on 14655 // the type below. 14656 if (Exp->getType().isNull()) { 14657 IsConst = false; 14658 return true; 14659 } 14660 14661 // FIXME: Evaluating values of large array and record types can cause 14662 // performance problems. Only do so in C++11 for now. 14663 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14664 Exp->getType()->isRecordType()) && 14665 !Ctx.getLangOpts().CPlusPlus11) { 14666 IsConst = false; 14667 return true; 14668 } 14669 return false; 14670 } 14671 14672 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14673 Expr::SideEffectsKind SEK) { 14674 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14675 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14676 } 14677 14678 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14679 const ASTContext &Ctx, EvalInfo &Info) { 14680 assert(!E->isValueDependent()); 14681 bool IsConst; 14682 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14683 return IsConst; 14684 14685 return EvaluateAsRValue(Info, E, Result.Val); 14686 } 14687 14688 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14689 const ASTContext &Ctx, 14690 Expr::SideEffectsKind AllowSideEffects, 14691 EvalInfo &Info) { 14692 assert(!E->isValueDependent()); 14693 if (!E->getType()->isIntegralOrEnumerationType()) 14694 return false; 14695 14696 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14697 !ExprResult.Val.isInt() || 14698 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14699 return false; 14700 14701 return true; 14702 } 14703 14704 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14705 const ASTContext &Ctx, 14706 Expr::SideEffectsKind AllowSideEffects, 14707 EvalInfo &Info) { 14708 assert(!E->isValueDependent()); 14709 if (!E->getType()->isFixedPointType()) 14710 return false; 14711 14712 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14713 return false; 14714 14715 if (!ExprResult.Val.isFixedPoint() || 14716 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14717 return false; 14718 14719 return true; 14720 } 14721 14722 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14723 /// any crazy technique (that has nothing to do with language standards) that 14724 /// we want to. If this function returns true, it returns the folded constant 14725 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14726 /// will be applied to the result. 14727 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14728 bool InConstantContext) const { 14729 assert(!isValueDependent() && 14730 "Expression evaluator can't be called on a dependent expression."); 14731 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14732 Info.InConstantContext = InConstantContext; 14733 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14734 } 14735 14736 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14737 bool InConstantContext) const { 14738 assert(!isValueDependent() && 14739 "Expression evaluator can't be called on a dependent expression."); 14740 EvalResult Scratch; 14741 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14742 HandleConversionToBool(Scratch.Val, Result); 14743 } 14744 14745 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14746 SideEffectsKind AllowSideEffects, 14747 bool InConstantContext) const { 14748 assert(!isValueDependent() && 14749 "Expression evaluator can't be called on a dependent expression."); 14750 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14751 Info.InConstantContext = InConstantContext; 14752 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14753 } 14754 14755 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14756 SideEffectsKind AllowSideEffects, 14757 bool InConstantContext) const { 14758 assert(!isValueDependent() && 14759 "Expression evaluator can't be called on a dependent expression."); 14760 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14761 Info.InConstantContext = InConstantContext; 14762 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14763 } 14764 14765 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14766 SideEffectsKind AllowSideEffects, 14767 bool InConstantContext) const { 14768 assert(!isValueDependent() && 14769 "Expression evaluator can't be called on a dependent expression."); 14770 14771 if (!getType()->isRealFloatingType()) 14772 return false; 14773 14774 EvalResult ExprResult; 14775 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14776 !ExprResult.Val.isFloat() || 14777 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14778 return false; 14779 14780 Result = ExprResult.Val.getFloat(); 14781 return true; 14782 } 14783 14784 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14785 bool InConstantContext) const { 14786 assert(!isValueDependent() && 14787 "Expression evaluator can't be called on a dependent expression."); 14788 14789 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14790 Info.InConstantContext = InConstantContext; 14791 LValue LV; 14792 CheckedTemporaries CheckedTemps; 14793 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14794 Result.HasSideEffects || 14795 !CheckLValueConstantExpression(Info, getExprLoc(), 14796 Ctx.getLValueReferenceType(getType()), LV, 14797 ConstantExprKind::Normal, CheckedTemps)) 14798 return false; 14799 14800 LV.moveInto(Result.Val); 14801 return true; 14802 } 14803 14804 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14805 APValue DestroyedValue, QualType Type, 14806 SourceLocation Loc, Expr::EvalStatus &EStatus, 14807 bool IsConstantDestruction) { 14808 EvalInfo Info(Ctx, EStatus, 14809 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14810 : EvalInfo::EM_ConstantFold); 14811 Info.setEvaluatingDecl(Base, DestroyedValue, 14812 EvalInfo::EvaluatingDeclKind::Dtor); 14813 Info.InConstantContext = IsConstantDestruction; 14814 14815 LValue LVal; 14816 LVal.set(Base); 14817 14818 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14819 EStatus.HasSideEffects) 14820 return false; 14821 14822 if (!Info.discardCleanups()) 14823 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14824 14825 return true; 14826 } 14827 14828 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14829 ConstantExprKind Kind) const { 14830 assert(!isValueDependent() && 14831 "Expression evaluator can't be called on a dependent expression."); 14832 14833 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14834 EvalInfo Info(Ctx, Result, EM); 14835 Info.InConstantContext = true; 14836 14837 // The type of the object we're initializing is 'const T' for a class NTTP. 14838 QualType T = getType(); 14839 if (Kind == ConstantExprKind::ClassTemplateArgument) 14840 T.addConst(); 14841 14842 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14843 // represent the result of the evaluation. CheckConstantExpression ensures 14844 // this doesn't escape. 14845 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14846 APValue::LValueBase Base(&BaseMTE); 14847 14848 Info.setEvaluatingDecl(Base, Result.Val); 14849 LValue LVal; 14850 LVal.set(Base); 14851 14852 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14853 return false; 14854 14855 if (!Info.discardCleanups()) 14856 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14857 14858 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14859 Result.Val, Kind)) 14860 return false; 14861 if (!CheckMemoryLeaks(Info)) 14862 return false; 14863 14864 // If this is a class template argument, it's required to have constant 14865 // destruction too. 14866 if (Kind == ConstantExprKind::ClassTemplateArgument && 14867 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 14868 true) || 14869 Result.HasSideEffects)) { 14870 // FIXME: Prefix a note to indicate that the problem is lack of constant 14871 // destruction. 14872 return false; 14873 } 14874 14875 return true; 14876 } 14877 14878 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14879 const VarDecl *VD, 14880 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14881 bool IsConstantInitialization) const { 14882 assert(!isValueDependent() && 14883 "Expression evaluator can't be called on a dependent expression."); 14884 14885 // FIXME: Evaluating initializers for large array and record types can cause 14886 // performance problems. Only do so in C++11 for now. 14887 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14888 !Ctx.getLangOpts().CPlusPlus11) 14889 return false; 14890 14891 Expr::EvalStatus EStatus; 14892 EStatus.Diag = &Notes; 14893 14894 EvalInfo Info(Ctx, EStatus, 14895 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14896 ? EvalInfo::EM_ConstantExpression 14897 : EvalInfo::EM_ConstantFold); 14898 Info.setEvaluatingDecl(VD, Value); 14899 Info.InConstantContext = IsConstantInitialization; 14900 14901 SourceLocation DeclLoc = VD->getLocation(); 14902 QualType DeclTy = VD->getType(); 14903 14904 if (Info.EnableNewConstInterp) { 14905 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14906 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14907 return false; 14908 } else { 14909 LValue LVal; 14910 LVal.set(VD); 14911 14912 if (!EvaluateInPlace(Value, Info, LVal, this, 14913 /*AllowNonLiteralTypes=*/true) || 14914 EStatus.HasSideEffects) 14915 return false; 14916 14917 // At this point, any lifetime-extended temporaries are completely 14918 // initialized. 14919 Info.performLifetimeExtension(); 14920 14921 if (!Info.discardCleanups()) 14922 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14923 } 14924 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14925 ConstantExprKind::Normal) && 14926 CheckMemoryLeaks(Info); 14927 } 14928 14929 bool VarDecl::evaluateDestruction( 14930 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14931 Expr::EvalStatus EStatus; 14932 EStatus.Diag = &Notes; 14933 14934 // Only treat the destruction as constant destruction if we formally have 14935 // constant initialization (or are usable in a constant expression). 14936 bool IsConstantDestruction = hasConstantInitialization(); 14937 14938 // Make a copy of the value for the destructor to mutate, if we know it. 14939 // Otherwise, treat the value as default-initialized; if the destructor works 14940 // anyway, then the destruction is constant (and must be essentially empty). 14941 APValue DestroyedValue; 14942 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14943 DestroyedValue = *getEvaluatedValue(); 14944 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14945 return false; 14946 14947 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14948 getType(), getLocation(), EStatus, 14949 IsConstantDestruction) || 14950 EStatus.HasSideEffects) 14951 return false; 14952 14953 ensureEvaluatedStmt()->HasConstantDestruction = true; 14954 return true; 14955 } 14956 14957 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14958 /// constant folded, but discard the result. 14959 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14960 assert(!isValueDependent() && 14961 "Expression evaluator can't be called on a dependent expression."); 14962 14963 EvalResult Result; 14964 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14965 !hasUnacceptableSideEffect(Result, SEK); 14966 } 14967 14968 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14969 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14970 assert(!isValueDependent() && 14971 "Expression evaluator can't be called on a dependent expression."); 14972 14973 EvalResult EVResult; 14974 EVResult.Diag = Diag; 14975 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14976 Info.InConstantContext = true; 14977 14978 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14979 (void)Result; 14980 assert(Result && "Could not evaluate expression"); 14981 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14982 14983 return EVResult.Val.getInt(); 14984 } 14985 14986 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14987 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14988 assert(!isValueDependent() && 14989 "Expression evaluator can't be called on a dependent expression."); 14990 14991 EvalResult EVResult; 14992 EVResult.Diag = Diag; 14993 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14994 Info.InConstantContext = true; 14995 Info.CheckingForUndefinedBehavior = true; 14996 14997 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14998 (void)Result; 14999 assert(Result && "Could not evaluate expression"); 15000 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15001 15002 return EVResult.Val.getInt(); 15003 } 15004 15005 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15006 assert(!isValueDependent() && 15007 "Expression evaluator can't be called on a dependent expression."); 15008 15009 bool IsConst; 15010 EvalResult EVResult; 15011 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15012 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15013 Info.CheckingForUndefinedBehavior = true; 15014 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15015 } 15016 } 15017 15018 bool Expr::EvalResult::isGlobalLValue() const { 15019 assert(Val.isLValue()); 15020 return IsGlobalLValue(Val.getLValueBase()); 15021 } 15022 15023 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15024 /// an integer constant expression. 15025 15026 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15027 /// comma, etc 15028 15029 // CheckICE - This function does the fundamental ICE checking: the returned 15030 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15031 // and a (possibly null) SourceLocation indicating the location of the problem. 15032 // 15033 // Note that to reduce code duplication, this helper does no evaluation 15034 // itself; the caller checks whether the expression is evaluatable, and 15035 // in the rare cases where CheckICE actually cares about the evaluated 15036 // value, it calls into Evaluate. 15037 15038 namespace { 15039 15040 enum ICEKind { 15041 /// This expression is an ICE. 15042 IK_ICE, 15043 /// This expression is not an ICE, but if it isn't evaluated, it's 15044 /// a legal subexpression for an ICE. This return value is used to handle 15045 /// the comma operator in C99 mode, and non-constant subexpressions. 15046 IK_ICEIfUnevaluated, 15047 /// This expression is not an ICE, and is not a legal subexpression for one. 15048 IK_NotICE 15049 }; 15050 15051 struct ICEDiag { 15052 ICEKind Kind; 15053 SourceLocation Loc; 15054 15055 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15056 }; 15057 15058 } 15059 15060 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15061 15062 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15063 15064 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15065 Expr::EvalResult EVResult; 15066 Expr::EvalStatus Status; 15067 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15068 15069 Info.InConstantContext = true; 15070 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15071 !EVResult.Val.isInt()) 15072 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15073 15074 return NoDiag(); 15075 } 15076 15077 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15078 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15079 if (!E->getType()->isIntegralOrEnumerationType()) 15080 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15081 15082 switch (E->getStmtClass()) { 15083 #define ABSTRACT_STMT(Node) 15084 #define STMT(Node, Base) case Expr::Node##Class: 15085 #define EXPR(Node, Base) 15086 #include "clang/AST/StmtNodes.inc" 15087 case Expr::PredefinedExprClass: 15088 case Expr::FloatingLiteralClass: 15089 case Expr::ImaginaryLiteralClass: 15090 case Expr::StringLiteralClass: 15091 case Expr::ArraySubscriptExprClass: 15092 case Expr::MatrixSubscriptExprClass: 15093 case Expr::OMPArraySectionExprClass: 15094 case Expr::OMPArrayShapingExprClass: 15095 case Expr::OMPIteratorExprClass: 15096 case Expr::MemberExprClass: 15097 case Expr::CompoundAssignOperatorClass: 15098 case Expr::CompoundLiteralExprClass: 15099 case Expr::ExtVectorElementExprClass: 15100 case Expr::DesignatedInitExprClass: 15101 case Expr::ArrayInitLoopExprClass: 15102 case Expr::ArrayInitIndexExprClass: 15103 case Expr::NoInitExprClass: 15104 case Expr::DesignatedInitUpdateExprClass: 15105 case Expr::ImplicitValueInitExprClass: 15106 case Expr::ParenListExprClass: 15107 case Expr::VAArgExprClass: 15108 case Expr::AddrLabelExprClass: 15109 case Expr::StmtExprClass: 15110 case Expr::CXXMemberCallExprClass: 15111 case Expr::CUDAKernelCallExprClass: 15112 case Expr::CXXAddrspaceCastExprClass: 15113 case Expr::CXXDynamicCastExprClass: 15114 case Expr::CXXTypeidExprClass: 15115 case Expr::CXXUuidofExprClass: 15116 case Expr::MSPropertyRefExprClass: 15117 case Expr::MSPropertySubscriptExprClass: 15118 case Expr::CXXNullPtrLiteralExprClass: 15119 case Expr::UserDefinedLiteralClass: 15120 case Expr::CXXThisExprClass: 15121 case Expr::CXXThrowExprClass: 15122 case Expr::CXXNewExprClass: 15123 case Expr::CXXDeleteExprClass: 15124 case Expr::CXXPseudoDestructorExprClass: 15125 case Expr::UnresolvedLookupExprClass: 15126 case Expr::TypoExprClass: 15127 case Expr::RecoveryExprClass: 15128 case Expr::DependentScopeDeclRefExprClass: 15129 case Expr::CXXConstructExprClass: 15130 case Expr::CXXInheritedCtorInitExprClass: 15131 case Expr::CXXStdInitializerListExprClass: 15132 case Expr::CXXBindTemporaryExprClass: 15133 case Expr::ExprWithCleanupsClass: 15134 case Expr::CXXTemporaryObjectExprClass: 15135 case Expr::CXXUnresolvedConstructExprClass: 15136 case Expr::CXXDependentScopeMemberExprClass: 15137 case Expr::UnresolvedMemberExprClass: 15138 case Expr::ObjCStringLiteralClass: 15139 case Expr::ObjCBoxedExprClass: 15140 case Expr::ObjCArrayLiteralClass: 15141 case Expr::ObjCDictionaryLiteralClass: 15142 case Expr::ObjCEncodeExprClass: 15143 case Expr::ObjCMessageExprClass: 15144 case Expr::ObjCSelectorExprClass: 15145 case Expr::ObjCProtocolExprClass: 15146 case Expr::ObjCIvarRefExprClass: 15147 case Expr::ObjCPropertyRefExprClass: 15148 case Expr::ObjCSubscriptRefExprClass: 15149 case Expr::ObjCIsaExprClass: 15150 case Expr::ObjCAvailabilityCheckExprClass: 15151 case Expr::ShuffleVectorExprClass: 15152 case Expr::ConvertVectorExprClass: 15153 case Expr::BlockExprClass: 15154 case Expr::NoStmtClass: 15155 case Expr::OpaqueValueExprClass: 15156 case Expr::PackExpansionExprClass: 15157 case Expr::SubstNonTypeTemplateParmPackExprClass: 15158 case Expr::FunctionParmPackExprClass: 15159 case Expr::AsTypeExprClass: 15160 case Expr::ObjCIndirectCopyRestoreExprClass: 15161 case Expr::MaterializeTemporaryExprClass: 15162 case Expr::PseudoObjectExprClass: 15163 case Expr::AtomicExprClass: 15164 case Expr::LambdaExprClass: 15165 case Expr::CXXFoldExprClass: 15166 case Expr::CoawaitExprClass: 15167 case Expr::DependentCoawaitExprClass: 15168 case Expr::CoyieldExprClass: 15169 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15170 15171 case Expr::InitListExprClass: { 15172 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15173 // form "T x = { a };" is equivalent to "T x = a;". 15174 // Unless we're initializing a reference, T is a scalar as it is known to be 15175 // of integral or enumeration type. 15176 if (E->isRValue()) 15177 if (cast<InitListExpr>(E)->getNumInits() == 1) 15178 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15179 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15180 } 15181 15182 case Expr::SizeOfPackExprClass: 15183 case Expr::GNUNullExprClass: 15184 case Expr::SourceLocExprClass: 15185 return NoDiag(); 15186 15187 case Expr::SubstNonTypeTemplateParmExprClass: 15188 return 15189 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15190 15191 case Expr::ConstantExprClass: 15192 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15193 15194 case Expr::ParenExprClass: 15195 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15196 case Expr::GenericSelectionExprClass: 15197 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15198 case Expr::IntegerLiteralClass: 15199 case Expr::FixedPointLiteralClass: 15200 case Expr::CharacterLiteralClass: 15201 case Expr::ObjCBoolLiteralExprClass: 15202 case Expr::CXXBoolLiteralExprClass: 15203 case Expr::CXXScalarValueInitExprClass: 15204 case Expr::TypeTraitExprClass: 15205 case Expr::ConceptSpecializationExprClass: 15206 case Expr::RequiresExprClass: 15207 case Expr::ArrayTypeTraitExprClass: 15208 case Expr::ExpressionTraitExprClass: 15209 case Expr::CXXNoexceptExprClass: 15210 return NoDiag(); 15211 case Expr::CallExprClass: 15212 case Expr::CXXOperatorCallExprClass: { 15213 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15214 // constant expressions, but they can never be ICEs because an ICE cannot 15215 // contain an operand of (pointer to) function type. 15216 const CallExpr *CE = cast<CallExpr>(E); 15217 if (CE->getBuiltinCallee()) 15218 return CheckEvalInICE(E, Ctx); 15219 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15220 } 15221 case Expr::CXXRewrittenBinaryOperatorClass: 15222 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15223 Ctx); 15224 case Expr::DeclRefExprClass: { 15225 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15226 if (isa<EnumConstantDecl>(D)) 15227 return NoDiag(); 15228 15229 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15230 // integer variables in constant expressions: 15231 // 15232 // C++ 7.1.5.1p2 15233 // A variable of non-volatile const-qualified integral or enumeration 15234 // type initialized by an ICE can be used in ICEs. 15235 // 15236 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15237 // that mode, use of reference variables should not be allowed. 15238 const VarDecl *VD = dyn_cast<VarDecl>(D); 15239 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15240 !VD->getType()->isReferenceType()) 15241 return NoDiag(); 15242 15243 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15244 } 15245 case Expr::UnaryOperatorClass: { 15246 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15247 switch (Exp->getOpcode()) { 15248 case UO_PostInc: 15249 case UO_PostDec: 15250 case UO_PreInc: 15251 case UO_PreDec: 15252 case UO_AddrOf: 15253 case UO_Deref: 15254 case UO_Coawait: 15255 // C99 6.6/3 allows increment and decrement within unevaluated 15256 // subexpressions of constant expressions, but they can never be ICEs 15257 // because an ICE cannot contain an lvalue operand. 15258 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15259 case UO_Extension: 15260 case UO_LNot: 15261 case UO_Plus: 15262 case UO_Minus: 15263 case UO_Not: 15264 case UO_Real: 15265 case UO_Imag: 15266 return CheckICE(Exp->getSubExpr(), Ctx); 15267 } 15268 llvm_unreachable("invalid unary operator class"); 15269 } 15270 case Expr::OffsetOfExprClass: { 15271 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15272 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15273 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15274 // compliance: we should warn earlier for offsetof expressions with 15275 // array subscripts that aren't ICEs, and if the array subscripts 15276 // are ICEs, the value of the offsetof must be an integer constant. 15277 return CheckEvalInICE(E, Ctx); 15278 } 15279 case Expr::UnaryExprOrTypeTraitExprClass: { 15280 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15281 if ((Exp->getKind() == UETT_SizeOf) && 15282 Exp->getTypeOfArgument()->isVariableArrayType()) 15283 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15284 return NoDiag(); 15285 } 15286 case Expr::BinaryOperatorClass: { 15287 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15288 switch (Exp->getOpcode()) { 15289 case BO_PtrMemD: 15290 case BO_PtrMemI: 15291 case BO_Assign: 15292 case BO_MulAssign: 15293 case BO_DivAssign: 15294 case BO_RemAssign: 15295 case BO_AddAssign: 15296 case BO_SubAssign: 15297 case BO_ShlAssign: 15298 case BO_ShrAssign: 15299 case BO_AndAssign: 15300 case BO_XorAssign: 15301 case BO_OrAssign: 15302 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15303 // constant expressions, but they can never be ICEs because an ICE cannot 15304 // contain an lvalue operand. 15305 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15306 15307 case BO_Mul: 15308 case BO_Div: 15309 case BO_Rem: 15310 case BO_Add: 15311 case BO_Sub: 15312 case BO_Shl: 15313 case BO_Shr: 15314 case BO_LT: 15315 case BO_GT: 15316 case BO_LE: 15317 case BO_GE: 15318 case BO_EQ: 15319 case BO_NE: 15320 case BO_And: 15321 case BO_Xor: 15322 case BO_Or: 15323 case BO_Comma: 15324 case BO_Cmp: { 15325 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15326 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15327 if (Exp->getOpcode() == BO_Div || 15328 Exp->getOpcode() == BO_Rem) { 15329 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15330 // we don't evaluate one. 15331 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15332 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15333 if (REval == 0) 15334 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15335 if (REval.isSigned() && REval.isAllOnesValue()) { 15336 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15337 if (LEval.isMinSignedValue()) 15338 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15339 } 15340 } 15341 } 15342 if (Exp->getOpcode() == BO_Comma) { 15343 if (Ctx.getLangOpts().C99) { 15344 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15345 // if it isn't evaluated. 15346 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15347 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15348 } else { 15349 // In both C89 and C++, commas in ICEs are illegal. 15350 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15351 } 15352 } 15353 return Worst(LHSResult, RHSResult); 15354 } 15355 case BO_LAnd: 15356 case BO_LOr: { 15357 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15358 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15359 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15360 // Rare case where the RHS has a comma "side-effect"; we need 15361 // to actually check the condition to see whether the side 15362 // with the comma is evaluated. 15363 if ((Exp->getOpcode() == BO_LAnd) != 15364 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15365 return RHSResult; 15366 return NoDiag(); 15367 } 15368 15369 return Worst(LHSResult, RHSResult); 15370 } 15371 } 15372 llvm_unreachable("invalid binary operator kind"); 15373 } 15374 case Expr::ImplicitCastExprClass: 15375 case Expr::CStyleCastExprClass: 15376 case Expr::CXXFunctionalCastExprClass: 15377 case Expr::CXXStaticCastExprClass: 15378 case Expr::CXXReinterpretCastExprClass: 15379 case Expr::CXXConstCastExprClass: 15380 case Expr::ObjCBridgedCastExprClass: { 15381 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15382 if (isa<ExplicitCastExpr>(E)) { 15383 if (const FloatingLiteral *FL 15384 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15385 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15386 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15387 APSInt IgnoredVal(DestWidth, !DestSigned); 15388 bool Ignored; 15389 // If the value does not fit in the destination type, the behavior is 15390 // undefined, so we are not required to treat it as a constant 15391 // expression. 15392 if (FL->getValue().convertToInteger(IgnoredVal, 15393 llvm::APFloat::rmTowardZero, 15394 &Ignored) & APFloat::opInvalidOp) 15395 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15396 return NoDiag(); 15397 } 15398 } 15399 switch (cast<CastExpr>(E)->getCastKind()) { 15400 case CK_LValueToRValue: 15401 case CK_AtomicToNonAtomic: 15402 case CK_NonAtomicToAtomic: 15403 case CK_NoOp: 15404 case CK_IntegralToBoolean: 15405 case CK_IntegralCast: 15406 return CheckICE(SubExpr, Ctx); 15407 default: 15408 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15409 } 15410 } 15411 case Expr::BinaryConditionalOperatorClass: { 15412 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15413 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15414 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15415 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15416 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15417 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15418 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15419 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15420 return FalseResult; 15421 } 15422 case Expr::ConditionalOperatorClass: { 15423 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15424 // If the condition (ignoring parens) is a __builtin_constant_p call, 15425 // then only the true side is actually considered in an integer constant 15426 // expression, and it is fully evaluated. This is an important GNU 15427 // extension. See GCC PR38377 for discussion. 15428 if (const CallExpr *CallCE 15429 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15430 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15431 return CheckEvalInICE(E, Ctx); 15432 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15433 if (CondResult.Kind == IK_NotICE) 15434 return CondResult; 15435 15436 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15437 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15438 15439 if (TrueResult.Kind == IK_NotICE) 15440 return TrueResult; 15441 if (FalseResult.Kind == IK_NotICE) 15442 return FalseResult; 15443 if (CondResult.Kind == IK_ICEIfUnevaluated) 15444 return CondResult; 15445 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15446 return NoDiag(); 15447 // Rare case where the diagnostics depend on which side is evaluated 15448 // Note that if we get here, CondResult is 0, and at least one of 15449 // TrueResult and FalseResult is non-zero. 15450 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15451 return FalseResult; 15452 return TrueResult; 15453 } 15454 case Expr::CXXDefaultArgExprClass: 15455 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15456 case Expr::CXXDefaultInitExprClass: 15457 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15458 case Expr::ChooseExprClass: { 15459 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15460 } 15461 case Expr::BuiltinBitCastExprClass: { 15462 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15463 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15464 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15465 } 15466 } 15467 15468 llvm_unreachable("Invalid StmtClass!"); 15469 } 15470 15471 /// Evaluate an expression as a C++11 integral constant expression. 15472 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15473 const Expr *E, 15474 llvm::APSInt *Value, 15475 SourceLocation *Loc) { 15476 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15477 if (Loc) *Loc = E->getExprLoc(); 15478 return false; 15479 } 15480 15481 APValue Result; 15482 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15483 return false; 15484 15485 if (!Result.isInt()) { 15486 if (Loc) *Loc = E->getExprLoc(); 15487 return false; 15488 } 15489 15490 if (Value) *Value = Result.getInt(); 15491 return true; 15492 } 15493 15494 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15495 SourceLocation *Loc) const { 15496 assert(!isValueDependent() && 15497 "Expression evaluator can't be called on a dependent expression."); 15498 15499 if (Ctx.getLangOpts().CPlusPlus11) 15500 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15501 15502 ICEDiag D = CheckICE(this, Ctx); 15503 if (D.Kind != IK_ICE) { 15504 if (Loc) *Loc = D.Loc; 15505 return false; 15506 } 15507 return true; 15508 } 15509 15510 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15511 SourceLocation *Loc, 15512 bool isEvaluated) const { 15513 assert(!isValueDependent() && 15514 "Expression evaluator can't be called on a dependent expression."); 15515 15516 APSInt Value; 15517 15518 if (Ctx.getLangOpts().CPlusPlus11) { 15519 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15520 return Value; 15521 return None; 15522 } 15523 15524 if (!isIntegerConstantExpr(Ctx, Loc)) 15525 return None; 15526 15527 // The only possible side-effects here are due to UB discovered in the 15528 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15529 // required to treat the expression as an ICE, so we produce the folded 15530 // value. 15531 EvalResult ExprResult; 15532 Expr::EvalStatus Status; 15533 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15534 Info.InConstantContext = true; 15535 15536 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15537 llvm_unreachable("ICE cannot be evaluated!"); 15538 15539 return ExprResult.Val.getInt(); 15540 } 15541 15542 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15543 assert(!isValueDependent() && 15544 "Expression evaluator can't be called on a dependent expression."); 15545 15546 return CheckICE(this, Ctx).Kind == IK_ICE; 15547 } 15548 15549 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15550 SourceLocation *Loc) const { 15551 assert(!isValueDependent() && 15552 "Expression evaluator can't be called on a dependent expression."); 15553 15554 // We support this checking in C++98 mode in order to diagnose compatibility 15555 // issues. 15556 assert(Ctx.getLangOpts().CPlusPlus); 15557 15558 // Build evaluation settings. 15559 Expr::EvalStatus Status; 15560 SmallVector<PartialDiagnosticAt, 8> Diags; 15561 Status.Diag = &Diags; 15562 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15563 15564 APValue Scratch; 15565 bool IsConstExpr = 15566 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15567 // FIXME: We don't produce a diagnostic for this, but the callers that 15568 // call us on arbitrary full-expressions should generally not care. 15569 Info.discardCleanups() && !Status.HasSideEffects; 15570 15571 if (!Diags.empty()) { 15572 IsConstExpr = false; 15573 if (Loc) *Loc = Diags[0].first; 15574 } else if (!IsConstExpr) { 15575 // FIXME: This shouldn't happen. 15576 if (Loc) *Loc = getExprLoc(); 15577 } 15578 15579 return IsConstExpr; 15580 } 15581 15582 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15583 const FunctionDecl *Callee, 15584 ArrayRef<const Expr*> Args, 15585 const Expr *This) const { 15586 assert(!isValueDependent() && 15587 "Expression evaluator can't be called on a dependent expression."); 15588 15589 Expr::EvalStatus Status; 15590 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15591 Info.InConstantContext = true; 15592 15593 LValue ThisVal; 15594 const LValue *ThisPtr = nullptr; 15595 if (This) { 15596 #ifndef NDEBUG 15597 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15598 assert(MD && "Don't provide `this` for non-methods."); 15599 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15600 #endif 15601 if (!This->isValueDependent() && 15602 EvaluateObjectArgument(Info, This, ThisVal) && 15603 !Info.EvalStatus.HasSideEffects) 15604 ThisPtr = &ThisVal; 15605 15606 // Ignore any side-effects from a failed evaluation. This is safe because 15607 // they can't interfere with any other argument evaluation. 15608 Info.EvalStatus.HasSideEffects = false; 15609 } 15610 15611 CallRef Call = Info.CurrentCall->createCall(Callee); 15612 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15613 I != E; ++I) { 15614 unsigned Idx = I - Args.begin(); 15615 if (Idx >= Callee->getNumParams()) 15616 break; 15617 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15618 if ((*I)->isValueDependent() || 15619 !EvaluateCallArg(PVD, *I, Call, Info) || 15620 Info.EvalStatus.HasSideEffects) { 15621 // If evaluation fails, throw away the argument entirely. 15622 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15623 *Slot = APValue(); 15624 } 15625 15626 // Ignore any side-effects from a failed evaluation. This is safe because 15627 // they can't interfere with any other argument evaluation. 15628 Info.EvalStatus.HasSideEffects = false; 15629 } 15630 15631 // Parameter cleanups happen in the caller and are not part of this 15632 // evaluation. 15633 Info.discardCleanups(); 15634 Info.EvalStatus.HasSideEffects = false; 15635 15636 // Build fake call to Callee. 15637 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15638 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15639 FullExpressionRAII Scope(Info); 15640 return Evaluate(Value, Info, this) && Scope.destroy() && 15641 !Info.EvalStatus.HasSideEffects; 15642 } 15643 15644 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15645 SmallVectorImpl< 15646 PartialDiagnosticAt> &Diags) { 15647 // FIXME: It would be useful to check constexpr function templates, but at the 15648 // moment the constant expression evaluator cannot cope with the non-rigorous 15649 // ASTs which we build for dependent expressions. 15650 if (FD->isDependentContext()) 15651 return true; 15652 15653 Expr::EvalStatus Status; 15654 Status.Diag = &Diags; 15655 15656 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15657 Info.InConstantContext = true; 15658 Info.CheckingPotentialConstantExpression = true; 15659 15660 // The constexpr VM attempts to compile all methods to bytecode here. 15661 if (Info.EnableNewConstInterp) { 15662 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15663 return Diags.empty(); 15664 } 15665 15666 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15667 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15668 15669 // Fabricate an arbitrary expression on the stack and pretend that it 15670 // is a temporary being used as the 'this' pointer. 15671 LValue This; 15672 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15673 This.set({&VIE, Info.CurrentCall->Index}); 15674 15675 ArrayRef<const Expr*> Args; 15676 15677 APValue Scratch; 15678 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15679 // Evaluate the call as a constant initializer, to allow the construction 15680 // of objects of non-literal types. 15681 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15682 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15683 } else { 15684 SourceLocation Loc = FD->getLocation(); 15685 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15686 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15687 } 15688 15689 return Diags.empty(); 15690 } 15691 15692 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15693 const FunctionDecl *FD, 15694 SmallVectorImpl< 15695 PartialDiagnosticAt> &Diags) { 15696 assert(!E->isValueDependent() && 15697 "Expression evaluator can't be called on a dependent expression."); 15698 15699 Expr::EvalStatus Status; 15700 Status.Diag = &Diags; 15701 15702 EvalInfo Info(FD->getASTContext(), Status, 15703 EvalInfo::EM_ConstantExpressionUnevaluated); 15704 Info.InConstantContext = true; 15705 Info.CheckingPotentialConstantExpression = true; 15706 15707 // Fabricate a call stack frame to give the arguments a plausible cover story. 15708 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15709 15710 APValue ResultScratch; 15711 Evaluate(ResultScratch, Info, E); 15712 return Diags.empty(); 15713 } 15714 15715 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15716 unsigned Type) const { 15717 if (!getType()->isPointerType()) 15718 return false; 15719 15720 Expr::EvalStatus Status; 15721 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15722 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15723 } 15724