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 bool CheckingForUndefinedBehavior = false; 930 931 enum EvaluationMode { 932 /// Evaluate as a constant expression. Stop if we find that the expression 933 /// is not a constant expression. 934 EM_ConstantExpression, 935 936 /// Evaluate as a constant expression. Stop if we find that the expression 937 /// is not a constant expression. Some expressions can be retried in the 938 /// optimizer if we don't constant fold them here, but in an unevaluated 939 /// context we try to fold them immediately since the optimizer never 940 /// gets a chance to look at it. 941 EM_ConstantExpressionUnevaluated, 942 943 /// Fold the expression to a constant. Stop if we hit a side-effect that 944 /// we can't model. 945 EM_ConstantFold, 946 947 /// Evaluate in any way we know how. Don't worry about side-effects that 948 /// can't be modeled. 949 EM_IgnoreSideEffects, 950 } EvalMode; 951 952 /// Are we checking whether the expression is a potential constant 953 /// expression? 954 bool checkingPotentialConstantExpression() const override { 955 return CheckingPotentialConstantExpression; 956 } 957 958 /// Are we checking an expression for overflow? 959 // FIXME: We should check for any kind of undefined or suspicious behavior 960 // in such constructs, not just overflow. 961 bool checkingForUndefinedBehavior() const override { 962 return CheckingForUndefinedBehavior; 963 } 964 965 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 966 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 967 CallStackDepth(0), NextCallIndex(1), 968 StepsLeft(C.getLangOpts().ConstexprStepLimit), 969 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 970 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 971 EvaluatingDecl((const ValueDecl *)nullptr), 972 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 973 HasFoldFailureDiagnostic(false), InConstantContext(false), 974 EvalMode(Mode) {} 975 976 ~EvalInfo() { 977 discardCleanups(); 978 } 979 980 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 981 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 982 EvaluatingDecl = Base; 983 IsEvaluatingDecl = EDK; 984 EvaluatingDeclValue = &Value; 985 } 986 987 bool CheckCallLimit(SourceLocation Loc) { 988 // Don't perform any constexpr calls (other than the call we're checking) 989 // when checking a potential constant expression. 990 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 991 return false; 992 if (NextCallIndex == 0) { 993 // NextCallIndex has wrapped around. 994 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 995 return false; 996 } 997 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 998 return true; 999 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1000 << getLangOpts().ConstexprCallDepth; 1001 return false; 1002 } 1003 1004 std::pair<CallStackFrame *, unsigned> 1005 getCallFrameAndDepth(unsigned CallIndex) { 1006 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1007 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1008 // be null in this loop. 1009 unsigned Depth = CallStackDepth; 1010 CallStackFrame *Frame = CurrentCall; 1011 while (Frame->Index > CallIndex) { 1012 Frame = Frame->Caller; 1013 --Depth; 1014 } 1015 if (Frame->Index == CallIndex) 1016 return {Frame, Depth}; 1017 return {nullptr, 0}; 1018 } 1019 1020 bool nextStep(const Stmt *S) { 1021 if (!StepsLeft) { 1022 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1023 return false; 1024 } 1025 --StepsLeft; 1026 return true; 1027 } 1028 1029 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1030 1031 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1032 Optional<DynAlloc*> Result; 1033 auto It = HeapAllocs.find(DA); 1034 if (It != HeapAllocs.end()) 1035 Result = &It->second; 1036 return Result; 1037 } 1038 1039 /// Get the allocated storage for the given parameter of the given call. 1040 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1041 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1042 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1043 : nullptr; 1044 } 1045 1046 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1047 struct StdAllocatorCaller { 1048 unsigned FrameIndex; 1049 QualType ElemType; 1050 explicit operator bool() const { return FrameIndex != 0; }; 1051 }; 1052 1053 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1054 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1055 Call = Call->Caller) { 1056 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1057 if (!MD) 1058 continue; 1059 const IdentifierInfo *FnII = MD->getIdentifier(); 1060 if (!FnII || !FnII->isStr(FnName)) 1061 continue; 1062 1063 const auto *CTSD = 1064 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1065 if (!CTSD) 1066 continue; 1067 1068 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1069 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1070 if (CTSD->isInStdNamespace() && ClassII && 1071 ClassII->isStr("allocator") && TAL.size() >= 1 && 1072 TAL[0].getKind() == TemplateArgument::Type) 1073 return {Call->Index, TAL[0].getAsType()}; 1074 } 1075 1076 return {}; 1077 } 1078 1079 void performLifetimeExtension() { 1080 // Disable the cleanups for lifetime-extended temporaries. 1081 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1082 CleanupStack.end(), 1083 [](Cleanup &C) { 1084 return !C.isDestroyedAtEndOf( 1085 ScopeKind::FullExpression); 1086 }), 1087 CleanupStack.end()); 1088 } 1089 1090 /// Throw away any remaining cleanups at the end of evaluation. If any 1091 /// cleanups would have had a side-effect, note that as an unmodeled 1092 /// side-effect and return false. Otherwise, return true. 1093 bool discardCleanups() { 1094 for (Cleanup &C : CleanupStack) { 1095 if (C.hasSideEffect() && !noteSideEffect()) { 1096 CleanupStack.clear(); 1097 return false; 1098 } 1099 } 1100 CleanupStack.clear(); 1101 return true; 1102 } 1103 1104 private: 1105 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1106 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1107 1108 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1109 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1110 1111 void setFoldFailureDiagnostic(bool Flag) override { 1112 HasFoldFailureDiagnostic = Flag; 1113 } 1114 1115 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1116 1117 ASTContext &getCtx() const override { return Ctx; } 1118 1119 // If we have a prior diagnostic, it will be noting that the expression 1120 // isn't a constant expression. This diagnostic is more important, 1121 // unless we require this evaluation to produce a constant expression. 1122 // 1123 // FIXME: We might want to show both diagnostics to the user in 1124 // EM_ConstantFold mode. 1125 bool hasPriorDiagnostic() override { 1126 if (!EvalStatus.Diag->empty()) { 1127 switch (EvalMode) { 1128 case EM_ConstantFold: 1129 case EM_IgnoreSideEffects: 1130 if (!HasFoldFailureDiagnostic) 1131 break; 1132 // We've already failed to fold something. Keep that diagnostic. 1133 LLVM_FALLTHROUGH; 1134 case EM_ConstantExpression: 1135 case EM_ConstantExpressionUnevaluated: 1136 setActiveDiagnostic(false); 1137 return true; 1138 } 1139 } 1140 return false; 1141 } 1142 1143 unsigned getCallStackDepth() override { return CallStackDepth; } 1144 1145 public: 1146 /// Should we continue evaluation after encountering a side-effect that we 1147 /// couldn't model? 1148 bool keepEvaluatingAfterSideEffect() { 1149 switch (EvalMode) { 1150 case EM_IgnoreSideEffects: 1151 return true; 1152 1153 case EM_ConstantExpression: 1154 case EM_ConstantExpressionUnevaluated: 1155 case EM_ConstantFold: 1156 // By default, assume any side effect might be valid in some other 1157 // evaluation of this expression from a different context. 1158 return checkingPotentialConstantExpression() || 1159 checkingForUndefinedBehavior(); 1160 } 1161 llvm_unreachable("Missed EvalMode case"); 1162 } 1163 1164 /// Note that we have had a side-effect, and determine whether we should 1165 /// keep evaluating. 1166 bool noteSideEffect() { 1167 EvalStatus.HasSideEffects = true; 1168 return keepEvaluatingAfterSideEffect(); 1169 } 1170 1171 /// Should we continue evaluation after encountering undefined behavior? 1172 bool keepEvaluatingAfterUndefinedBehavior() { 1173 switch (EvalMode) { 1174 case EM_IgnoreSideEffects: 1175 case EM_ConstantFold: 1176 return true; 1177 1178 case EM_ConstantExpression: 1179 case EM_ConstantExpressionUnevaluated: 1180 return checkingForUndefinedBehavior(); 1181 } 1182 llvm_unreachable("Missed EvalMode case"); 1183 } 1184 1185 /// Note that we hit something that was technically undefined behavior, but 1186 /// that we can evaluate past it (such as signed overflow or floating-point 1187 /// division by zero.) 1188 bool noteUndefinedBehavior() override { 1189 EvalStatus.HasUndefinedBehavior = true; 1190 return keepEvaluatingAfterUndefinedBehavior(); 1191 } 1192 1193 /// Should we continue evaluation as much as possible after encountering a 1194 /// construct which can't be reduced to a value? 1195 bool keepEvaluatingAfterFailure() const override { 1196 if (!StepsLeft) 1197 return false; 1198 1199 switch (EvalMode) { 1200 case EM_ConstantExpression: 1201 case EM_ConstantExpressionUnevaluated: 1202 case EM_ConstantFold: 1203 case EM_IgnoreSideEffects: 1204 return checkingPotentialConstantExpression() || 1205 checkingForUndefinedBehavior(); 1206 } 1207 llvm_unreachable("Missed EvalMode case"); 1208 } 1209 1210 /// Notes that we failed to evaluate an expression that other expressions 1211 /// directly depend on, and determine if we should keep evaluating. This 1212 /// should only be called if we actually intend to keep evaluating. 1213 /// 1214 /// Call noteSideEffect() instead if we may be able to ignore the value that 1215 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1216 /// 1217 /// (Foo(), 1) // use noteSideEffect 1218 /// (Foo() || true) // use noteSideEffect 1219 /// Foo() + 1 // use noteFailure 1220 LLVM_NODISCARD bool noteFailure() { 1221 // Failure when evaluating some expression often means there is some 1222 // subexpression whose evaluation was skipped. Therefore, (because we 1223 // don't track whether we skipped an expression when unwinding after an 1224 // evaluation failure) every evaluation failure that bubbles up from a 1225 // subexpression implies that a side-effect has potentially happened. We 1226 // skip setting the HasSideEffects flag to true until we decide to 1227 // continue evaluating after that point, which happens here. 1228 bool KeepGoing = keepEvaluatingAfterFailure(); 1229 EvalStatus.HasSideEffects |= KeepGoing; 1230 return KeepGoing; 1231 } 1232 1233 class ArrayInitLoopIndex { 1234 EvalInfo &Info; 1235 uint64_t OuterIndex; 1236 1237 public: 1238 ArrayInitLoopIndex(EvalInfo &Info) 1239 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1240 Info.ArrayInitIndex = 0; 1241 } 1242 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1243 1244 operator uint64_t&() { return Info.ArrayInitIndex; } 1245 }; 1246 }; 1247 1248 /// Object used to treat all foldable expressions as constant expressions. 1249 struct FoldConstant { 1250 EvalInfo &Info; 1251 bool Enabled; 1252 bool HadNoPriorDiags; 1253 EvalInfo::EvaluationMode OldMode; 1254 1255 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1256 : Info(Info), 1257 Enabled(Enabled), 1258 HadNoPriorDiags(Info.EvalStatus.Diag && 1259 Info.EvalStatus.Diag->empty() && 1260 !Info.EvalStatus.HasSideEffects), 1261 OldMode(Info.EvalMode) { 1262 if (Enabled) 1263 Info.EvalMode = EvalInfo::EM_ConstantFold; 1264 } 1265 void keepDiagnostics() { Enabled = false; } 1266 ~FoldConstant() { 1267 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1268 !Info.EvalStatus.HasSideEffects) 1269 Info.EvalStatus.Diag->clear(); 1270 Info.EvalMode = OldMode; 1271 } 1272 }; 1273 1274 /// RAII object used to set the current evaluation mode to ignore 1275 /// side-effects. 1276 struct IgnoreSideEffectsRAII { 1277 EvalInfo &Info; 1278 EvalInfo::EvaluationMode OldMode; 1279 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1280 : Info(Info), OldMode(Info.EvalMode) { 1281 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1282 } 1283 1284 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1285 }; 1286 1287 /// RAII object used to optionally suppress diagnostics and side-effects from 1288 /// a speculative evaluation. 1289 class SpeculativeEvaluationRAII { 1290 EvalInfo *Info = nullptr; 1291 Expr::EvalStatus OldStatus; 1292 unsigned OldSpeculativeEvaluationDepth; 1293 1294 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1295 Info = Other.Info; 1296 OldStatus = Other.OldStatus; 1297 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1298 Other.Info = nullptr; 1299 } 1300 1301 void maybeRestoreState() { 1302 if (!Info) 1303 return; 1304 1305 Info->EvalStatus = OldStatus; 1306 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1307 } 1308 1309 public: 1310 SpeculativeEvaluationRAII() = default; 1311 1312 SpeculativeEvaluationRAII( 1313 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1314 : Info(&Info), OldStatus(Info.EvalStatus), 1315 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1316 Info.EvalStatus.Diag = NewDiag; 1317 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1318 } 1319 1320 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1321 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1322 moveFromAndCancel(std::move(Other)); 1323 } 1324 1325 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1326 maybeRestoreState(); 1327 moveFromAndCancel(std::move(Other)); 1328 return *this; 1329 } 1330 1331 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1332 }; 1333 1334 /// RAII object wrapping a full-expression or block scope, and handling 1335 /// the ending of the lifetime of temporaries created within it. 1336 template<ScopeKind Kind> 1337 class ScopeRAII { 1338 EvalInfo &Info; 1339 unsigned OldStackSize; 1340 public: 1341 ScopeRAII(EvalInfo &Info) 1342 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1343 // Push a new temporary version. This is needed to distinguish between 1344 // temporaries created in different iterations of a loop. 1345 Info.CurrentCall->pushTempVersion(); 1346 } 1347 bool destroy(bool RunDestructors = true) { 1348 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1349 OldStackSize = -1U; 1350 return OK; 1351 } 1352 ~ScopeRAII() { 1353 if (OldStackSize != -1U) 1354 destroy(false); 1355 // Body moved to a static method to encourage the compiler to inline away 1356 // instances of this class. 1357 Info.CurrentCall->popTempVersion(); 1358 } 1359 private: 1360 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1361 unsigned OldStackSize) { 1362 assert(OldStackSize <= Info.CleanupStack.size() && 1363 "running cleanups out of order?"); 1364 1365 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1366 // for a full-expression scope. 1367 bool Success = true; 1368 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1369 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1370 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1371 Success = false; 1372 break; 1373 } 1374 } 1375 } 1376 1377 // Compact any retained cleanups. 1378 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1379 if (Kind != ScopeKind::Block) 1380 NewEnd = 1381 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1382 return C.isDestroyedAtEndOf(Kind); 1383 }); 1384 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1385 return Success; 1386 } 1387 }; 1388 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1389 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1390 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1391 } 1392 1393 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1394 CheckSubobjectKind CSK) { 1395 if (Invalid) 1396 return false; 1397 if (isOnePastTheEnd()) { 1398 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1399 << CSK; 1400 setInvalid(); 1401 return false; 1402 } 1403 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1404 // must actually be at least one array element; even a VLA cannot have a 1405 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1406 return true; 1407 } 1408 1409 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1410 const Expr *E) { 1411 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1412 // Do not set the designator as invalid: we can represent this situation, 1413 // and correct handling of __builtin_object_size requires us to do so. 1414 } 1415 1416 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1417 const Expr *E, 1418 const APSInt &N) { 1419 // If we're complaining, we must be able to statically determine the size of 1420 // the most derived array. 1421 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1422 Info.CCEDiag(E, diag::note_constexpr_array_index) 1423 << N << /*array*/ 0 1424 << static_cast<unsigned>(getMostDerivedArraySize()); 1425 else 1426 Info.CCEDiag(E, diag::note_constexpr_array_index) 1427 << N << /*non-array*/ 1; 1428 setInvalid(); 1429 } 1430 1431 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1432 const FunctionDecl *Callee, const LValue *This, 1433 CallRef Call) 1434 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1435 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1436 Info.CurrentCall = this; 1437 ++Info.CallStackDepth; 1438 } 1439 1440 CallStackFrame::~CallStackFrame() { 1441 assert(Info.CurrentCall == this && "calls retired out of order"); 1442 --Info.CallStackDepth; 1443 Info.CurrentCall = Caller; 1444 } 1445 1446 static bool isRead(AccessKinds AK) { 1447 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1448 } 1449 1450 static bool isModification(AccessKinds AK) { 1451 switch (AK) { 1452 case AK_Read: 1453 case AK_ReadObjectRepresentation: 1454 case AK_MemberCall: 1455 case AK_DynamicCast: 1456 case AK_TypeId: 1457 return false; 1458 case AK_Assign: 1459 case AK_Increment: 1460 case AK_Decrement: 1461 case AK_Construct: 1462 case AK_Destroy: 1463 return true; 1464 } 1465 llvm_unreachable("unknown access kind"); 1466 } 1467 1468 static bool isAnyAccess(AccessKinds AK) { 1469 return isRead(AK) || isModification(AK); 1470 } 1471 1472 /// Is this an access per the C++ definition? 1473 static bool isFormalAccess(AccessKinds AK) { 1474 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1475 } 1476 1477 /// Is this kind of axcess valid on an indeterminate object value? 1478 static bool isValidIndeterminateAccess(AccessKinds AK) { 1479 switch (AK) { 1480 case AK_Read: 1481 case AK_Increment: 1482 case AK_Decrement: 1483 // These need the object's value. 1484 return false; 1485 1486 case AK_ReadObjectRepresentation: 1487 case AK_Assign: 1488 case AK_Construct: 1489 case AK_Destroy: 1490 // Construction and destruction don't need the value. 1491 return true; 1492 1493 case AK_MemberCall: 1494 case AK_DynamicCast: 1495 case AK_TypeId: 1496 // These aren't really meaningful on scalars. 1497 return true; 1498 } 1499 llvm_unreachable("unknown access kind"); 1500 } 1501 1502 namespace { 1503 struct ComplexValue { 1504 private: 1505 bool IsInt; 1506 1507 public: 1508 APSInt IntReal, IntImag; 1509 APFloat FloatReal, FloatImag; 1510 1511 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1512 1513 void makeComplexFloat() { IsInt = false; } 1514 bool isComplexFloat() const { return !IsInt; } 1515 APFloat &getComplexFloatReal() { return FloatReal; } 1516 APFloat &getComplexFloatImag() { return FloatImag; } 1517 1518 void makeComplexInt() { IsInt = true; } 1519 bool isComplexInt() const { return IsInt; } 1520 APSInt &getComplexIntReal() { return IntReal; } 1521 APSInt &getComplexIntImag() { return IntImag; } 1522 1523 void moveInto(APValue &v) const { 1524 if (isComplexFloat()) 1525 v = APValue(FloatReal, FloatImag); 1526 else 1527 v = APValue(IntReal, IntImag); 1528 } 1529 void setFrom(const APValue &v) { 1530 assert(v.isComplexFloat() || v.isComplexInt()); 1531 if (v.isComplexFloat()) { 1532 makeComplexFloat(); 1533 FloatReal = v.getComplexFloatReal(); 1534 FloatImag = v.getComplexFloatImag(); 1535 } else { 1536 makeComplexInt(); 1537 IntReal = v.getComplexIntReal(); 1538 IntImag = v.getComplexIntImag(); 1539 } 1540 } 1541 }; 1542 1543 struct LValue { 1544 APValue::LValueBase Base; 1545 CharUnits Offset; 1546 SubobjectDesignator Designator; 1547 bool IsNullPtr : 1; 1548 bool InvalidBase : 1; 1549 1550 const APValue::LValueBase getLValueBase() const { return Base; } 1551 CharUnits &getLValueOffset() { return Offset; } 1552 const CharUnits &getLValueOffset() const { return Offset; } 1553 SubobjectDesignator &getLValueDesignator() { return Designator; } 1554 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1555 bool isNullPointer() const { return IsNullPtr;} 1556 1557 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1558 unsigned getLValueVersion() const { return Base.getVersion(); } 1559 1560 void moveInto(APValue &V) const { 1561 if (Designator.Invalid) 1562 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1563 else { 1564 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1565 V = APValue(Base, Offset, Designator.Entries, 1566 Designator.IsOnePastTheEnd, IsNullPtr); 1567 } 1568 } 1569 void setFrom(ASTContext &Ctx, const APValue &V) { 1570 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1571 Base = V.getLValueBase(); 1572 Offset = V.getLValueOffset(); 1573 InvalidBase = false; 1574 Designator = SubobjectDesignator(Ctx, V); 1575 IsNullPtr = V.isNullPointer(); 1576 } 1577 1578 void set(APValue::LValueBase B, bool BInvalid = false) { 1579 #ifndef NDEBUG 1580 // We only allow a few types of invalid bases. Enforce that here. 1581 if (BInvalid) { 1582 const auto *E = B.get<const Expr *>(); 1583 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1584 "Unexpected type of invalid base"); 1585 } 1586 #endif 1587 1588 Base = B; 1589 Offset = CharUnits::fromQuantity(0); 1590 InvalidBase = BInvalid; 1591 Designator = SubobjectDesignator(getType(B)); 1592 IsNullPtr = false; 1593 } 1594 1595 void setNull(ASTContext &Ctx, QualType PointerTy) { 1596 Base = (const ValueDecl *)nullptr; 1597 Offset = 1598 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1599 InvalidBase = false; 1600 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1601 IsNullPtr = true; 1602 } 1603 1604 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1605 set(B, true); 1606 } 1607 1608 std::string toString(ASTContext &Ctx, QualType T) const { 1609 APValue Printable; 1610 moveInto(Printable); 1611 return Printable.getAsString(Ctx, T); 1612 } 1613 1614 private: 1615 // Check that this LValue is not based on a null pointer. If it is, produce 1616 // a diagnostic and mark the designator as invalid. 1617 template <typename GenDiagType> 1618 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1619 if (Designator.Invalid) 1620 return false; 1621 if (IsNullPtr) { 1622 GenDiag(); 1623 Designator.setInvalid(); 1624 return false; 1625 } 1626 return true; 1627 } 1628 1629 public: 1630 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1631 CheckSubobjectKind CSK) { 1632 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1633 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1634 }); 1635 } 1636 1637 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1638 AccessKinds AK) { 1639 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1640 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1641 }); 1642 } 1643 1644 // Check this LValue refers to an object. If not, set the designator to be 1645 // invalid and emit a diagnostic. 1646 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1647 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1648 Designator.checkSubobject(Info, E, CSK); 1649 } 1650 1651 void addDecl(EvalInfo &Info, const Expr *E, 1652 const Decl *D, bool Virtual = false) { 1653 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1654 Designator.addDeclUnchecked(D, Virtual); 1655 } 1656 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1657 if (!Designator.Entries.empty()) { 1658 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1659 Designator.setInvalid(); 1660 return; 1661 } 1662 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1663 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1664 Designator.FirstEntryIsAnUnsizedArray = true; 1665 Designator.addUnsizedArrayUnchecked(ElemTy); 1666 } 1667 } 1668 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1669 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1670 Designator.addArrayUnchecked(CAT); 1671 } 1672 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1673 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1674 Designator.addComplexUnchecked(EltTy, Imag); 1675 } 1676 void clearIsNullPointer() { 1677 IsNullPtr = false; 1678 } 1679 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1680 const APSInt &Index, CharUnits ElementSize) { 1681 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1682 // but we're not required to diagnose it and it's valid in C++.) 1683 if (!Index) 1684 return; 1685 1686 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1687 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1688 // offsets. 1689 uint64_t Offset64 = Offset.getQuantity(); 1690 uint64_t ElemSize64 = ElementSize.getQuantity(); 1691 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1692 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1693 1694 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1695 Designator.adjustIndex(Info, E, Index); 1696 clearIsNullPointer(); 1697 } 1698 void adjustOffset(CharUnits N) { 1699 Offset += N; 1700 if (N.getQuantity()) 1701 clearIsNullPointer(); 1702 } 1703 }; 1704 1705 struct MemberPtr { 1706 MemberPtr() {} 1707 explicit MemberPtr(const ValueDecl *Decl) : 1708 DeclAndIsDerivedMember(Decl, false), Path() {} 1709 1710 /// The member or (direct or indirect) field referred to by this member 1711 /// pointer, or 0 if this is a null member pointer. 1712 const ValueDecl *getDecl() const { 1713 return DeclAndIsDerivedMember.getPointer(); 1714 } 1715 /// Is this actually a member of some type derived from the relevant class? 1716 bool isDerivedMember() const { 1717 return DeclAndIsDerivedMember.getInt(); 1718 } 1719 /// Get the class which the declaration actually lives in. 1720 const CXXRecordDecl *getContainingRecord() const { 1721 return cast<CXXRecordDecl>( 1722 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1723 } 1724 1725 void moveInto(APValue &V) const { 1726 V = APValue(getDecl(), isDerivedMember(), Path); 1727 } 1728 void setFrom(const APValue &V) { 1729 assert(V.isMemberPointer()); 1730 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1731 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1732 Path.clear(); 1733 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1734 Path.insert(Path.end(), P.begin(), P.end()); 1735 } 1736 1737 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1738 /// whether the member is a member of some class derived from the class type 1739 /// of the member pointer. 1740 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1741 /// Path - The path of base/derived classes from the member declaration's 1742 /// class (exclusive) to the class type of the member pointer (inclusive). 1743 SmallVector<const CXXRecordDecl*, 4> Path; 1744 1745 /// Perform a cast towards the class of the Decl (either up or down the 1746 /// hierarchy). 1747 bool castBack(const CXXRecordDecl *Class) { 1748 assert(!Path.empty()); 1749 const CXXRecordDecl *Expected; 1750 if (Path.size() >= 2) 1751 Expected = Path[Path.size() - 2]; 1752 else 1753 Expected = getContainingRecord(); 1754 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1755 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1756 // if B does not contain the original member and is not a base or 1757 // derived class of the class containing the original member, the result 1758 // of the cast is undefined. 1759 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1760 // (D::*). We consider that to be a language defect. 1761 return false; 1762 } 1763 Path.pop_back(); 1764 return true; 1765 } 1766 /// Perform a base-to-derived member pointer cast. 1767 bool castToDerived(const CXXRecordDecl *Derived) { 1768 if (!getDecl()) 1769 return true; 1770 if (!isDerivedMember()) { 1771 Path.push_back(Derived); 1772 return true; 1773 } 1774 if (!castBack(Derived)) 1775 return false; 1776 if (Path.empty()) 1777 DeclAndIsDerivedMember.setInt(false); 1778 return true; 1779 } 1780 /// Perform a derived-to-base member pointer cast. 1781 bool castToBase(const CXXRecordDecl *Base) { 1782 if (!getDecl()) 1783 return true; 1784 if (Path.empty()) 1785 DeclAndIsDerivedMember.setInt(true); 1786 if (isDerivedMember()) { 1787 Path.push_back(Base); 1788 return true; 1789 } 1790 return castBack(Base); 1791 } 1792 }; 1793 1794 /// Compare two member pointers, which are assumed to be of the same type. 1795 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1796 if (!LHS.getDecl() || !RHS.getDecl()) 1797 return !LHS.getDecl() && !RHS.getDecl(); 1798 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1799 return false; 1800 return LHS.Path == RHS.Path; 1801 } 1802 } 1803 1804 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1805 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1806 const LValue &This, const Expr *E, 1807 bool AllowNonLiteralTypes = false); 1808 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1809 bool InvalidBaseOK = false); 1810 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1811 bool InvalidBaseOK = false); 1812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1813 EvalInfo &Info); 1814 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1815 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1816 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1817 EvalInfo &Info); 1818 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1819 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1820 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1821 EvalInfo &Info); 1822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1823 1824 /// Evaluate an integer or fixed point expression into an APResult. 1825 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1826 EvalInfo &Info); 1827 1828 /// Evaluate only a fixed point expression into an APResult. 1829 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1830 EvalInfo &Info); 1831 1832 //===----------------------------------------------------------------------===// 1833 // Misc utilities 1834 //===----------------------------------------------------------------------===// 1835 1836 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1837 /// preserving its value (by extending by up to one bit as needed). 1838 static void negateAsSigned(APSInt &Int) { 1839 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1840 Int = Int.extend(Int.getBitWidth() + 1); 1841 Int.setIsSigned(true); 1842 } 1843 Int = -Int; 1844 } 1845 1846 template<typename KeyT> 1847 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1848 ScopeKind Scope, LValue &LV) { 1849 unsigned Version = getTempVersion(); 1850 APValue::LValueBase Base(Key, Index, Version); 1851 LV.set(Base); 1852 return createLocal(Base, Key, T, Scope); 1853 } 1854 1855 /// Allocate storage for a parameter of a function call made in this frame. 1856 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1857 LValue &LV) { 1858 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1859 APValue::LValueBase Base(PVD, Index, Args.Version); 1860 LV.set(Base); 1861 // We always destroy parameters at the end of the call, even if we'd allow 1862 // them to live to the end of the full-expression at runtime, in order to 1863 // give portable results and match other compilers. 1864 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1865 } 1866 1867 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1868 QualType T, ScopeKind Scope) { 1869 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1870 unsigned Version = Base.getVersion(); 1871 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1872 assert(Result.isAbsent() && "local created multiple times"); 1873 1874 // If we're creating a local immediately in the operand of a speculative 1875 // evaluation, don't register a cleanup to be run outside the speculative 1876 // evaluation context, since we won't actually be able to initialize this 1877 // object. 1878 if (Index <= Info.SpeculativeEvaluationDepth) { 1879 if (T.isDestructedType()) 1880 Info.noteSideEffect(); 1881 } else { 1882 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1883 } 1884 return Result; 1885 } 1886 1887 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1888 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1889 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1890 return nullptr; 1891 } 1892 1893 DynamicAllocLValue DA(NumHeapAllocs++); 1894 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1895 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1896 std::forward_as_tuple(DA), std::tuple<>()); 1897 assert(Result.second && "reused a heap alloc index?"); 1898 Result.first->second.AllocExpr = E; 1899 return &Result.first->second.Value; 1900 } 1901 1902 /// Produce a string describing the given constexpr call. 1903 void CallStackFrame::describe(raw_ostream &Out) { 1904 unsigned ArgIndex = 0; 1905 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1906 !isa<CXXConstructorDecl>(Callee) && 1907 cast<CXXMethodDecl>(Callee)->isInstance(); 1908 1909 if (!IsMemberCall) 1910 Out << *Callee << '('; 1911 1912 if (This && IsMemberCall) { 1913 APValue Val; 1914 This->moveInto(Val); 1915 Val.printPretty(Out, Info.Ctx, 1916 This->Designator.MostDerivedType); 1917 // FIXME: Add parens around Val if needed. 1918 Out << "->" << *Callee << '('; 1919 IsMemberCall = false; 1920 } 1921 1922 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1923 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1924 if (ArgIndex > (unsigned)IsMemberCall) 1925 Out << ", "; 1926 1927 const ParmVarDecl *Param = *I; 1928 APValue *V = Info.getParamSlot(Arguments, Param); 1929 if (V) 1930 V->printPretty(Out, Info.Ctx, Param->getType()); 1931 else 1932 Out << "<...>"; 1933 1934 if (ArgIndex == 0 && IsMemberCall) 1935 Out << "->" << *Callee << '('; 1936 } 1937 1938 Out << ')'; 1939 } 1940 1941 /// Evaluate an expression to see if it had side-effects, and discard its 1942 /// result. 1943 /// \return \c true if the caller should keep evaluating. 1944 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1945 assert(!E->isValueDependent()); 1946 APValue Scratch; 1947 if (!Evaluate(Scratch, Info, E)) 1948 // We don't need the value, but we might have skipped a side effect here. 1949 return Info.noteSideEffect(); 1950 return true; 1951 } 1952 1953 /// Should this call expression be treated as a string literal? 1954 static bool IsStringLiteralCall(const CallExpr *E) { 1955 unsigned Builtin = E->getBuiltinCallee(); 1956 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1957 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1958 } 1959 1960 static bool IsGlobalLValue(APValue::LValueBase B) { 1961 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1962 // constant expression of pointer type that evaluates to... 1963 1964 // ... a null pointer value, or a prvalue core constant expression of type 1965 // std::nullptr_t. 1966 if (!B) return true; 1967 1968 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1969 // ... the address of an object with static storage duration, 1970 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1971 return VD->hasGlobalStorage(); 1972 if (isa<TemplateParamObjectDecl>(D)) 1973 return true; 1974 // ... the address of a function, 1975 // ... the address of a GUID [MS extension], 1976 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1977 } 1978 1979 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1980 return true; 1981 1982 const Expr *E = B.get<const Expr*>(); 1983 switch (E->getStmtClass()) { 1984 default: 1985 return false; 1986 case Expr::CompoundLiteralExprClass: { 1987 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1988 return CLE->isFileScope() && CLE->isLValue(); 1989 } 1990 case Expr::MaterializeTemporaryExprClass: 1991 // A materialized temporary might have been lifetime-extended to static 1992 // storage duration. 1993 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1994 // A string literal has static storage duration. 1995 case Expr::StringLiteralClass: 1996 case Expr::PredefinedExprClass: 1997 case Expr::ObjCStringLiteralClass: 1998 case Expr::ObjCEncodeExprClass: 1999 return true; 2000 case Expr::ObjCBoxedExprClass: 2001 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2002 case Expr::CallExprClass: 2003 return IsStringLiteralCall(cast<CallExpr>(E)); 2004 // For GCC compatibility, &&label has static storage duration. 2005 case Expr::AddrLabelExprClass: 2006 return true; 2007 // A Block literal expression may be used as the initialization value for 2008 // Block variables at global or local static scope. 2009 case Expr::BlockExprClass: 2010 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2011 case Expr::ImplicitValueInitExprClass: 2012 // FIXME: 2013 // We can never form an lvalue with an implicit value initialization as its 2014 // base through expression evaluation, so these only appear in one case: the 2015 // implicit variable declaration we invent when checking whether a constexpr 2016 // constructor can produce a constant expression. We must assume that such 2017 // an expression might be a global lvalue. 2018 return true; 2019 } 2020 } 2021 2022 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2023 return LVal.Base.dyn_cast<const ValueDecl*>(); 2024 } 2025 2026 static bool IsLiteralLValue(const LValue &Value) { 2027 if (Value.getLValueCallIndex()) 2028 return false; 2029 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2030 return E && !isa<MaterializeTemporaryExpr>(E); 2031 } 2032 2033 static bool IsWeakLValue(const LValue &Value) { 2034 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2035 return Decl && Decl->isWeak(); 2036 } 2037 2038 static bool isZeroSized(const LValue &Value) { 2039 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2040 if (Decl && isa<VarDecl>(Decl)) { 2041 QualType Ty = Decl->getType(); 2042 if (Ty->isArrayType()) 2043 return Ty->isIncompleteType() || 2044 Decl->getASTContext().getTypeSize(Ty) == 0; 2045 } 2046 return false; 2047 } 2048 2049 static bool HasSameBase(const LValue &A, const LValue &B) { 2050 if (!A.getLValueBase()) 2051 return !B.getLValueBase(); 2052 if (!B.getLValueBase()) 2053 return false; 2054 2055 if (A.getLValueBase().getOpaqueValue() != 2056 B.getLValueBase().getOpaqueValue()) 2057 return false; 2058 2059 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2060 A.getLValueVersion() == B.getLValueVersion(); 2061 } 2062 2063 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2064 assert(Base && "no location for a null lvalue"); 2065 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2066 2067 // For a parameter, find the corresponding call stack frame (if it still 2068 // exists), and point at the parameter of the function definition we actually 2069 // invoked. 2070 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2071 unsigned Idx = PVD->getFunctionScopeIndex(); 2072 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2073 if (F->Arguments.CallIndex == Base.getCallIndex() && 2074 F->Arguments.Version == Base.getVersion() && F->Callee && 2075 Idx < F->Callee->getNumParams()) { 2076 VD = F->Callee->getParamDecl(Idx); 2077 break; 2078 } 2079 } 2080 } 2081 2082 if (VD) 2083 Info.Note(VD->getLocation(), diag::note_declared_at); 2084 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2085 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2086 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2087 // FIXME: Produce a note for dangling pointers too. 2088 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2089 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2090 diag::note_constexpr_dynamic_alloc_here); 2091 } 2092 // We have no information to show for a typeid(T) object. 2093 } 2094 2095 enum class CheckEvaluationResultKind { 2096 ConstantExpression, 2097 FullyInitialized, 2098 }; 2099 2100 /// Materialized temporaries that we've already checked to determine if they're 2101 /// initializsed by a constant expression. 2102 using CheckedTemporaries = 2103 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2104 2105 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2106 EvalInfo &Info, SourceLocation DiagLoc, 2107 QualType Type, const APValue &Value, 2108 ConstantExprKind Kind, 2109 SourceLocation SubobjectLoc, 2110 CheckedTemporaries &CheckedTemps); 2111 2112 /// Check that this reference or pointer core constant expression is a valid 2113 /// value for an address or reference constant expression. Return true if we 2114 /// can fold this expression, whether or not it's a constant expression. 2115 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2116 QualType Type, const LValue &LVal, 2117 ConstantExprKind Kind, 2118 CheckedTemporaries &CheckedTemps) { 2119 bool IsReferenceType = Type->isReferenceType(); 2120 2121 APValue::LValueBase Base = LVal.getLValueBase(); 2122 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2123 2124 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2125 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2126 2127 // Additional restrictions apply in a template argument. We only enforce the 2128 // C++20 restrictions here; additional syntactic and semantic restrictions 2129 // are applied elsewhere. 2130 if (isTemplateArgument(Kind)) { 2131 int InvalidBaseKind = -1; 2132 StringRef Ident; 2133 if (Base.is<TypeInfoLValue>()) 2134 InvalidBaseKind = 0; 2135 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2136 InvalidBaseKind = 1; 2137 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2138 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2139 InvalidBaseKind = 2; 2140 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2141 InvalidBaseKind = 3; 2142 Ident = PE->getIdentKindName(); 2143 } 2144 2145 if (InvalidBaseKind != -1) { 2146 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2147 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2148 << Ident; 2149 return false; 2150 } 2151 } 2152 2153 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2154 if (FD->isConsteval()) { 2155 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2156 << !Type->isAnyPointerType(); 2157 Info.Note(FD->getLocation(), diag::note_declared_at); 2158 return false; 2159 } 2160 } 2161 2162 // Check that the object is a global. Note that the fake 'this' object we 2163 // manufacture when checking potential constant expressions is conservatively 2164 // assumed to be global here. 2165 if (!IsGlobalLValue(Base)) { 2166 if (Info.getLangOpts().CPlusPlus11) { 2167 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2168 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2169 << IsReferenceType << !Designator.Entries.empty() 2170 << !!VD << VD; 2171 2172 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2173 if (VarD && VarD->isConstexpr()) { 2174 // Non-static local constexpr variables have unintuitive semantics: 2175 // constexpr int a = 1; 2176 // constexpr const int *p = &a; 2177 // ... is invalid because the address of 'a' is not constant. Suggest 2178 // adding a 'static' in this case. 2179 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2180 << VarD 2181 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2182 } else { 2183 NoteLValueLocation(Info, Base); 2184 } 2185 } else { 2186 Info.FFDiag(Loc); 2187 } 2188 // Don't allow references to temporaries to escape. 2189 return false; 2190 } 2191 assert((Info.checkingPotentialConstantExpression() || 2192 LVal.getLValueCallIndex() == 0) && 2193 "have call index for global lvalue"); 2194 2195 if (Base.is<DynamicAllocLValue>()) { 2196 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2197 << IsReferenceType << !Designator.Entries.empty(); 2198 NoteLValueLocation(Info, Base); 2199 return false; 2200 } 2201 2202 if (BaseVD) { 2203 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2204 // Check if this is a thread-local variable. 2205 if (Var->getTLSKind()) 2206 // FIXME: Diagnostic! 2207 return false; 2208 2209 // A dllimport variable never acts like a constant, unless we're 2210 // evaluating a value for use only in name mangling. 2211 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2212 // FIXME: Diagnostic! 2213 return false; 2214 } 2215 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2216 // __declspec(dllimport) must be handled very carefully: 2217 // We must never initialize an expression with the thunk in C++. 2218 // Doing otherwise would allow the same id-expression to yield 2219 // different addresses for the same function in different translation 2220 // units. However, this means that we must dynamically initialize the 2221 // expression with the contents of the import address table at runtime. 2222 // 2223 // The C language has no notion of ODR; furthermore, it has no notion of 2224 // dynamic initialization. This means that we are permitted to 2225 // perform initialization with the address of the thunk. 2226 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2227 FD->hasAttr<DLLImportAttr>()) 2228 // FIXME: Diagnostic! 2229 return false; 2230 } 2231 } else if (const auto *MTE = 2232 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2233 if (CheckedTemps.insert(MTE).second) { 2234 QualType TempType = getType(Base); 2235 if (TempType.isDestructedType()) { 2236 Info.FFDiag(MTE->getExprLoc(), 2237 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2238 << TempType; 2239 return false; 2240 } 2241 2242 APValue *V = MTE->getOrCreateValue(false); 2243 assert(V && "evasluation result refers to uninitialised temporary"); 2244 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2245 Info, MTE->getExprLoc(), TempType, *V, 2246 Kind, SourceLocation(), CheckedTemps)) 2247 return false; 2248 } 2249 } 2250 2251 // Allow address constant expressions to be past-the-end pointers. This is 2252 // an extension: the standard requires them to point to an object. 2253 if (!IsReferenceType) 2254 return true; 2255 2256 // A reference constant expression must refer to an object. 2257 if (!Base) { 2258 // FIXME: diagnostic 2259 Info.CCEDiag(Loc); 2260 return true; 2261 } 2262 2263 // Does this refer one past the end of some object? 2264 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2265 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2266 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2267 NoteLValueLocation(Info, Base); 2268 } 2269 2270 return true; 2271 } 2272 2273 /// Member pointers are constant expressions unless they point to a 2274 /// non-virtual dllimport member function. 2275 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2276 SourceLocation Loc, 2277 QualType Type, 2278 const APValue &Value, 2279 ConstantExprKind Kind) { 2280 const ValueDecl *Member = Value.getMemberPointerDecl(); 2281 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2282 if (!FD) 2283 return true; 2284 if (FD->isConsteval()) { 2285 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2286 Info.Note(FD->getLocation(), diag::note_declared_at); 2287 return false; 2288 } 2289 return isForManglingOnly(Kind) || FD->isVirtual() || 2290 !FD->hasAttr<DLLImportAttr>(); 2291 } 2292 2293 /// Check that this core constant expression is of literal type, and if not, 2294 /// produce an appropriate diagnostic. 2295 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2296 const LValue *This = nullptr) { 2297 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2298 return true; 2299 2300 // C++1y: A constant initializer for an object o [...] may also invoke 2301 // constexpr constructors for o and its subobjects even if those objects 2302 // are of non-literal class types. 2303 // 2304 // C++11 missed this detail for aggregates, so classes like this: 2305 // struct foo_t { union { int i; volatile int j; } u; }; 2306 // are not (obviously) initializable like so: 2307 // __attribute__((__require_constant_initialization__)) 2308 // static const foo_t x = {{0}}; 2309 // because "i" is a subobject with non-literal initialization (due to the 2310 // volatile member of the union). See: 2311 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2312 // Therefore, we use the C++1y behavior. 2313 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2314 return true; 2315 2316 // Prvalue constant expressions must be of literal types. 2317 if (Info.getLangOpts().CPlusPlus11) 2318 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2319 << E->getType(); 2320 else 2321 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2322 return false; 2323 } 2324 2325 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2326 EvalInfo &Info, SourceLocation DiagLoc, 2327 QualType Type, const APValue &Value, 2328 ConstantExprKind Kind, 2329 SourceLocation SubobjectLoc, 2330 CheckedTemporaries &CheckedTemps) { 2331 if (!Value.hasValue()) { 2332 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2333 << true << Type; 2334 if (SubobjectLoc.isValid()) 2335 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2336 return false; 2337 } 2338 2339 // We allow _Atomic(T) to be initialized from anything that T can be 2340 // initialized from. 2341 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2342 Type = AT->getValueType(); 2343 2344 // Core issue 1454: For a literal constant expression of array or class type, 2345 // each subobject of its value shall have been initialized by a constant 2346 // expression. 2347 if (Value.isArray()) { 2348 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2349 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2350 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2351 Value.getArrayInitializedElt(I), Kind, 2352 SubobjectLoc, CheckedTemps)) 2353 return false; 2354 } 2355 if (!Value.hasArrayFiller()) 2356 return true; 2357 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2358 Value.getArrayFiller(), Kind, SubobjectLoc, 2359 CheckedTemps); 2360 } 2361 if (Value.isUnion() && Value.getUnionField()) { 2362 return CheckEvaluationResult( 2363 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2364 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2365 CheckedTemps); 2366 } 2367 if (Value.isStruct()) { 2368 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2369 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2370 unsigned BaseIndex = 0; 2371 for (const CXXBaseSpecifier &BS : CD->bases()) { 2372 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2373 Value.getStructBase(BaseIndex), Kind, 2374 BS.getBeginLoc(), CheckedTemps)) 2375 return false; 2376 ++BaseIndex; 2377 } 2378 } 2379 for (const auto *I : RD->fields()) { 2380 if (I->isUnnamedBitfield()) 2381 continue; 2382 2383 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2384 Value.getStructField(I->getFieldIndex()), 2385 Kind, I->getLocation(), CheckedTemps)) 2386 return false; 2387 } 2388 } 2389 2390 if (Value.isLValue() && 2391 CERK == CheckEvaluationResultKind::ConstantExpression) { 2392 LValue LVal; 2393 LVal.setFrom(Info.Ctx, Value); 2394 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2395 CheckedTemps); 2396 } 2397 2398 if (Value.isMemberPointer() && 2399 CERK == CheckEvaluationResultKind::ConstantExpression) 2400 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2401 2402 // Everything else is fine. 2403 return true; 2404 } 2405 2406 /// Check that this core constant expression value is a valid value for a 2407 /// constant expression. If not, report an appropriate diagnostic. Does not 2408 /// check that the expression is of literal type. 2409 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2410 QualType Type, const APValue &Value, 2411 ConstantExprKind Kind) { 2412 // Nothing to check for a constant expression of type 'cv void'. 2413 if (Type->isVoidType()) 2414 return true; 2415 2416 CheckedTemporaries CheckedTemps; 2417 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2418 Info, DiagLoc, Type, Value, Kind, 2419 SourceLocation(), CheckedTemps); 2420 } 2421 2422 /// Check that this evaluated value is fully-initialized and can be loaded by 2423 /// an lvalue-to-rvalue conversion. 2424 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2425 QualType Type, const APValue &Value) { 2426 CheckedTemporaries CheckedTemps; 2427 return CheckEvaluationResult( 2428 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2429 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2430 } 2431 2432 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2433 /// "the allocated storage is deallocated within the evaluation". 2434 static bool CheckMemoryLeaks(EvalInfo &Info) { 2435 if (!Info.HeapAllocs.empty()) { 2436 // We can still fold to a constant despite a compile-time memory leak, 2437 // so long as the heap allocation isn't referenced in the result (we check 2438 // that in CheckConstantExpression). 2439 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2440 diag::note_constexpr_memory_leak) 2441 << unsigned(Info.HeapAllocs.size() - 1); 2442 } 2443 return true; 2444 } 2445 2446 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2447 // A null base expression indicates a null pointer. These are always 2448 // evaluatable, and they are false unless the offset is zero. 2449 if (!Value.getLValueBase()) { 2450 Result = !Value.getLValueOffset().isZero(); 2451 return true; 2452 } 2453 2454 // We have a non-null base. These are generally known to be true, but if it's 2455 // a weak declaration it can be null at runtime. 2456 Result = true; 2457 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2458 return !Decl || !Decl->isWeak(); 2459 } 2460 2461 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2462 switch (Val.getKind()) { 2463 case APValue::None: 2464 case APValue::Indeterminate: 2465 return false; 2466 case APValue::Int: 2467 Result = Val.getInt().getBoolValue(); 2468 return true; 2469 case APValue::FixedPoint: 2470 Result = Val.getFixedPoint().getBoolValue(); 2471 return true; 2472 case APValue::Float: 2473 Result = !Val.getFloat().isZero(); 2474 return true; 2475 case APValue::ComplexInt: 2476 Result = Val.getComplexIntReal().getBoolValue() || 2477 Val.getComplexIntImag().getBoolValue(); 2478 return true; 2479 case APValue::ComplexFloat: 2480 Result = !Val.getComplexFloatReal().isZero() || 2481 !Val.getComplexFloatImag().isZero(); 2482 return true; 2483 case APValue::LValue: 2484 return EvalPointerValueAsBool(Val, Result); 2485 case APValue::MemberPointer: 2486 Result = Val.getMemberPointerDecl(); 2487 return true; 2488 case APValue::Vector: 2489 case APValue::Array: 2490 case APValue::Struct: 2491 case APValue::Union: 2492 case APValue::AddrLabelDiff: 2493 return false; 2494 } 2495 2496 llvm_unreachable("unknown APValue kind"); 2497 } 2498 2499 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2500 EvalInfo &Info) { 2501 assert(!E->isValueDependent()); 2502 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2503 APValue Val; 2504 if (!Evaluate(Val, Info, E)) 2505 return false; 2506 return HandleConversionToBool(Val, Result); 2507 } 2508 2509 template<typename T> 2510 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2511 const T &SrcValue, QualType DestType) { 2512 Info.CCEDiag(E, diag::note_constexpr_overflow) 2513 << SrcValue << DestType; 2514 return Info.noteUndefinedBehavior(); 2515 } 2516 2517 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2518 QualType SrcType, const APFloat &Value, 2519 QualType DestType, APSInt &Result) { 2520 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2521 // Determine whether we are converting to unsigned or signed. 2522 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2523 2524 Result = APSInt(DestWidth, !DestSigned); 2525 bool ignored; 2526 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2527 & APFloat::opInvalidOp) 2528 return HandleOverflow(Info, E, Value, DestType); 2529 return true; 2530 } 2531 2532 /// Get rounding mode used for evaluation of the specified expression. 2533 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2534 /// dynamic. 2535 /// If rounding mode is unknown at compile time, still try to evaluate the 2536 /// expression. If the result is exact, it does not depend on rounding mode. 2537 /// So return "tonearest" mode instead of "dynamic". 2538 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2539 bool &DynamicRM) { 2540 llvm::RoundingMode RM = 2541 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2542 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2543 if (DynamicRM) 2544 RM = llvm::RoundingMode::NearestTiesToEven; 2545 return RM; 2546 } 2547 2548 /// Check if the given evaluation result is allowed for constant evaluation. 2549 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2550 APFloat::opStatus St) { 2551 // In a constant context, assume that any dynamic rounding mode or FP 2552 // exception state matches the default floating-point environment. 2553 if (Info.InConstantContext) 2554 return true; 2555 2556 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2557 if ((St & APFloat::opInexact) && 2558 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2559 // Inexact result means that it depends on rounding mode. If the requested 2560 // mode is dynamic, the evaluation cannot be made in compile time. 2561 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2562 return false; 2563 } 2564 2565 if ((St != APFloat::opOK) && 2566 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2567 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2568 FPO.getAllowFEnvAccess())) { 2569 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2570 return false; 2571 } 2572 2573 if ((St & APFloat::opStatus::opInvalidOp) && 2574 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2575 // There is no usefully definable result. 2576 Info.FFDiag(E); 2577 return false; 2578 } 2579 2580 // FIXME: if: 2581 // - evaluation triggered other FP exception, and 2582 // - exception mode is not "ignore", and 2583 // - the expression being evaluated is not a part of global variable 2584 // initializer, 2585 // the evaluation probably need to be rejected. 2586 return true; 2587 } 2588 2589 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2590 QualType SrcType, QualType DestType, 2591 APFloat &Result) { 2592 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2593 bool DynamicRM; 2594 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2595 APFloat::opStatus St; 2596 APFloat Value = Result; 2597 bool ignored; 2598 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2599 return checkFloatingPointResult(Info, E, St); 2600 } 2601 2602 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2603 QualType DestType, QualType SrcType, 2604 const APSInt &Value) { 2605 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2606 // Figure out if this is a truncate, extend or noop cast. 2607 // If the input is signed, do a sign extend, noop, or truncate. 2608 APSInt Result = Value.extOrTrunc(DestWidth); 2609 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2610 if (DestType->isBooleanType()) 2611 Result = Value.getBoolValue(); 2612 return Result; 2613 } 2614 2615 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2616 const FPOptions FPO, 2617 QualType SrcType, const APSInt &Value, 2618 QualType DestType, APFloat &Result) { 2619 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2620 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2621 APFloat::rmNearestTiesToEven); 2622 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2623 FPO.isFPConstrained()) { 2624 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2625 return false; 2626 } 2627 return true; 2628 } 2629 2630 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2631 APValue &Value, const FieldDecl *FD) { 2632 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2633 2634 if (!Value.isInt()) { 2635 // Trying to store a pointer-cast-to-integer into a bitfield. 2636 // FIXME: In this case, we should provide the diagnostic for casting 2637 // a pointer to an integer. 2638 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2639 Info.FFDiag(E); 2640 return false; 2641 } 2642 2643 APSInt &Int = Value.getInt(); 2644 unsigned OldBitWidth = Int.getBitWidth(); 2645 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2646 if (NewBitWidth < OldBitWidth) 2647 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2648 return true; 2649 } 2650 2651 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2652 llvm::APInt &Res) { 2653 APValue SVal; 2654 if (!Evaluate(SVal, Info, E)) 2655 return false; 2656 if (SVal.isInt()) { 2657 Res = SVal.getInt(); 2658 return true; 2659 } 2660 if (SVal.isFloat()) { 2661 Res = SVal.getFloat().bitcastToAPInt(); 2662 return true; 2663 } 2664 if (SVal.isVector()) { 2665 QualType VecTy = E->getType(); 2666 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2667 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2668 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2669 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2670 Res = llvm::APInt::getNullValue(VecSize); 2671 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2672 APValue &Elt = SVal.getVectorElt(i); 2673 llvm::APInt EltAsInt; 2674 if (Elt.isInt()) { 2675 EltAsInt = Elt.getInt(); 2676 } else if (Elt.isFloat()) { 2677 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2678 } else { 2679 // Don't try to handle vectors of anything other than int or float 2680 // (not sure if it's possible to hit this case). 2681 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2682 return false; 2683 } 2684 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2685 if (BigEndian) 2686 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2687 else 2688 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2689 } 2690 return true; 2691 } 2692 // Give up if the input isn't an int, float, or vector. For example, we 2693 // reject "(v4i16)(intptr_t)&a". 2694 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2695 return false; 2696 } 2697 2698 /// Perform the given integer operation, which is known to need at most BitWidth 2699 /// bits, and check for overflow in the original type (if that type was not an 2700 /// unsigned type). 2701 template<typename Operation> 2702 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2703 const APSInt &LHS, const APSInt &RHS, 2704 unsigned BitWidth, Operation Op, 2705 APSInt &Result) { 2706 if (LHS.isUnsigned()) { 2707 Result = Op(LHS, RHS); 2708 return true; 2709 } 2710 2711 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2712 Result = Value.trunc(LHS.getBitWidth()); 2713 if (Result.extend(BitWidth) != Value) { 2714 if (Info.checkingForUndefinedBehavior()) 2715 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2716 diag::warn_integer_constant_overflow) 2717 << Result.toString(10) << E->getType(); 2718 else 2719 return HandleOverflow(Info, E, Value, E->getType()); 2720 } 2721 return true; 2722 } 2723 2724 /// Perform the given binary integer operation. 2725 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2726 BinaryOperatorKind Opcode, APSInt RHS, 2727 APSInt &Result) { 2728 switch (Opcode) { 2729 default: 2730 Info.FFDiag(E); 2731 return false; 2732 case BO_Mul: 2733 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2734 std::multiplies<APSInt>(), Result); 2735 case BO_Add: 2736 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2737 std::plus<APSInt>(), Result); 2738 case BO_Sub: 2739 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2740 std::minus<APSInt>(), Result); 2741 case BO_And: Result = LHS & RHS; return true; 2742 case BO_Xor: Result = LHS ^ RHS; return true; 2743 case BO_Or: Result = LHS | RHS; return true; 2744 case BO_Div: 2745 case BO_Rem: 2746 if (RHS == 0) { 2747 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2748 return false; 2749 } 2750 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2751 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2752 // this operation and gives the two's complement result. 2753 if (RHS.isNegative() && RHS.isAllOnesValue() && 2754 LHS.isSigned() && LHS.isMinSignedValue()) 2755 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2756 E->getType()); 2757 return true; 2758 case BO_Shl: { 2759 if (Info.getLangOpts().OpenCL) 2760 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2761 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2762 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2763 RHS.isUnsigned()); 2764 else if (RHS.isSigned() && RHS.isNegative()) { 2765 // During constant-folding, a negative shift is an opposite shift. Such 2766 // a shift is not a constant expression. 2767 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2768 RHS = -RHS; 2769 goto shift_right; 2770 } 2771 shift_left: 2772 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2773 // the shifted type. 2774 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2775 if (SA != RHS) { 2776 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2777 << RHS << E->getType() << LHS.getBitWidth(); 2778 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2779 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2780 // operand, and must not overflow the corresponding unsigned type. 2781 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2782 // E1 x 2^E2 module 2^N. 2783 if (LHS.isNegative()) 2784 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2785 else if (LHS.countLeadingZeros() < SA) 2786 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2787 } 2788 Result = LHS << SA; 2789 return true; 2790 } 2791 case BO_Shr: { 2792 if (Info.getLangOpts().OpenCL) 2793 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2794 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2795 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2796 RHS.isUnsigned()); 2797 else if (RHS.isSigned() && RHS.isNegative()) { 2798 // During constant-folding, a negative shift is an opposite shift. Such a 2799 // shift is not a constant expression. 2800 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2801 RHS = -RHS; 2802 goto shift_left; 2803 } 2804 shift_right: 2805 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2806 // shifted type. 2807 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2808 if (SA != RHS) 2809 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2810 << RHS << E->getType() << LHS.getBitWidth(); 2811 Result = LHS >> SA; 2812 return true; 2813 } 2814 2815 case BO_LT: Result = LHS < RHS; return true; 2816 case BO_GT: Result = LHS > RHS; return true; 2817 case BO_LE: Result = LHS <= RHS; return true; 2818 case BO_GE: Result = LHS >= RHS; return true; 2819 case BO_EQ: Result = LHS == RHS; return true; 2820 case BO_NE: Result = LHS != RHS; return true; 2821 case BO_Cmp: 2822 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2823 } 2824 } 2825 2826 /// Perform the given binary floating-point operation, in-place, on LHS. 2827 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2828 APFloat &LHS, BinaryOperatorKind Opcode, 2829 const APFloat &RHS) { 2830 bool DynamicRM; 2831 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2832 APFloat::opStatus St; 2833 switch (Opcode) { 2834 default: 2835 Info.FFDiag(E); 2836 return false; 2837 case BO_Mul: 2838 St = LHS.multiply(RHS, RM); 2839 break; 2840 case BO_Add: 2841 St = LHS.add(RHS, RM); 2842 break; 2843 case BO_Sub: 2844 St = LHS.subtract(RHS, RM); 2845 break; 2846 case BO_Div: 2847 // [expr.mul]p4: 2848 // If the second operand of / or % is zero the behavior is undefined. 2849 if (RHS.isZero()) 2850 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2851 St = LHS.divide(RHS, RM); 2852 break; 2853 } 2854 2855 // [expr.pre]p4: 2856 // If during the evaluation of an expression, the result is not 2857 // mathematically defined [...], the behavior is undefined. 2858 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2859 if (LHS.isNaN()) { 2860 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2861 return Info.noteUndefinedBehavior(); 2862 } 2863 2864 return checkFloatingPointResult(Info, E, St); 2865 } 2866 2867 static bool handleLogicalOpForVector(const APInt &LHSValue, 2868 BinaryOperatorKind Opcode, 2869 const APInt &RHSValue, APInt &Result) { 2870 bool LHS = (LHSValue != 0); 2871 bool RHS = (RHSValue != 0); 2872 2873 if (Opcode == BO_LAnd) 2874 Result = LHS && RHS; 2875 else 2876 Result = LHS || RHS; 2877 return true; 2878 } 2879 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2880 BinaryOperatorKind Opcode, 2881 const APFloat &RHSValue, APInt &Result) { 2882 bool LHS = !LHSValue.isZero(); 2883 bool RHS = !RHSValue.isZero(); 2884 2885 if (Opcode == BO_LAnd) 2886 Result = LHS && RHS; 2887 else 2888 Result = LHS || RHS; 2889 return true; 2890 } 2891 2892 static bool handleLogicalOpForVector(const APValue &LHSValue, 2893 BinaryOperatorKind Opcode, 2894 const APValue &RHSValue, APInt &Result) { 2895 // The result is always an int type, however operands match the first. 2896 if (LHSValue.getKind() == APValue::Int) 2897 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2898 RHSValue.getInt(), Result); 2899 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2900 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2901 RHSValue.getFloat(), Result); 2902 } 2903 2904 template <typename APTy> 2905 static bool 2906 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2907 const APTy &RHSValue, APInt &Result) { 2908 switch (Opcode) { 2909 default: 2910 llvm_unreachable("unsupported binary operator"); 2911 case BO_EQ: 2912 Result = (LHSValue == RHSValue); 2913 break; 2914 case BO_NE: 2915 Result = (LHSValue != RHSValue); 2916 break; 2917 case BO_LT: 2918 Result = (LHSValue < RHSValue); 2919 break; 2920 case BO_GT: 2921 Result = (LHSValue > RHSValue); 2922 break; 2923 case BO_LE: 2924 Result = (LHSValue <= RHSValue); 2925 break; 2926 case BO_GE: 2927 Result = (LHSValue >= RHSValue); 2928 break; 2929 } 2930 2931 return true; 2932 } 2933 2934 static bool handleCompareOpForVector(const APValue &LHSValue, 2935 BinaryOperatorKind Opcode, 2936 const APValue &RHSValue, APInt &Result) { 2937 // The result is always an int type, however operands match the first. 2938 if (LHSValue.getKind() == APValue::Int) 2939 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2940 RHSValue.getInt(), Result); 2941 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2942 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2943 RHSValue.getFloat(), Result); 2944 } 2945 2946 // Perform binary operations for vector types, in place on the LHS. 2947 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2948 BinaryOperatorKind Opcode, 2949 APValue &LHSValue, 2950 const APValue &RHSValue) { 2951 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2952 "Operation not supported on vector types"); 2953 2954 const auto *VT = E->getType()->castAs<VectorType>(); 2955 unsigned NumElements = VT->getNumElements(); 2956 QualType EltTy = VT->getElementType(); 2957 2958 // In the cases (typically C as I've observed) where we aren't evaluating 2959 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2960 // just give up. 2961 if (!LHSValue.isVector()) { 2962 assert(LHSValue.isLValue() && 2963 "A vector result that isn't a vector OR uncalculated LValue"); 2964 Info.FFDiag(E); 2965 return false; 2966 } 2967 2968 assert(LHSValue.getVectorLength() == NumElements && 2969 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2970 2971 SmallVector<APValue, 4> ResultElements; 2972 2973 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2974 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2975 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2976 2977 if (EltTy->isIntegerType()) { 2978 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2979 EltTy->isUnsignedIntegerType()}; 2980 bool Success = true; 2981 2982 if (BinaryOperator::isLogicalOp(Opcode)) 2983 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2984 else if (BinaryOperator::isComparisonOp(Opcode)) 2985 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2986 else 2987 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2988 RHSElt.getInt(), EltResult); 2989 2990 if (!Success) { 2991 Info.FFDiag(E); 2992 return false; 2993 } 2994 ResultElements.emplace_back(EltResult); 2995 2996 } else if (EltTy->isFloatingType()) { 2997 assert(LHSElt.getKind() == APValue::Float && 2998 RHSElt.getKind() == APValue::Float && 2999 "Mismatched LHS/RHS/Result Type"); 3000 APFloat LHSFloat = LHSElt.getFloat(); 3001 3002 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3003 RHSElt.getFloat())) { 3004 Info.FFDiag(E); 3005 return false; 3006 } 3007 3008 ResultElements.emplace_back(LHSFloat); 3009 } 3010 } 3011 3012 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3013 return true; 3014 } 3015 3016 /// Cast an lvalue referring to a base subobject to a derived class, by 3017 /// truncating the lvalue's path to the given length. 3018 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3019 const RecordDecl *TruncatedType, 3020 unsigned TruncatedElements) { 3021 SubobjectDesignator &D = Result.Designator; 3022 3023 // Check we actually point to a derived class object. 3024 if (TruncatedElements == D.Entries.size()) 3025 return true; 3026 assert(TruncatedElements >= D.MostDerivedPathLength && 3027 "not casting to a derived class"); 3028 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3029 return false; 3030 3031 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3032 const RecordDecl *RD = TruncatedType; 3033 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3034 if (RD->isInvalidDecl()) return false; 3035 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3036 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3037 if (isVirtualBaseClass(D.Entries[I])) 3038 Result.Offset -= Layout.getVBaseClassOffset(Base); 3039 else 3040 Result.Offset -= Layout.getBaseClassOffset(Base); 3041 RD = Base; 3042 } 3043 D.Entries.resize(TruncatedElements); 3044 return true; 3045 } 3046 3047 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3048 const CXXRecordDecl *Derived, 3049 const CXXRecordDecl *Base, 3050 const ASTRecordLayout *RL = nullptr) { 3051 if (!RL) { 3052 if (Derived->isInvalidDecl()) return false; 3053 RL = &Info.Ctx.getASTRecordLayout(Derived); 3054 } 3055 3056 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3057 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3058 return true; 3059 } 3060 3061 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3062 const CXXRecordDecl *DerivedDecl, 3063 const CXXBaseSpecifier *Base) { 3064 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3065 3066 if (!Base->isVirtual()) 3067 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3068 3069 SubobjectDesignator &D = Obj.Designator; 3070 if (D.Invalid) 3071 return false; 3072 3073 // Extract most-derived object and corresponding type. 3074 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3075 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3076 return false; 3077 3078 // Find the virtual base class. 3079 if (DerivedDecl->isInvalidDecl()) return false; 3080 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3081 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3082 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3083 return true; 3084 } 3085 3086 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3087 QualType Type, LValue &Result) { 3088 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3089 PathE = E->path_end(); 3090 PathI != PathE; ++PathI) { 3091 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3092 *PathI)) 3093 return false; 3094 Type = (*PathI)->getType(); 3095 } 3096 return true; 3097 } 3098 3099 /// Cast an lvalue referring to a derived class to a known base subobject. 3100 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3101 const CXXRecordDecl *DerivedRD, 3102 const CXXRecordDecl *BaseRD) { 3103 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3104 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3105 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3106 llvm_unreachable("Class must be derived from the passed in base class!"); 3107 3108 for (CXXBasePathElement &Elem : Paths.front()) 3109 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3110 return false; 3111 return true; 3112 } 3113 3114 /// Update LVal to refer to the given field, which must be a member of the type 3115 /// currently described by LVal. 3116 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3117 const FieldDecl *FD, 3118 const ASTRecordLayout *RL = nullptr) { 3119 if (!RL) { 3120 if (FD->getParent()->isInvalidDecl()) return false; 3121 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3122 } 3123 3124 unsigned I = FD->getFieldIndex(); 3125 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3126 LVal.addDecl(Info, E, FD); 3127 return true; 3128 } 3129 3130 /// Update LVal to refer to the given indirect field. 3131 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3132 LValue &LVal, 3133 const IndirectFieldDecl *IFD) { 3134 for (const auto *C : IFD->chain()) 3135 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3136 return false; 3137 return true; 3138 } 3139 3140 /// Get the size of the given type in char units. 3141 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3142 QualType Type, CharUnits &Size) { 3143 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3144 // extension. 3145 if (Type->isVoidType() || Type->isFunctionType()) { 3146 Size = CharUnits::One(); 3147 return true; 3148 } 3149 3150 if (Type->isDependentType()) { 3151 Info.FFDiag(Loc); 3152 return false; 3153 } 3154 3155 if (!Type->isConstantSizeType()) { 3156 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3157 // FIXME: Better diagnostic. 3158 Info.FFDiag(Loc); 3159 return false; 3160 } 3161 3162 Size = Info.Ctx.getTypeSizeInChars(Type); 3163 return true; 3164 } 3165 3166 /// Update a pointer value to model pointer arithmetic. 3167 /// \param Info - Information about the ongoing evaluation. 3168 /// \param E - The expression being evaluated, for diagnostic purposes. 3169 /// \param LVal - The pointer value to be updated. 3170 /// \param EltTy - The pointee type represented by LVal. 3171 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3172 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3173 LValue &LVal, QualType EltTy, 3174 APSInt Adjustment) { 3175 CharUnits SizeOfPointee; 3176 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3177 return false; 3178 3179 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3180 return true; 3181 } 3182 3183 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3184 LValue &LVal, QualType EltTy, 3185 int64_t Adjustment) { 3186 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3187 APSInt::get(Adjustment)); 3188 } 3189 3190 /// Update an lvalue to refer to a component of a complex number. 3191 /// \param Info - Information about the ongoing evaluation. 3192 /// \param LVal - The lvalue to be updated. 3193 /// \param EltTy - The complex number's component type. 3194 /// \param Imag - False for the real component, true for the imaginary. 3195 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3196 LValue &LVal, QualType EltTy, 3197 bool Imag) { 3198 if (Imag) { 3199 CharUnits SizeOfComponent; 3200 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3201 return false; 3202 LVal.Offset += SizeOfComponent; 3203 } 3204 LVal.addComplex(Info, E, EltTy, Imag); 3205 return true; 3206 } 3207 3208 /// Try to evaluate the initializer for a variable declaration. 3209 /// 3210 /// \param Info Information about the ongoing evaluation. 3211 /// \param E An expression to be used when printing diagnostics. 3212 /// \param VD The variable whose initializer should be obtained. 3213 /// \param Version The version of the variable within the frame. 3214 /// \param Frame The frame in which the variable was created. Must be null 3215 /// if this variable is not local to the evaluation. 3216 /// \param Result Filled in with a pointer to the value of the variable. 3217 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3218 const VarDecl *VD, CallStackFrame *Frame, 3219 unsigned Version, APValue *&Result) { 3220 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3221 3222 // If this is a local variable, dig out its value. 3223 if (Frame) { 3224 Result = Frame->getTemporary(VD, Version); 3225 if (Result) 3226 return true; 3227 3228 if (!isa<ParmVarDecl>(VD)) { 3229 // Assume variables referenced within a lambda's call operator that were 3230 // not declared within the call operator are captures and during checking 3231 // of a potential constant expression, assume they are unknown constant 3232 // expressions. 3233 assert(isLambdaCallOperator(Frame->Callee) && 3234 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3235 "missing value for local variable"); 3236 if (Info.checkingPotentialConstantExpression()) 3237 return false; 3238 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3239 // still reachable at all? 3240 Info.FFDiag(E->getBeginLoc(), 3241 diag::note_unimplemented_constexpr_lambda_feature_ast) 3242 << "captures not currently allowed"; 3243 return false; 3244 } 3245 } 3246 3247 // If we're currently evaluating the initializer of this declaration, use that 3248 // in-flight value. 3249 if (Info.EvaluatingDecl == Base) { 3250 Result = Info.EvaluatingDeclValue; 3251 return true; 3252 } 3253 3254 if (isa<ParmVarDecl>(VD)) { 3255 // Assume parameters of a potential constant expression are usable in 3256 // constant expressions. 3257 if (!Info.checkingPotentialConstantExpression() || 3258 !Info.CurrentCall->Callee || 3259 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3260 if (Info.getLangOpts().CPlusPlus11) { 3261 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3262 << VD; 3263 NoteLValueLocation(Info, Base); 3264 } else { 3265 Info.FFDiag(E); 3266 } 3267 } 3268 return false; 3269 } 3270 3271 // Dig out the initializer, and use the declaration which it's attached to. 3272 // FIXME: We should eventually check whether the variable has a reachable 3273 // initializing declaration. 3274 const Expr *Init = VD->getAnyInitializer(VD); 3275 if (!Init) { 3276 // Don't diagnose during potential constant expression checking; an 3277 // initializer might be added later. 3278 if (!Info.checkingPotentialConstantExpression()) { 3279 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3280 << VD; 3281 NoteLValueLocation(Info, Base); 3282 } 3283 return false; 3284 } 3285 3286 if (Init->isValueDependent()) { 3287 // The DeclRefExpr is not value-dependent, but the variable it refers to 3288 // has a value-dependent initializer. This should only happen in 3289 // constant-folding cases, where the variable is not actually of a suitable 3290 // type for use in a constant expression (otherwise the DeclRefExpr would 3291 // have been value-dependent too), so diagnose that. 3292 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3293 if (!Info.checkingPotentialConstantExpression()) { 3294 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3295 ? diag::note_constexpr_ltor_non_constexpr 3296 : diag::note_constexpr_ltor_non_integral, 1) 3297 << VD << VD->getType(); 3298 NoteLValueLocation(Info, Base); 3299 } 3300 return false; 3301 } 3302 3303 // Check that we can fold the initializer. In C++, we will have already done 3304 // this in the cases where it matters for conformance. 3305 if (!VD->evaluateValue()) { 3306 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3307 NoteLValueLocation(Info, Base); 3308 return false; 3309 } 3310 3311 // Check that the variable is actually usable in constant expressions. For a 3312 // const integral variable or a reference, we might have a non-constant 3313 // initializer that we can nonetheless evaluate the initializer for. Such 3314 // variables are not usable in constant expressions. In C++98, the 3315 // initializer also syntactically needs to be an ICE. 3316 // 3317 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3318 // expressions here; doing so would regress diagnostics for things like 3319 // reading from a volatile constexpr variable. 3320 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3321 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3322 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3323 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3324 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3325 NoteLValueLocation(Info, Base); 3326 } 3327 3328 // Never use the initializer of a weak variable, not even for constant 3329 // folding. We can't be sure that this is the definition that will be used. 3330 if (VD->isWeak()) { 3331 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3332 NoteLValueLocation(Info, Base); 3333 return false; 3334 } 3335 3336 Result = VD->getEvaluatedValue(); 3337 return true; 3338 } 3339 3340 /// Get the base index of the given base class within an APValue representing 3341 /// the given derived class. 3342 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3343 const CXXRecordDecl *Base) { 3344 Base = Base->getCanonicalDecl(); 3345 unsigned Index = 0; 3346 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3347 E = Derived->bases_end(); I != E; ++I, ++Index) { 3348 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3349 return Index; 3350 } 3351 3352 llvm_unreachable("base class missing from derived class's bases list"); 3353 } 3354 3355 /// Extract the value of a character from a string literal. 3356 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3357 uint64_t Index) { 3358 assert(!isa<SourceLocExpr>(Lit) && 3359 "SourceLocExpr should have already been converted to a StringLiteral"); 3360 3361 // FIXME: Support MakeStringConstant 3362 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3363 std::string Str; 3364 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3365 assert(Index <= Str.size() && "Index too large"); 3366 return APSInt::getUnsigned(Str.c_str()[Index]); 3367 } 3368 3369 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3370 Lit = PE->getFunctionName(); 3371 const StringLiteral *S = cast<StringLiteral>(Lit); 3372 const ConstantArrayType *CAT = 3373 Info.Ctx.getAsConstantArrayType(S->getType()); 3374 assert(CAT && "string literal isn't an array"); 3375 QualType CharType = CAT->getElementType(); 3376 assert(CharType->isIntegerType() && "unexpected character type"); 3377 3378 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3379 CharType->isUnsignedIntegerType()); 3380 if (Index < S->getLength()) 3381 Value = S->getCodeUnit(Index); 3382 return Value; 3383 } 3384 3385 // Expand a string literal into an array of characters. 3386 // 3387 // FIXME: This is inefficient; we should probably introduce something similar 3388 // to the LLVM ConstantDataArray to make this cheaper. 3389 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3390 APValue &Result, 3391 QualType AllocType = QualType()) { 3392 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3393 AllocType.isNull() ? S->getType() : AllocType); 3394 assert(CAT && "string literal isn't an array"); 3395 QualType CharType = CAT->getElementType(); 3396 assert(CharType->isIntegerType() && "unexpected character type"); 3397 3398 unsigned Elts = CAT->getSize().getZExtValue(); 3399 Result = APValue(APValue::UninitArray(), 3400 std::min(S->getLength(), Elts), Elts); 3401 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3402 CharType->isUnsignedIntegerType()); 3403 if (Result.hasArrayFiller()) 3404 Result.getArrayFiller() = APValue(Value); 3405 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3406 Value = S->getCodeUnit(I); 3407 Result.getArrayInitializedElt(I) = APValue(Value); 3408 } 3409 } 3410 3411 // Expand an array so that it has more than Index filled elements. 3412 static void expandArray(APValue &Array, unsigned Index) { 3413 unsigned Size = Array.getArraySize(); 3414 assert(Index < Size); 3415 3416 // Always at least double the number of elements for which we store a value. 3417 unsigned OldElts = Array.getArrayInitializedElts(); 3418 unsigned NewElts = std::max(Index+1, OldElts * 2); 3419 NewElts = std::min(Size, std::max(NewElts, 8u)); 3420 3421 // Copy the data across. 3422 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3423 for (unsigned I = 0; I != OldElts; ++I) 3424 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3425 for (unsigned I = OldElts; I != NewElts; ++I) 3426 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3427 if (NewValue.hasArrayFiller()) 3428 NewValue.getArrayFiller() = Array.getArrayFiller(); 3429 Array.swap(NewValue); 3430 } 3431 3432 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3433 /// conversion. If it's of class type, we may assume that the copy operation 3434 /// is trivial. Note that this is never true for a union type with fields 3435 /// (because the copy always "reads" the active member) and always true for 3436 /// a non-class type. 3437 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3438 static bool isReadByLvalueToRvalueConversion(QualType T) { 3439 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3440 return !RD || isReadByLvalueToRvalueConversion(RD); 3441 } 3442 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3443 // FIXME: A trivial copy of a union copies the object representation, even if 3444 // the union is empty. 3445 if (RD->isUnion()) 3446 return !RD->field_empty(); 3447 if (RD->isEmpty()) 3448 return false; 3449 3450 for (auto *Field : RD->fields()) 3451 if (!Field->isUnnamedBitfield() && 3452 isReadByLvalueToRvalueConversion(Field->getType())) 3453 return true; 3454 3455 for (auto &BaseSpec : RD->bases()) 3456 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3457 return true; 3458 3459 return false; 3460 } 3461 3462 /// Diagnose an attempt to read from any unreadable field within the specified 3463 /// type, which might be a class type. 3464 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3465 QualType T) { 3466 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3467 if (!RD) 3468 return false; 3469 3470 if (!RD->hasMutableFields()) 3471 return false; 3472 3473 for (auto *Field : RD->fields()) { 3474 // If we're actually going to read this field in some way, then it can't 3475 // be mutable. If we're in a union, then assigning to a mutable field 3476 // (even an empty one) can change the active member, so that's not OK. 3477 // FIXME: Add core issue number for the union case. 3478 if (Field->isMutable() && 3479 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3480 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3481 Info.Note(Field->getLocation(), diag::note_declared_at); 3482 return true; 3483 } 3484 3485 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3486 return true; 3487 } 3488 3489 for (auto &BaseSpec : RD->bases()) 3490 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3491 return true; 3492 3493 // All mutable fields were empty, and thus not actually read. 3494 return false; 3495 } 3496 3497 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3498 APValue::LValueBase Base, 3499 bool MutableSubobject = false) { 3500 // A temporary we created. 3501 if (Base.getCallIndex()) 3502 return true; 3503 3504 switch (Info.IsEvaluatingDecl) { 3505 case EvalInfo::EvaluatingDeclKind::None: 3506 return false; 3507 3508 case EvalInfo::EvaluatingDeclKind::Ctor: 3509 // The variable whose initializer we're evaluating. 3510 if (Info.EvaluatingDecl == Base) 3511 return true; 3512 3513 // A temporary lifetime-extended by the variable whose initializer we're 3514 // evaluating. 3515 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3516 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3517 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3518 return false; 3519 3520 case EvalInfo::EvaluatingDeclKind::Dtor: 3521 // C++2a [expr.const]p6: 3522 // [during constant destruction] the lifetime of a and its non-mutable 3523 // subobjects (but not its mutable subobjects) [are] considered to start 3524 // within e. 3525 if (MutableSubobject || Base != Info.EvaluatingDecl) 3526 return false; 3527 // FIXME: We can meaningfully extend this to cover non-const objects, but 3528 // we will need special handling: we should be able to access only 3529 // subobjects of such objects that are themselves declared const. 3530 QualType T = getType(Base); 3531 return T.isConstQualified() || T->isReferenceType(); 3532 } 3533 3534 llvm_unreachable("unknown evaluating decl kind"); 3535 } 3536 3537 namespace { 3538 /// A handle to a complete object (an object that is not a subobject of 3539 /// another object). 3540 struct CompleteObject { 3541 /// The identity of the object. 3542 APValue::LValueBase Base; 3543 /// The value of the complete object. 3544 APValue *Value; 3545 /// The type of the complete object. 3546 QualType Type; 3547 3548 CompleteObject() : Value(nullptr) {} 3549 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3550 : Base(Base), Value(Value), Type(Type) {} 3551 3552 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3553 // If this isn't a "real" access (eg, if it's just accessing the type 3554 // info), allow it. We assume the type doesn't change dynamically for 3555 // subobjects of constexpr objects (even though we'd hit UB here if it 3556 // did). FIXME: Is this right? 3557 if (!isAnyAccess(AK)) 3558 return true; 3559 3560 // In C++14 onwards, it is permitted to read a mutable member whose 3561 // lifetime began within the evaluation. 3562 // FIXME: Should we also allow this in C++11? 3563 if (!Info.getLangOpts().CPlusPlus14) 3564 return false; 3565 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3566 } 3567 3568 explicit operator bool() const { return !Type.isNull(); } 3569 }; 3570 } // end anonymous namespace 3571 3572 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3573 bool IsMutable = false) { 3574 // C++ [basic.type.qualifier]p1: 3575 // - A const object is an object of type const T or a non-mutable subobject 3576 // of a const object. 3577 if (ObjType.isConstQualified() && !IsMutable) 3578 SubobjType.addConst(); 3579 // - A volatile object is an object of type const T or a subobject of a 3580 // volatile object. 3581 if (ObjType.isVolatileQualified()) 3582 SubobjType.addVolatile(); 3583 return SubobjType; 3584 } 3585 3586 /// Find the designated sub-object of an rvalue. 3587 template<typename SubobjectHandler> 3588 typename SubobjectHandler::result_type 3589 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3590 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3591 if (Sub.Invalid) 3592 // A diagnostic will have already been produced. 3593 return handler.failed(); 3594 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3595 if (Info.getLangOpts().CPlusPlus11) 3596 Info.FFDiag(E, Sub.isOnePastTheEnd() 3597 ? diag::note_constexpr_access_past_end 3598 : diag::note_constexpr_access_unsized_array) 3599 << handler.AccessKind; 3600 else 3601 Info.FFDiag(E); 3602 return handler.failed(); 3603 } 3604 3605 APValue *O = Obj.Value; 3606 QualType ObjType = Obj.Type; 3607 const FieldDecl *LastField = nullptr; 3608 const FieldDecl *VolatileField = nullptr; 3609 3610 // Walk the designator's path to find the subobject. 3611 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3612 // Reading an indeterminate value is undefined, but assigning over one is OK. 3613 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3614 (O->isIndeterminate() && 3615 !isValidIndeterminateAccess(handler.AccessKind))) { 3616 if (!Info.checkingPotentialConstantExpression()) 3617 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3618 << handler.AccessKind << O->isIndeterminate(); 3619 return handler.failed(); 3620 } 3621 3622 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3623 // const and volatile semantics are not applied on an object under 3624 // {con,de}struction. 3625 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3626 ObjType->isRecordType() && 3627 Info.isEvaluatingCtorDtor( 3628 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3629 Sub.Entries.begin() + I)) != 3630 ConstructionPhase::None) { 3631 ObjType = Info.Ctx.getCanonicalType(ObjType); 3632 ObjType.removeLocalConst(); 3633 ObjType.removeLocalVolatile(); 3634 } 3635 3636 // If this is our last pass, check that the final object type is OK. 3637 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3638 // Accesses to volatile objects are prohibited. 3639 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3640 if (Info.getLangOpts().CPlusPlus) { 3641 int DiagKind; 3642 SourceLocation Loc; 3643 const NamedDecl *Decl = nullptr; 3644 if (VolatileField) { 3645 DiagKind = 2; 3646 Loc = VolatileField->getLocation(); 3647 Decl = VolatileField; 3648 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3649 DiagKind = 1; 3650 Loc = VD->getLocation(); 3651 Decl = VD; 3652 } else { 3653 DiagKind = 0; 3654 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3655 Loc = E->getExprLoc(); 3656 } 3657 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3658 << handler.AccessKind << DiagKind << Decl; 3659 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3660 } else { 3661 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3662 } 3663 return handler.failed(); 3664 } 3665 3666 // If we are reading an object of class type, there may still be more 3667 // things we need to check: if there are any mutable subobjects, we 3668 // cannot perform this read. (This only happens when performing a trivial 3669 // copy or assignment.) 3670 if (ObjType->isRecordType() && 3671 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3672 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3673 return handler.failed(); 3674 } 3675 3676 if (I == N) { 3677 if (!handler.found(*O, ObjType)) 3678 return false; 3679 3680 // If we modified a bit-field, truncate it to the right width. 3681 if (isModification(handler.AccessKind) && 3682 LastField && LastField->isBitField() && 3683 !truncateBitfieldValue(Info, E, *O, LastField)) 3684 return false; 3685 3686 return true; 3687 } 3688 3689 LastField = nullptr; 3690 if (ObjType->isArrayType()) { 3691 // Next subobject is an array element. 3692 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3693 assert(CAT && "vla in literal type?"); 3694 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3695 if (CAT->getSize().ule(Index)) { 3696 // Note, it should not be possible to form a pointer with a valid 3697 // designator which points more than one past the end of the array. 3698 if (Info.getLangOpts().CPlusPlus11) 3699 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3700 << handler.AccessKind; 3701 else 3702 Info.FFDiag(E); 3703 return handler.failed(); 3704 } 3705 3706 ObjType = CAT->getElementType(); 3707 3708 if (O->getArrayInitializedElts() > Index) 3709 O = &O->getArrayInitializedElt(Index); 3710 else if (!isRead(handler.AccessKind)) { 3711 expandArray(*O, Index); 3712 O = &O->getArrayInitializedElt(Index); 3713 } else 3714 O = &O->getArrayFiller(); 3715 } else if (ObjType->isAnyComplexType()) { 3716 // Next subobject is a complex number. 3717 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3718 if (Index > 1) { 3719 if (Info.getLangOpts().CPlusPlus11) 3720 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3721 << handler.AccessKind; 3722 else 3723 Info.FFDiag(E); 3724 return handler.failed(); 3725 } 3726 3727 ObjType = getSubobjectType( 3728 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3729 3730 assert(I == N - 1 && "extracting subobject of scalar?"); 3731 if (O->isComplexInt()) { 3732 return handler.found(Index ? O->getComplexIntImag() 3733 : O->getComplexIntReal(), ObjType); 3734 } else { 3735 assert(O->isComplexFloat()); 3736 return handler.found(Index ? O->getComplexFloatImag() 3737 : O->getComplexFloatReal(), ObjType); 3738 } 3739 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3740 if (Field->isMutable() && 3741 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3742 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3743 << handler.AccessKind << Field; 3744 Info.Note(Field->getLocation(), diag::note_declared_at); 3745 return handler.failed(); 3746 } 3747 3748 // Next subobject is a class, struct or union field. 3749 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3750 if (RD->isUnion()) { 3751 const FieldDecl *UnionField = O->getUnionField(); 3752 if (!UnionField || 3753 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3754 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3755 // Placement new onto an inactive union member makes it active. 3756 O->setUnion(Field, APValue()); 3757 } else { 3758 // FIXME: If O->getUnionValue() is absent, report that there's no 3759 // active union member rather than reporting the prior active union 3760 // member. We'll need to fix nullptr_t to not use APValue() as its 3761 // representation first. 3762 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3763 << handler.AccessKind << Field << !UnionField << UnionField; 3764 return handler.failed(); 3765 } 3766 } 3767 O = &O->getUnionValue(); 3768 } else 3769 O = &O->getStructField(Field->getFieldIndex()); 3770 3771 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3772 LastField = Field; 3773 if (Field->getType().isVolatileQualified()) 3774 VolatileField = Field; 3775 } else { 3776 // Next subobject is a base class. 3777 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3778 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3779 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3780 3781 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3782 } 3783 } 3784 } 3785 3786 namespace { 3787 struct ExtractSubobjectHandler { 3788 EvalInfo &Info; 3789 const Expr *E; 3790 APValue &Result; 3791 const AccessKinds AccessKind; 3792 3793 typedef bool result_type; 3794 bool failed() { return false; } 3795 bool found(APValue &Subobj, QualType SubobjType) { 3796 Result = Subobj; 3797 if (AccessKind == AK_ReadObjectRepresentation) 3798 return true; 3799 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3800 } 3801 bool found(APSInt &Value, QualType SubobjType) { 3802 Result = APValue(Value); 3803 return true; 3804 } 3805 bool found(APFloat &Value, QualType SubobjType) { 3806 Result = APValue(Value); 3807 return true; 3808 } 3809 }; 3810 } // end anonymous namespace 3811 3812 /// Extract the designated sub-object of an rvalue. 3813 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3814 const CompleteObject &Obj, 3815 const SubobjectDesignator &Sub, APValue &Result, 3816 AccessKinds AK = AK_Read) { 3817 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3818 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3819 return findSubobject(Info, E, Obj, Sub, Handler); 3820 } 3821 3822 namespace { 3823 struct ModifySubobjectHandler { 3824 EvalInfo &Info; 3825 APValue &NewVal; 3826 const Expr *E; 3827 3828 typedef bool result_type; 3829 static const AccessKinds AccessKind = AK_Assign; 3830 3831 bool checkConst(QualType QT) { 3832 // Assigning to a const object has undefined behavior. 3833 if (QT.isConstQualified()) { 3834 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3835 return false; 3836 } 3837 return true; 3838 } 3839 3840 bool failed() { return false; } 3841 bool found(APValue &Subobj, QualType SubobjType) { 3842 if (!checkConst(SubobjType)) 3843 return false; 3844 // We've been given ownership of NewVal, so just swap it in. 3845 Subobj.swap(NewVal); 3846 return true; 3847 } 3848 bool found(APSInt &Value, QualType SubobjType) { 3849 if (!checkConst(SubobjType)) 3850 return false; 3851 if (!NewVal.isInt()) { 3852 // Maybe trying to write a cast pointer value into a complex? 3853 Info.FFDiag(E); 3854 return false; 3855 } 3856 Value = NewVal.getInt(); 3857 return true; 3858 } 3859 bool found(APFloat &Value, QualType SubobjType) { 3860 if (!checkConst(SubobjType)) 3861 return false; 3862 Value = NewVal.getFloat(); 3863 return true; 3864 } 3865 }; 3866 } // end anonymous namespace 3867 3868 const AccessKinds ModifySubobjectHandler::AccessKind; 3869 3870 /// Update the designated sub-object of an rvalue to the given value. 3871 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3872 const CompleteObject &Obj, 3873 const SubobjectDesignator &Sub, 3874 APValue &NewVal) { 3875 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3876 return findSubobject(Info, E, Obj, Sub, Handler); 3877 } 3878 3879 /// Find the position where two subobject designators diverge, or equivalently 3880 /// the length of the common initial subsequence. 3881 static unsigned FindDesignatorMismatch(QualType ObjType, 3882 const SubobjectDesignator &A, 3883 const SubobjectDesignator &B, 3884 bool &WasArrayIndex) { 3885 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3886 for (/**/; I != N; ++I) { 3887 if (!ObjType.isNull() && 3888 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3889 // Next subobject is an array element. 3890 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3891 WasArrayIndex = true; 3892 return I; 3893 } 3894 if (ObjType->isAnyComplexType()) 3895 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3896 else 3897 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3898 } else { 3899 if (A.Entries[I].getAsBaseOrMember() != 3900 B.Entries[I].getAsBaseOrMember()) { 3901 WasArrayIndex = false; 3902 return I; 3903 } 3904 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3905 // Next subobject is a field. 3906 ObjType = FD->getType(); 3907 else 3908 // Next subobject is a base class. 3909 ObjType = QualType(); 3910 } 3911 } 3912 WasArrayIndex = false; 3913 return I; 3914 } 3915 3916 /// Determine whether the given subobject designators refer to elements of the 3917 /// same array object. 3918 static bool AreElementsOfSameArray(QualType ObjType, 3919 const SubobjectDesignator &A, 3920 const SubobjectDesignator &B) { 3921 if (A.Entries.size() != B.Entries.size()) 3922 return false; 3923 3924 bool IsArray = A.MostDerivedIsArrayElement; 3925 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3926 // A is a subobject of the array element. 3927 return false; 3928 3929 // If A (and B) designates an array element, the last entry will be the array 3930 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3931 // of length 1' case, and the entire path must match. 3932 bool WasArrayIndex; 3933 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3934 return CommonLength >= A.Entries.size() - IsArray; 3935 } 3936 3937 /// Find the complete object to which an LValue refers. 3938 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3939 AccessKinds AK, const LValue &LVal, 3940 QualType LValType) { 3941 if (LVal.InvalidBase) { 3942 Info.FFDiag(E); 3943 return CompleteObject(); 3944 } 3945 3946 if (!LVal.Base) { 3947 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3948 return CompleteObject(); 3949 } 3950 3951 CallStackFrame *Frame = nullptr; 3952 unsigned Depth = 0; 3953 if (LVal.getLValueCallIndex()) { 3954 std::tie(Frame, Depth) = 3955 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3956 if (!Frame) { 3957 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3958 << AK << LVal.Base.is<const ValueDecl*>(); 3959 NoteLValueLocation(Info, LVal.Base); 3960 return CompleteObject(); 3961 } 3962 } 3963 3964 bool IsAccess = isAnyAccess(AK); 3965 3966 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3967 // is not a constant expression (even if the object is non-volatile). We also 3968 // apply this rule to C++98, in order to conform to the expected 'volatile' 3969 // semantics. 3970 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3971 if (Info.getLangOpts().CPlusPlus) 3972 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3973 << AK << LValType; 3974 else 3975 Info.FFDiag(E); 3976 return CompleteObject(); 3977 } 3978 3979 // Compute value storage location and type of base object. 3980 APValue *BaseVal = nullptr; 3981 QualType BaseType = getType(LVal.Base); 3982 3983 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3984 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3985 // This is the object whose initializer we're evaluating, so its lifetime 3986 // started in the current evaluation. 3987 BaseVal = Info.EvaluatingDeclValue; 3988 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3989 // Allow reading from a GUID declaration. 3990 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3991 if (isModification(AK)) { 3992 // All the remaining cases do not permit modification of the object. 3993 Info.FFDiag(E, diag::note_constexpr_modify_global); 3994 return CompleteObject(); 3995 } 3996 APValue &V = GD->getAsAPValue(); 3997 if (V.isAbsent()) { 3998 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3999 << GD->getType(); 4000 return CompleteObject(); 4001 } 4002 return CompleteObject(LVal.Base, &V, GD->getType()); 4003 } 4004 4005 // Allow reading from template parameter objects. 4006 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4007 if (isModification(AK)) { 4008 Info.FFDiag(E, diag::note_constexpr_modify_global); 4009 return CompleteObject(); 4010 } 4011 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4012 TPO->getType()); 4013 } 4014 4015 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4016 // In C++11, constexpr, non-volatile variables initialized with constant 4017 // expressions are constant expressions too. Inside constexpr functions, 4018 // parameters are constant expressions even if they're non-const. 4019 // In C++1y, objects local to a constant expression (those with a Frame) are 4020 // both readable and writable inside constant expressions. 4021 // In C, such things can also be folded, although they are not ICEs. 4022 const VarDecl *VD = dyn_cast<VarDecl>(D); 4023 if (VD) { 4024 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4025 VD = VDef; 4026 } 4027 if (!VD || VD->isInvalidDecl()) { 4028 Info.FFDiag(E); 4029 return CompleteObject(); 4030 } 4031 4032 bool IsConstant = BaseType.isConstant(Info.Ctx); 4033 4034 // Unless we're looking at a local variable or argument in a constexpr call, 4035 // the variable we're reading must be const. 4036 if (!Frame) { 4037 if (IsAccess && isa<ParmVarDecl>(VD)) { 4038 // Access of a parameter that's not associated with a frame isn't going 4039 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4040 // suitable diagnostic. 4041 } else if (Info.getLangOpts().CPlusPlus14 && 4042 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4043 // OK, we can read and modify an object if we're in the process of 4044 // evaluating its initializer, because its lifetime began in this 4045 // evaluation. 4046 } else if (isModification(AK)) { 4047 // All the remaining cases do not permit modification of the object. 4048 Info.FFDiag(E, diag::note_constexpr_modify_global); 4049 return CompleteObject(); 4050 } else if (VD->isConstexpr()) { 4051 // OK, we can read this variable. 4052 } else if (BaseType->isIntegralOrEnumerationType()) { 4053 if (!IsConstant) { 4054 if (!IsAccess) 4055 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4056 if (Info.getLangOpts().CPlusPlus) { 4057 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4058 Info.Note(VD->getLocation(), diag::note_declared_at); 4059 } else { 4060 Info.FFDiag(E); 4061 } 4062 return CompleteObject(); 4063 } 4064 } else if (!IsAccess) { 4065 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4066 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4067 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4068 // This variable might end up being constexpr. Don't diagnose it yet. 4069 } else if (IsConstant) { 4070 // Keep evaluating to see what we can do. In particular, we support 4071 // folding of const floating-point types, in order to make static const 4072 // data members of such types (supported as an extension) more useful. 4073 if (Info.getLangOpts().CPlusPlus) { 4074 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4075 ? diag::note_constexpr_ltor_non_constexpr 4076 : diag::note_constexpr_ltor_non_integral, 1) 4077 << VD << BaseType; 4078 Info.Note(VD->getLocation(), diag::note_declared_at); 4079 } else { 4080 Info.CCEDiag(E); 4081 } 4082 } else { 4083 // Never allow reading a non-const value. 4084 if (Info.getLangOpts().CPlusPlus) { 4085 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4086 ? diag::note_constexpr_ltor_non_constexpr 4087 : diag::note_constexpr_ltor_non_integral, 1) 4088 << VD << BaseType; 4089 Info.Note(VD->getLocation(), diag::note_declared_at); 4090 } else { 4091 Info.FFDiag(E); 4092 } 4093 return CompleteObject(); 4094 } 4095 } 4096 4097 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4098 return CompleteObject(); 4099 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4100 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4101 if (!Alloc) { 4102 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4103 return CompleteObject(); 4104 } 4105 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4106 LVal.Base.getDynamicAllocType()); 4107 } else { 4108 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4109 4110 if (!Frame) { 4111 if (const MaterializeTemporaryExpr *MTE = 4112 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4113 assert(MTE->getStorageDuration() == SD_Static && 4114 "should have a frame for a non-global materialized temporary"); 4115 4116 // C++20 [expr.const]p4: [DR2126] 4117 // An object or reference is usable in constant expressions if it is 4118 // - a temporary object of non-volatile const-qualified literal type 4119 // whose lifetime is extended to that of a variable that is usable 4120 // in constant expressions 4121 // 4122 // C++20 [expr.const]p5: 4123 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4124 // - a non-volatile glvalue that refers to an object that is usable 4125 // in constant expressions, or 4126 // - a non-volatile glvalue of literal type that refers to a 4127 // non-volatile object whose lifetime began within the evaluation 4128 // of E; 4129 // 4130 // C++11 misses the 'began within the evaluation of e' check and 4131 // instead allows all temporaries, including things like: 4132 // int &&r = 1; 4133 // int x = ++r; 4134 // constexpr int k = r; 4135 // Therefore we use the C++14-onwards rules in C++11 too. 4136 // 4137 // Note that temporaries whose lifetimes began while evaluating a 4138 // variable's constructor are not usable while evaluating the 4139 // corresponding destructor, not even if they're of const-qualified 4140 // types. 4141 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4142 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4143 if (!IsAccess) 4144 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4145 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4146 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4147 return CompleteObject(); 4148 } 4149 4150 BaseVal = MTE->getOrCreateValue(false); 4151 assert(BaseVal && "got reference to unevaluated temporary"); 4152 } else { 4153 if (!IsAccess) 4154 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4155 APValue Val; 4156 LVal.moveInto(Val); 4157 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4158 << AK 4159 << Val.getAsString(Info.Ctx, 4160 Info.Ctx.getLValueReferenceType(LValType)); 4161 NoteLValueLocation(Info, LVal.Base); 4162 return CompleteObject(); 4163 } 4164 } else { 4165 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4166 assert(BaseVal && "missing value for temporary"); 4167 } 4168 } 4169 4170 // In C++14, we can't safely access any mutable state when we might be 4171 // evaluating after an unmodeled side effect. Parameters are modeled as state 4172 // in the caller, but aren't visible once the call returns, so they can be 4173 // modified in a speculatively-evaluated call. 4174 // 4175 // FIXME: Not all local state is mutable. Allow local constant subobjects 4176 // to be read here (but take care with 'mutable' fields). 4177 unsigned VisibleDepth = Depth; 4178 if (llvm::isa_and_nonnull<ParmVarDecl>( 4179 LVal.Base.dyn_cast<const ValueDecl *>())) 4180 ++VisibleDepth; 4181 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4182 Info.EvalStatus.HasSideEffects) || 4183 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4184 return CompleteObject(); 4185 4186 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4187 } 4188 4189 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4190 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4191 /// glvalue referred to by an entity of reference type. 4192 /// 4193 /// \param Info - Information about the ongoing evaluation. 4194 /// \param Conv - The expression for which we are performing the conversion. 4195 /// Used for diagnostics. 4196 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4197 /// case of a non-class type). 4198 /// \param LVal - The glvalue on which we are attempting to perform this action. 4199 /// \param RVal - The produced value will be placed here. 4200 /// \param WantObjectRepresentation - If true, we're looking for the object 4201 /// representation rather than the value, and in particular, 4202 /// there is no requirement that the result be fully initialized. 4203 static bool 4204 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4205 const LValue &LVal, APValue &RVal, 4206 bool WantObjectRepresentation = false) { 4207 if (LVal.Designator.Invalid) 4208 return false; 4209 4210 // Check for special cases where there is no existing APValue to look at. 4211 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4212 4213 AccessKinds AK = 4214 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4215 4216 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4217 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4218 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4219 // initializer until now for such expressions. Such an expression can't be 4220 // an ICE in C, so this only matters for fold. 4221 if (Type.isVolatileQualified()) { 4222 Info.FFDiag(Conv); 4223 return false; 4224 } 4225 APValue Lit; 4226 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4227 return false; 4228 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4229 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4230 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4231 // Special-case character extraction so we don't have to construct an 4232 // APValue for the whole string. 4233 assert(LVal.Designator.Entries.size() <= 1 && 4234 "Can only read characters from string literals"); 4235 if (LVal.Designator.Entries.empty()) { 4236 // Fail for now for LValue to RValue conversion of an array. 4237 // (This shouldn't show up in C/C++, but it could be triggered by a 4238 // weird EvaluateAsRValue call from a tool.) 4239 Info.FFDiag(Conv); 4240 return false; 4241 } 4242 if (LVal.Designator.isOnePastTheEnd()) { 4243 if (Info.getLangOpts().CPlusPlus11) 4244 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4245 else 4246 Info.FFDiag(Conv); 4247 return false; 4248 } 4249 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4250 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4251 return true; 4252 } 4253 } 4254 4255 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4256 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4257 } 4258 4259 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4260 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4261 QualType LValType, APValue &Val) { 4262 if (LVal.Designator.Invalid) 4263 return false; 4264 4265 if (!Info.getLangOpts().CPlusPlus14) { 4266 Info.FFDiag(E); 4267 return false; 4268 } 4269 4270 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4271 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4272 } 4273 4274 namespace { 4275 struct CompoundAssignSubobjectHandler { 4276 EvalInfo &Info; 4277 const CompoundAssignOperator *E; 4278 QualType PromotedLHSType; 4279 BinaryOperatorKind Opcode; 4280 const APValue &RHS; 4281 4282 static const AccessKinds AccessKind = AK_Assign; 4283 4284 typedef bool result_type; 4285 4286 bool checkConst(QualType QT) { 4287 // Assigning to a const object has undefined behavior. 4288 if (QT.isConstQualified()) { 4289 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4290 return false; 4291 } 4292 return true; 4293 } 4294 4295 bool failed() { return false; } 4296 bool found(APValue &Subobj, QualType SubobjType) { 4297 switch (Subobj.getKind()) { 4298 case APValue::Int: 4299 return found(Subobj.getInt(), SubobjType); 4300 case APValue::Float: 4301 return found(Subobj.getFloat(), SubobjType); 4302 case APValue::ComplexInt: 4303 case APValue::ComplexFloat: 4304 // FIXME: Implement complex compound assignment. 4305 Info.FFDiag(E); 4306 return false; 4307 case APValue::LValue: 4308 return foundPointer(Subobj, SubobjType); 4309 case APValue::Vector: 4310 return foundVector(Subobj, SubobjType); 4311 default: 4312 // FIXME: can this happen? 4313 Info.FFDiag(E); 4314 return false; 4315 } 4316 } 4317 4318 bool foundVector(APValue &Value, QualType SubobjType) { 4319 if (!checkConst(SubobjType)) 4320 return false; 4321 4322 if (!SubobjType->isVectorType()) { 4323 Info.FFDiag(E); 4324 return false; 4325 } 4326 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4327 } 4328 4329 bool found(APSInt &Value, QualType SubobjType) { 4330 if (!checkConst(SubobjType)) 4331 return false; 4332 4333 if (!SubobjType->isIntegerType()) { 4334 // We don't support compound assignment on integer-cast-to-pointer 4335 // values. 4336 Info.FFDiag(E); 4337 return false; 4338 } 4339 4340 if (RHS.isInt()) { 4341 APSInt LHS = 4342 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4343 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4344 return false; 4345 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4346 return true; 4347 } else if (RHS.isFloat()) { 4348 const FPOptions FPO = E->getFPFeaturesInEffect( 4349 Info.Ctx.getLangOpts()); 4350 APFloat FValue(0.0); 4351 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4352 PromotedLHSType, FValue) && 4353 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4354 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4355 Value); 4356 } 4357 4358 Info.FFDiag(E); 4359 return false; 4360 } 4361 bool found(APFloat &Value, QualType SubobjType) { 4362 return checkConst(SubobjType) && 4363 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4364 Value) && 4365 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4366 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4367 } 4368 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4369 if (!checkConst(SubobjType)) 4370 return false; 4371 4372 QualType PointeeType; 4373 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4374 PointeeType = PT->getPointeeType(); 4375 4376 if (PointeeType.isNull() || !RHS.isInt() || 4377 (Opcode != BO_Add && Opcode != BO_Sub)) { 4378 Info.FFDiag(E); 4379 return false; 4380 } 4381 4382 APSInt Offset = RHS.getInt(); 4383 if (Opcode == BO_Sub) 4384 negateAsSigned(Offset); 4385 4386 LValue LVal; 4387 LVal.setFrom(Info.Ctx, Subobj); 4388 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4389 return false; 4390 LVal.moveInto(Subobj); 4391 return true; 4392 } 4393 }; 4394 } // end anonymous namespace 4395 4396 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4397 4398 /// Perform a compound assignment of LVal <op>= RVal. 4399 static bool handleCompoundAssignment(EvalInfo &Info, 4400 const CompoundAssignOperator *E, 4401 const LValue &LVal, QualType LValType, 4402 QualType PromotedLValType, 4403 BinaryOperatorKind Opcode, 4404 const APValue &RVal) { 4405 if (LVal.Designator.Invalid) 4406 return false; 4407 4408 if (!Info.getLangOpts().CPlusPlus14) { 4409 Info.FFDiag(E); 4410 return false; 4411 } 4412 4413 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4414 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4415 RVal }; 4416 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4417 } 4418 4419 namespace { 4420 struct IncDecSubobjectHandler { 4421 EvalInfo &Info; 4422 const UnaryOperator *E; 4423 AccessKinds AccessKind; 4424 APValue *Old; 4425 4426 typedef bool result_type; 4427 4428 bool checkConst(QualType QT) { 4429 // Assigning to a const object has undefined behavior. 4430 if (QT.isConstQualified()) { 4431 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4432 return false; 4433 } 4434 return true; 4435 } 4436 4437 bool failed() { return false; } 4438 bool found(APValue &Subobj, QualType SubobjType) { 4439 // Stash the old value. Also clear Old, so we don't clobber it later 4440 // if we're post-incrementing a complex. 4441 if (Old) { 4442 *Old = Subobj; 4443 Old = nullptr; 4444 } 4445 4446 switch (Subobj.getKind()) { 4447 case APValue::Int: 4448 return found(Subobj.getInt(), SubobjType); 4449 case APValue::Float: 4450 return found(Subobj.getFloat(), SubobjType); 4451 case APValue::ComplexInt: 4452 return found(Subobj.getComplexIntReal(), 4453 SubobjType->castAs<ComplexType>()->getElementType() 4454 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4455 case APValue::ComplexFloat: 4456 return found(Subobj.getComplexFloatReal(), 4457 SubobjType->castAs<ComplexType>()->getElementType() 4458 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4459 case APValue::LValue: 4460 return foundPointer(Subobj, SubobjType); 4461 default: 4462 // FIXME: can this happen? 4463 Info.FFDiag(E); 4464 return false; 4465 } 4466 } 4467 bool found(APSInt &Value, QualType SubobjType) { 4468 if (!checkConst(SubobjType)) 4469 return false; 4470 4471 if (!SubobjType->isIntegerType()) { 4472 // We don't support increment / decrement on integer-cast-to-pointer 4473 // values. 4474 Info.FFDiag(E); 4475 return false; 4476 } 4477 4478 if (Old) *Old = APValue(Value); 4479 4480 // bool arithmetic promotes to int, and the conversion back to bool 4481 // doesn't reduce mod 2^n, so special-case it. 4482 if (SubobjType->isBooleanType()) { 4483 if (AccessKind == AK_Increment) 4484 Value = 1; 4485 else 4486 Value = !Value; 4487 return true; 4488 } 4489 4490 bool WasNegative = Value.isNegative(); 4491 if (AccessKind == AK_Increment) { 4492 ++Value; 4493 4494 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4495 APSInt ActualValue(Value, /*IsUnsigned*/true); 4496 return HandleOverflow(Info, E, ActualValue, SubobjType); 4497 } 4498 } else { 4499 --Value; 4500 4501 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4502 unsigned BitWidth = Value.getBitWidth(); 4503 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4504 ActualValue.setBit(BitWidth); 4505 return HandleOverflow(Info, E, ActualValue, SubobjType); 4506 } 4507 } 4508 return true; 4509 } 4510 bool found(APFloat &Value, QualType SubobjType) { 4511 if (!checkConst(SubobjType)) 4512 return false; 4513 4514 if (Old) *Old = APValue(Value); 4515 4516 APFloat One(Value.getSemantics(), 1); 4517 if (AccessKind == AK_Increment) 4518 Value.add(One, APFloat::rmNearestTiesToEven); 4519 else 4520 Value.subtract(One, APFloat::rmNearestTiesToEven); 4521 return true; 4522 } 4523 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4524 if (!checkConst(SubobjType)) 4525 return false; 4526 4527 QualType PointeeType; 4528 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4529 PointeeType = PT->getPointeeType(); 4530 else { 4531 Info.FFDiag(E); 4532 return false; 4533 } 4534 4535 LValue LVal; 4536 LVal.setFrom(Info.Ctx, Subobj); 4537 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4538 AccessKind == AK_Increment ? 1 : -1)) 4539 return false; 4540 LVal.moveInto(Subobj); 4541 return true; 4542 } 4543 }; 4544 } // end anonymous namespace 4545 4546 /// Perform an increment or decrement on LVal. 4547 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4548 QualType LValType, bool IsIncrement, APValue *Old) { 4549 if (LVal.Designator.Invalid) 4550 return false; 4551 4552 if (!Info.getLangOpts().CPlusPlus14) { 4553 Info.FFDiag(E); 4554 return false; 4555 } 4556 4557 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4558 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4559 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4560 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4561 } 4562 4563 /// Build an lvalue for the object argument of a member function call. 4564 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4565 LValue &This) { 4566 if (Object->getType()->isPointerType() && Object->isRValue()) 4567 return EvaluatePointer(Object, This, Info); 4568 4569 if (Object->isGLValue()) 4570 return EvaluateLValue(Object, This, Info); 4571 4572 if (Object->getType()->isLiteralType(Info.Ctx)) 4573 return EvaluateTemporary(Object, This, Info); 4574 4575 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4576 return false; 4577 } 4578 4579 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4580 /// lvalue referring to the result. 4581 /// 4582 /// \param Info - Information about the ongoing evaluation. 4583 /// \param LV - An lvalue referring to the base of the member pointer. 4584 /// \param RHS - The member pointer expression. 4585 /// \param IncludeMember - Specifies whether the member itself is included in 4586 /// the resulting LValue subobject designator. This is not possible when 4587 /// creating a bound member function. 4588 /// \return The field or method declaration to which the member pointer refers, 4589 /// or 0 if evaluation fails. 4590 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4591 QualType LVType, 4592 LValue &LV, 4593 const Expr *RHS, 4594 bool IncludeMember = true) { 4595 MemberPtr MemPtr; 4596 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4597 return nullptr; 4598 4599 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4600 // member value, the behavior is undefined. 4601 if (!MemPtr.getDecl()) { 4602 // FIXME: Specific diagnostic. 4603 Info.FFDiag(RHS); 4604 return nullptr; 4605 } 4606 4607 if (MemPtr.isDerivedMember()) { 4608 // This is a member of some derived class. Truncate LV appropriately. 4609 // The end of the derived-to-base path for the base object must match the 4610 // derived-to-base path for the member pointer. 4611 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4612 LV.Designator.Entries.size()) { 4613 Info.FFDiag(RHS); 4614 return nullptr; 4615 } 4616 unsigned PathLengthToMember = 4617 LV.Designator.Entries.size() - MemPtr.Path.size(); 4618 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4619 const CXXRecordDecl *LVDecl = getAsBaseClass( 4620 LV.Designator.Entries[PathLengthToMember + I]); 4621 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4622 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4623 Info.FFDiag(RHS); 4624 return nullptr; 4625 } 4626 } 4627 4628 // Truncate the lvalue to the appropriate derived class. 4629 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4630 PathLengthToMember)) 4631 return nullptr; 4632 } else if (!MemPtr.Path.empty()) { 4633 // Extend the LValue path with the member pointer's path. 4634 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4635 MemPtr.Path.size() + IncludeMember); 4636 4637 // Walk down to the appropriate base class. 4638 if (const PointerType *PT = LVType->getAs<PointerType>()) 4639 LVType = PT->getPointeeType(); 4640 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4641 assert(RD && "member pointer access on non-class-type expression"); 4642 // The first class in the path is that of the lvalue. 4643 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4644 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4645 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4646 return nullptr; 4647 RD = Base; 4648 } 4649 // Finally cast to the class containing the member. 4650 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4651 MemPtr.getContainingRecord())) 4652 return nullptr; 4653 } 4654 4655 // Add the member. Note that we cannot build bound member functions here. 4656 if (IncludeMember) { 4657 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4658 if (!HandleLValueMember(Info, RHS, LV, FD)) 4659 return nullptr; 4660 } else if (const IndirectFieldDecl *IFD = 4661 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4662 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4663 return nullptr; 4664 } else { 4665 llvm_unreachable("can't construct reference to bound member function"); 4666 } 4667 } 4668 4669 return MemPtr.getDecl(); 4670 } 4671 4672 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4673 const BinaryOperator *BO, 4674 LValue &LV, 4675 bool IncludeMember = true) { 4676 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4677 4678 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4679 if (Info.noteFailure()) { 4680 MemberPtr MemPtr; 4681 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4682 } 4683 return nullptr; 4684 } 4685 4686 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4687 BO->getRHS(), IncludeMember); 4688 } 4689 4690 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4691 /// the provided lvalue, which currently refers to the base object. 4692 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4693 LValue &Result) { 4694 SubobjectDesignator &D = Result.Designator; 4695 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4696 return false; 4697 4698 QualType TargetQT = E->getType(); 4699 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4700 TargetQT = PT->getPointeeType(); 4701 4702 // Check this cast lands within the final derived-to-base subobject path. 4703 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4704 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4705 << D.MostDerivedType << TargetQT; 4706 return false; 4707 } 4708 4709 // Check the type of the final cast. We don't need to check the path, 4710 // since a cast can only be formed if the path is unique. 4711 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4712 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4713 const CXXRecordDecl *FinalType; 4714 if (NewEntriesSize == D.MostDerivedPathLength) 4715 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4716 else 4717 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4718 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4719 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4720 << D.MostDerivedType << TargetQT; 4721 return false; 4722 } 4723 4724 // Truncate the lvalue to the appropriate derived class. 4725 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4726 } 4727 4728 /// Get the value to use for a default-initialized object of type T. 4729 /// Return false if it encounters something invalid. 4730 static bool getDefaultInitValue(QualType T, APValue &Result) { 4731 bool Success = true; 4732 if (auto *RD = T->getAsCXXRecordDecl()) { 4733 if (RD->isInvalidDecl()) { 4734 Result = APValue(); 4735 return false; 4736 } 4737 if (RD->isUnion()) { 4738 Result = APValue((const FieldDecl *)nullptr); 4739 return true; 4740 } 4741 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4742 std::distance(RD->field_begin(), RD->field_end())); 4743 4744 unsigned Index = 0; 4745 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4746 End = RD->bases_end(); 4747 I != End; ++I, ++Index) 4748 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4749 4750 for (const auto *I : RD->fields()) { 4751 if (I->isUnnamedBitfield()) 4752 continue; 4753 Success &= getDefaultInitValue(I->getType(), 4754 Result.getStructField(I->getFieldIndex())); 4755 } 4756 return Success; 4757 } 4758 4759 if (auto *AT = 4760 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4761 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4762 if (Result.hasArrayFiller()) 4763 Success &= 4764 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4765 4766 return Success; 4767 } 4768 4769 Result = APValue::IndeterminateValue(); 4770 return true; 4771 } 4772 4773 namespace { 4774 enum EvalStmtResult { 4775 /// Evaluation failed. 4776 ESR_Failed, 4777 /// Hit a 'return' statement. 4778 ESR_Returned, 4779 /// Evaluation succeeded. 4780 ESR_Succeeded, 4781 /// Hit a 'continue' statement. 4782 ESR_Continue, 4783 /// Hit a 'break' statement. 4784 ESR_Break, 4785 /// Still scanning for 'case' or 'default' statement. 4786 ESR_CaseNotFound 4787 }; 4788 } 4789 4790 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4791 // We don't need to evaluate the initializer for a static local. 4792 if (!VD->hasLocalStorage()) 4793 return true; 4794 4795 LValue Result; 4796 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4797 ScopeKind::Block, Result); 4798 4799 const Expr *InitE = VD->getInit(); 4800 if (!InitE) { 4801 if (VD->getType()->isDependentType()) 4802 return Info.noteSideEffect(); 4803 return getDefaultInitValue(VD->getType(), Val); 4804 } 4805 if (InitE->isValueDependent()) 4806 return false; 4807 4808 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4809 // Wipe out any partially-computed value, to allow tracking that this 4810 // evaluation failed. 4811 Val = APValue(); 4812 return false; 4813 } 4814 4815 return true; 4816 } 4817 4818 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4819 bool OK = true; 4820 4821 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4822 OK &= EvaluateVarDecl(Info, VD); 4823 4824 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4825 for (auto *BD : DD->bindings()) 4826 if (auto *VD = BD->getHoldingVar()) 4827 OK &= EvaluateDecl(Info, VD); 4828 4829 return OK; 4830 } 4831 4832 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4833 assert(E->isValueDependent()); 4834 if (Info.noteSideEffect()) 4835 return true; 4836 assert(E->containsErrors() && "valid value-dependent expression should never " 4837 "reach invalid code path."); 4838 return false; 4839 } 4840 4841 /// Evaluate a condition (either a variable declaration or an expression). 4842 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4843 const Expr *Cond, bool &Result) { 4844 if (Cond->isValueDependent()) 4845 return false; 4846 FullExpressionRAII Scope(Info); 4847 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4848 return false; 4849 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4850 return false; 4851 return Scope.destroy(); 4852 } 4853 4854 namespace { 4855 /// A location where the result (returned value) of evaluating a 4856 /// statement should be stored. 4857 struct StmtResult { 4858 /// The APValue that should be filled in with the returned value. 4859 APValue &Value; 4860 /// The location containing the result, if any (used to support RVO). 4861 const LValue *Slot; 4862 }; 4863 4864 struct TempVersionRAII { 4865 CallStackFrame &Frame; 4866 4867 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4868 Frame.pushTempVersion(); 4869 } 4870 4871 ~TempVersionRAII() { 4872 Frame.popTempVersion(); 4873 } 4874 }; 4875 4876 } 4877 4878 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4879 const Stmt *S, 4880 const SwitchCase *SC = nullptr); 4881 4882 /// Evaluate the body of a loop, and translate the result as appropriate. 4883 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4884 const Stmt *Body, 4885 const SwitchCase *Case = nullptr) { 4886 BlockScopeRAII Scope(Info); 4887 4888 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4889 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4890 ESR = ESR_Failed; 4891 4892 switch (ESR) { 4893 case ESR_Break: 4894 return ESR_Succeeded; 4895 case ESR_Succeeded: 4896 case ESR_Continue: 4897 return ESR_Continue; 4898 case ESR_Failed: 4899 case ESR_Returned: 4900 case ESR_CaseNotFound: 4901 return ESR; 4902 } 4903 llvm_unreachable("Invalid EvalStmtResult!"); 4904 } 4905 4906 /// Evaluate a switch statement. 4907 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4908 const SwitchStmt *SS) { 4909 BlockScopeRAII Scope(Info); 4910 4911 // Evaluate the switch condition. 4912 APSInt Value; 4913 { 4914 if (const Stmt *Init = SS->getInit()) { 4915 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4916 if (ESR != ESR_Succeeded) { 4917 if (ESR != ESR_Failed && !Scope.destroy()) 4918 ESR = ESR_Failed; 4919 return ESR; 4920 } 4921 } 4922 4923 FullExpressionRAII CondScope(Info); 4924 if (SS->getConditionVariable() && 4925 !EvaluateDecl(Info, SS->getConditionVariable())) 4926 return ESR_Failed; 4927 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4928 return ESR_Failed; 4929 if (!CondScope.destroy()) 4930 return ESR_Failed; 4931 } 4932 4933 // Find the switch case corresponding to the value of the condition. 4934 // FIXME: Cache this lookup. 4935 const SwitchCase *Found = nullptr; 4936 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4937 SC = SC->getNextSwitchCase()) { 4938 if (isa<DefaultStmt>(SC)) { 4939 Found = SC; 4940 continue; 4941 } 4942 4943 const CaseStmt *CS = cast<CaseStmt>(SC); 4944 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4945 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4946 : LHS; 4947 if (LHS <= Value && Value <= RHS) { 4948 Found = SC; 4949 break; 4950 } 4951 } 4952 4953 if (!Found) 4954 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4955 4956 // Search the switch body for the switch case and evaluate it from there. 4957 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4958 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4959 return ESR_Failed; 4960 4961 switch (ESR) { 4962 case ESR_Break: 4963 return ESR_Succeeded; 4964 case ESR_Succeeded: 4965 case ESR_Continue: 4966 case ESR_Failed: 4967 case ESR_Returned: 4968 return ESR; 4969 case ESR_CaseNotFound: 4970 // This can only happen if the switch case is nested within a statement 4971 // expression. We have no intention of supporting that. 4972 Info.FFDiag(Found->getBeginLoc(), 4973 diag::note_constexpr_stmt_expr_unsupported); 4974 return ESR_Failed; 4975 } 4976 llvm_unreachable("Invalid EvalStmtResult!"); 4977 } 4978 4979 // Evaluate a statement. 4980 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4981 const Stmt *S, const SwitchCase *Case) { 4982 if (!Info.nextStep(S)) 4983 return ESR_Failed; 4984 4985 // If we're hunting down a 'case' or 'default' label, recurse through 4986 // substatements until we hit the label. 4987 if (Case) { 4988 switch (S->getStmtClass()) { 4989 case Stmt::CompoundStmtClass: 4990 // FIXME: Precompute which substatement of a compound statement we 4991 // would jump to, and go straight there rather than performing a 4992 // linear scan each time. 4993 case Stmt::LabelStmtClass: 4994 case Stmt::AttributedStmtClass: 4995 case Stmt::DoStmtClass: 4996 break; 4997 4998 case Stmt::CaseStmtClass: 4999 case Stmt::DefaultStmtClass: 5000 if (Case == S) 5001 Case = nullptr; 5002 break; 5003 5004 case Stmt::IfStmtClass: { 5005 // FIXME: Precompute which side of an 'if' we would jump to, and go 5006 // straight there rather than scanning both sides. 5007 const IfStmt *IS = cast<IfStmt>(S); 5008 5009 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5010 // preceded by our switch label. 5011 BlockScopeRAII Scope(Info); 5012 5013 // Step into the init statement in case it brings an (uninitialized) 5014 // variable into scope. 5015 if (const Stmt *Init = IS->getInit()) { 5016 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5017 if (ESR != ESR_CaseNotFound) { 5018 assert(ESR != ESR_Succeeded); 5019 return ESR; 5020 } 5021 } 5022 5023 // Condition variable must be initialized if it exists. 5024 // FIXME: We can skip evaluating the body if there's a condition 5025 // variable, as there can't be any case labels within it. 5026 // (The same is true for 'for' statements.) 5027 5028 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5029 if (ESR == ESR_Failed) 5030 return ESR; 5031 if (ESR != ESR_CaseNotFound) 5032 return Scope.destroy() ? ESR : ESR_Failed; 5033 if (!IS->getElse()) 5034 return ESR_CaseNotFound; 5035 5036 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5037 if (ESR == ESR_Failed) 5038 return ESR; 5039 if (ESR != ESR_CaseNotFound) 5040 return Scope.destroy() ? ESR : ESR_Failed; 5041 return ESR_CaseNotFound; 5042 } 5043 5044 case Stmt::WhileStmtClass: { 5045 EvalStmtResult ESR = 5046 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5047 if (ESR != ESR_Continue) 5048 return ESR; 5049 break; 5050 } 5051 5052 case Stmt::ForStmtClass: { 5053 const ForStmt *FS = cast<ForStmt>(S); 5054 BlockScopeRAII Scope(Info); 5055 5056 // Step into the init statement in case it brings an (uninitialized) 5057 // variable into scope. 5058 if (const Stmt *Init = FS->getInit()) { 5059 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5060 if (ESR != ESR_CaseNotFound) { 5061 assert(ESR != ESR_Succeeded); 5062 return ESR; 5063 } 5064 } 5065 5066 EvalStmtResult ESR = 5067 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5068 if (ESR != ESR_Continue) 5069 return ESR; 5070 if (const auto *Inc = FS->getInc()) { 5071 if (Inc->isValueDependent()) { 5072 if (!EvaluateDependentExpr(Inc, Info)) 5073 return ESR_Failed; 5074 } else { 5075 FullExpressionRAII IncScope(Info); 5076 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5077 return ESR_Failed; 5078 } 5079 } 5080 break; 5081 } 5082 5083 case Stmt::DeclStmtClass: { 5084 // Start the lifetime of any uninitialized variables we encounter. They 5085 // might be used by the selected branch of the switch. 5086 const DeclStmt *DS = cast<DeclStmt>(S); 5087 for (const auto *D : DS->decls()) { 5088 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5089 if (VD->hasLocalStorage() && !VD->getInit()) 5090 if (!EvaluateVarDecl(Info, VD)) 5091 return ESR_Failed; 5092 // FIXME: If the variable has initialization that can't be jumped 5093 // over, bail out of any immediately-surrounding compound-statement 5094 // too. There can't be any case labels here. 5095 } 5096 } 5097 return ESR_CaseNotFound; 5098 } 5099 5100 default: 5101 return ESR_CaseNotFound; 5102 } 5103 } 5104 5105 switch (S->getStmtClass()) { 5106 default: 5107 if (const Expr *E = dyn_cast<Expr>(S)) { 5108 if (E->isValueDependent()) { 5109 if (!EvaluateDependentExpr(E, Info)) 5110 return ESR_Failed; 5111 } else { 5112 // Don't bother evaluating beyond an expression-statement which couldn't 5113 // be evaluated. 5114 // FIXME: Do we need the FullExpressionRAII object here? 5115 // VisitExprWithCleanups should create one when necessary. 5116 FullExpressionRAII Scope(Info); 5117 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5118 return ESR_Failed; 5119 } 5120 return ESR_Succeeded; 5121 } 5122 5123 Info.FFDiag(S->getBeginLoc()); 5124 return ESR_Failed; 5125 5126 case Stmt::NullStmtClass: 5127 return ESR_Succeeded; 5128 5129 case Stmt::DeclStmtClass: { 5130 const DeclStmt *DS = cast<DeclStmt>(S); 5131 for (const auto *D : DS->decls()) { 5132 // Each declaration initialization is its own full-expression. 5133 FullExpressionRAII Scope(Info); 5134 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5135 return ESR_Failed; 5136 if (!Scope.destroy()) 5137 return ESR_Failed; 5138 } 5139 return ESR_Succeeded; 5140 } 5141 5142 case Stmt::ReturnStmtClass: { 5143 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5144 FullExpressionRAII Scope(Info); 5145 if (RetExpr && RetExpr->isValueDependent()) { 5146 EvaluateDependentExpr(RetExpr, Info); 5147 // We know we returned, but we don't know what the value is. 5148 return ESR_Failed; 5149 } 5150 if (RetExpr && 5151 !(Result.Slot 5152 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5153 : Evaluate(Result.Value, Info, RetExpr))) 5154 return ESR_Failed; 5155 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5156 } 5157 5158 case Stmt::CompoundStmtClass: { 5159 BlockScopeRAII Scope(Info); 5160 5161 const CompoundStmt *CS = cast<CompoundStmt>(S); 5162 for (const auto *BI : CS->body()) { 5163 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5164 if (ESR == ESR_Succeeded) 5165 Case = nullptr; 5166 else if (ESR != ESR_CaseNotFound) { 5167 if (ESR != ESR_Failed && !Scope.destroy()) 5168 return ESR_Failed; 5169 return ESR; 5170 } 5171 } 5172 if (Case) 5173 return ESR_CaseNotFound; 5174 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5175 } 5176 5177 case Stmt::IfStmtClass: { 5178 const IfStmt *IS = cast<IfStmt>(S); 5179 5180 // Evaluate the condition, as either a var decl or as an expression. 5181 BlockScopeRAII Scope(Info); 5182 if (const Stmt *Init = IS->getInit()) { 5183 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5184 if (ESR != ESR_Succeeded) { 5185 if (ESR != ESR_Failed && !Scope.destroy()) 5186 return ESR_Failed; 5187 return ESR; 5188 } 5189 } 5190 bool Cond; 5191 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5192 return ESR_Failed; 5193 5194 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5195 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5196 if (ESR != ESR_Succeeded) { 5197 if (ESR != ESR_Failed && !Scope.destroy()) 5198 return ESR_Failed; 5199 return ESR; 5200 } 5201 } 5202 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5203 } 5204 5205 case Stmt::WhileStmtClass: { 5206 const WhileStmt *WS = cast<WhileStmt>(S); 5207 while (true) { 5208 BlockScopeRAII Scope(Info); 5209 bool Continue; 5210 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5211 Continue)) 5212 return ESR_Failed; 5213 if (!Continue) 5214 break; 5215 5216 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5217 if (ESR != ESR_Continue) { 5218 if (ESR != ESR_Failed && !Scope.destroy()) 5219 return ESR_Failed; 5220 return ESR; 5221 } 5222 if (!Scope.destroy()) 5223 return ESR_Failed; 5224 } 5225 return ESR_Succeeded; 5226 } 5227 5228 case Stmt::DoStmtClass: { 5229 const DoStmt *DS = cast<DoStmt>(S); 5230 bool Continue; 5231 do { 5232 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5233 if (ESR != ESR_Continue) 5234 return ESR; 5235 Case = nullptr; 5236 5237 if (DS->getCond()->isValueDependent()) { 5238 EvaluateDependentExpr(DS->getCond(), Info); 5239 // Bailout as we don't know whether to keep going or terminate the loop. 5240 return ESR_Failed; 5241 } 5242 FullExpressionRAII CondScope(Info); 5243 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5244 !CondScope.destroy()) 5245 return ESR_Failed; 5246 } while (Continue); 5247 return ESR_Succeeded; 5248 } 5249 5250 case Stmt::ForStmtClass: { 5251 const ForStmt *FS = cast<ForStmt>(S); 5252 BlockScopeRAII ForScope(Info); 5253 if (FS->getInit()) { 5254 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5255 if (ESR != ESR_Succeeded) { 5256 if (ESR != ESR_Failed && !ForScope.destroy()) 5257 return ESR_Failed; 5258 return ESR; 5259 } 5260 } 5261 while (true) { 5262 BlockScopeRAII IterScope(Info); 5263 bool Continue = true; 5264 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5265 FS->getCond(), Continue)) 5266 return ESR_Failed; 5267 if (!Continue) 5268 break; 5269 5270 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5271 if (ESR != ESR_Continue) { 5272 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5273 return ESR_Failed; 5274 return ESR; 5275 } 5276 5277 if (const auto *Inc = FS->getInc()) { 5278 if (Inc->isValueDependent()) { 5279 if (!EvaluateDependentExpr(Inc, Info)) 5280 return ESR_Failed; 5281 } else { 5282 FullExpressionRAII IncScope(Info); 5283 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5284 return ESR_Failed; 5285 } 5286 } 5287 5288 if (!IterScope.destroy()) 5289 return ESR_Failed; 5290 } 5291 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5292 } 5293 5294 case Stmt::CXXForRangeStmtClass: { 5295 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5296 BlockScopeRAII Scope(Info); 5297 5298 // Evaluate the init-statement if present. 5299 if (FS->getInit()) { 5300 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5301 if (ESR != ESR_Succeeded) { 5302 if (ESR != ESR_Failed && !Scope.destroy()) 5303 return ESR_Failed; 5304 return ESR; 5305 } 5306 } 5307 5308 // Initialize the __range variable. 5309 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5310 if (ESR != ESR_Succeeded) { 5311 if (ESR != ESR_Failed && !Scope.destroy()) 5312 return ESR_Failed; 5313 return ESR; 5314 } 5315 5316 // Create the __begin and __end iterators. 5317 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5318 if (ESR != ESR_Succeeded) { 5319 if (ESR != ESR_Failed && !Scope.destroy()) 5320 return ESR_Failed; 5321 return ESR; 5322 } 5323 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5324 if (ESR != ESR_Succeeded) { 5325 if (ESR != ESR_Failed && !Scope.destroy()) 5326 return ESR_Failed; 5327 return ESR; 5328 } 5329 5330 while (true) { 5331 // Condition: __begin != __end. 5332 { 5333 if (FS->getCond()->isValueDependent()) { 5334 EvaluateDependentExpr(FS->getCond(), Info); 5335 // We don't know whether to keep going or terminate the loop. 5336 return ESR_Failed; 5337 } 5338 bool Continue = true; 5339 FullExpressionRAII CondExpr(Info); 5340 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5341 return ESR_Failed; 5342 if (!Continue) 5343 break; 5344 } 5345 5346 // User's variable declaration, initialized by *__begin. 5347 BlockScopeRAII InnerScope(Info); 5348 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5349 if (ESR != ESR_Succeeded) { 5350 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5351 return ESR_Failed; 5352 return ESR; 5353 } 5354 5355 // Loop body. 5356 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5357 if (ESR != ESR_Continue) { 5358 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5359 return ESR_Failed; 5360 return ESR; 5361 } 5362 if (FS->getInc()->isValueDependent()) { 5363 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5364 return ESR_Failed; 5365 } else { 5366 // Increment: ++__begin 5367 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5368 return ESR_Failed; 5369 } 5370 5371 if (!InnerScope.destroy()) 5372 return ESR_Failed; 5373 } 5374 5375 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5376 } 5377 5378 case Stmt::SwitchStmtClass: 5379 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5380 5381 case Stmt::ContinueStmtClass: 5382 return ESR_Continue; 5383 5384 case Stmt::BreakStmtClass: 5385 return ESR_Break; 5386 5387 case Stmt::LabelStmtClass: 5388 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5389 5390 case Stmt::AttributedStmtClass: 5391 // As a general principle, C++11 attributes can be ignored without 5392 // any semantic impact. 5393 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5394 Case); 5395 5396 case Stmt::CaseStmtClass: 5397 case Stmt::DefaultStmtClass: 5398 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5399 case Stmt::CXXTryStmtClass: 5400 // Evaluate try blocks by evaluating all sub statements. 5401 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5402 } 5403 } 5404 5405 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5406 /// default constructor. If so, we'll fold it whether or not it's marked as 5407 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5408 /// so we need special handling. 5409 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5410 const CXXConstructorDecl *CD, 5411 bool IsValueInitialization) { 5412 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5413 return false; 5414 5415 // Value-initialization does not call a trivial default constructor, so such a 5416 // call is a core constant expression whether or not the constructor is 5417 // constexpr. 5418 if (!CD->isConstexpr() && !IsValueInitialization) { 5419 if (Info.getLangOpts().CPlusPlus11) { 5420 // FIXME: If DiagDecl is an implicitly-declared special member function, 5421 // we should be much more explicit about why it's not constexpr. 5422 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5423 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5424 Info.Note(CD->getLocation(), diag::note_declared_at); 5425 } else { 5426 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5427 } 5428 } 5429 return true; 5430 } 5431 5432 /// CheckConstexprFunction - Check that a function can be called in a constant 5433 /// expression. 5434 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5435 const FunctionDecl *Declaration, 5436 const FunctionDecl *Definition, 5437 const Stmt *Body) { 5438 // Potential constant expressions can contain calls to declared, but not yet 5439 // defined, constexpr functions. 5440 if (Info.checkingPotentialConstantExpression() && !Definition && 5441 Declaration->isConstexpr()) 5442 return false; 5443 5444 // Bail out if the function declaration itself is invalid. We will 5445 // have produced a relevant diagnostic while parsing it, so just 5446 // note the problematic sub-expression. 5447 if (Declaration->isInvalidDecl()) { 5448 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5449 return false; 5450 } 5451 5452 // DR1872: An instantiated virtual constexpr function can't be called in a 5453 // constant expression (prior to C++20). We can still constant-fold such a 5454 // call. 5455 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5456 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5457 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5458 5459 if (Definition && Definition->isInvalidDecl()) { 5460 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5461 return false; 5462 } 5463 5464 // Can we evaluate this function call? 5465 if (Definition && Definition->isConstexpr() && Body) 5466 return true; 5467 5468 if (Info.getLangOpts().CPlusPlus11) { 5469 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5470 5471 // If this function is not constexpr because it is an inherited 5472 // non-constexpr constructor, diagnose that directly. 5473 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5474 if (CD && CD->isInheritingConstructor()) { 5475 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5476 if (!Inherited->isConstexpr()) 5477 DiagDecl = CD = Inherited; 5478 } 5479 5480 // FIXME: If DiagDecl is an implicitly-declared special member function 5481 // or an inheriting constructor, we should be much more explicit about why 5482 // it's not constexpr. 5483 if (CD && CD->isInheritingConstructor()) 5484 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5485 << CD->getInheritedConstructor().getConstructor()->getParent(); 5486 else 5487 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5488 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5489 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5490 } else { 5491 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5492 } 5493 return false; 5494 } 5495 5496 namespace { 5497 struct CheckDynamicTypeHandler { 5498 AccessKinds AccessKind; 5499 typedef bool result_type; 5500 bool failed() { return false; } 5501 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5502 bool found(APSInt &Value, QualType SubobjType) { return true; } 5503 bool found(APFloat &Value, QualType SubobjType) { return true; } 5504 }; 5505 } // end anonymous namespace 5506 5507 /// Check that we can access the notional vptr of an object / determine its 5508 /// dynamic type. 5509 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5510 AccessKinds AK, bool Polymorphic) { 5511 if (This.Designator.Invalid) 5512 return false; 5513 5514 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5515 5516 if (!Obj) 5517 return false; 5518 5519 if (!Obj.Value) { 5520 // The object is not usable in constant expressions, so we can't inspect 5521 // its value to see if it's in-lifetime or what the active union members 5522 // are. We can still check for a one-past-the-end lvalue. 5523 if (This.Designator.isOnePastTheEnd() || 5524 This.Designator.isMostDerivedAnUnsizedArray()) { 5525 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5526 ? diag::note_constexpr_access_past_end 5527 : diag::note_constexpr_access_unsized_array) 5528 << AK; 5529 return false; 5530 } else if (Polymorphic) { 5531 // Conservatively refuse to perform a polymorphic operation if we would 5532 // not be able to read a notional 'vptr' value. 5533 APValue Val; 5534 This.moveInto(Val); 5535 QualType StarThisType = 5536 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5537 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5538 << AK << Val.getAsString(Info.Ctx, StarThisType); 5539 return false; 5540 } 5541 return true; 5542 } 5543 5544 CheckDynamicTypeHandler Handler{AK}; 5545 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5546 } 5547 5548 /// Check that the pointee of the 'this' pointer in a member function call is 5549 /// either within its lifetime or in its period of construction or destruction. 5550 static bool 5551 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5552 const LValue &This, 5553 const CXXMethodDecl *NamedMember) { 5554 return checkDynamicType( 5555 Info, E, This, 5556 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5557 } 5558 5559 struct DynamicType { 5560 /// The dynamic class type of the object. 5561 const CXXRecordDecl *Type; 5562 /// The corresponding path length in the lvalue. 5563 unsigned PathLength; 5564 }; 5565 5566 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5567 unsigned PathLength) { 5568 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5569 Designator.Entries.size() && "invalid path length"); 5570 return (PathLength == Designator.MostDerivedPathLength) 5571 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5572 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5573 } 5574 5575 /// Determine the dynamic type of an object. 5576 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5577 LValue &This, AccessKinds AK) { 5578 // If we don't have an lvalue denoting an object of class type, there is no 5579 // meaningful dynamic type. (We consider objects of non-class type to have no 5580 // dynamic type.) 5581 if (!checkDynamicType(Info, E, This, AK, true)) 5582 return None; 5583 5584 // Refuse to compute a dynamic type in the presence of virtual bases. This 5585 // shouldn't happen other than in constant-folding situations, since literal 5586 // types can't have virtual bases. 5587 // 5588 // Note that consumers of DynamicType assume that the type has no virtual 5589 // bases, and will need modifications if this restriction is relaxed. 5590 const CXXRecordDecl *Class = 5591 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5592 if (!Class || Class->getNumVBases()) { 5593 Info.FFDiag(E); 5594 return None; 5595 } 5596 5597 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5598 // binary search here instead. But the overwhelmingly common case is that 5599 // we're not in the middle of a constructor, so it probably doesn't matter 5600 // in practice. 5601 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5602 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5603 PathLength <= Path.size(); ++PathLength) { 5604 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5605 Path.slice(0, PathLength))) { 5606 case ConstructionPhase::Bases: 5607 case ConstructionPhase::DestroyingBases: 5608 // We're constructing or destroying a base class. This is not the dynamic 5609 // type. 5610 break; 5611 5612 case ConstructionPhase::None: 5613 case ConstructionPhase::AfterBases: 5614 case ConstructionPhase::AfterFields: 5615 case ConstructionPhase::Destroying: 5616 // We've finished constructing the base classes and not yet started 5617 // destroying them again, so this is the dynamic type. 5618 return DynamicType{getBaseClassType(This.Designator, PathLength), 5619 PathLength}; 5620 } 5621 } 5622 5623 // CWG issue 1517: we're constructing a base class of the object described by 5624 // 'This', so that object has not yet begun its period of construction and 5625 // any polymorphic operation on it results in undefined behavior. 5626 Info.FFDiag(E); 5627 return None; 5628 } 5629 5630 /// Perform virtual dispatch. 5631 static const CXXMethodDecl *HandleVirtualDispatch( 5632 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5633 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5634 Optional<DynamicType> DynType = ComputeDynamicType( 5635 Info, E, This, 5636 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5637 if (!DynType) 5638 return nullptr; 5639 5640 // Find the final overrider. It must be declared in one of the classes on the 5641 // path from the dynamic type to the static type. 5642 // FIXME: If we ever allow literal types to have virtual base classes, that 5643 // won't be true. 5644 const CXXMethodDecl *Callee = Found; 5645 unsigned PathLength = DynType->PathLength; 5646 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5647 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5648 const CXXMethodDecl *Overrider = 5649 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5650 if (Overrider) { 5651 Callee = Overrider; 5652 break; 5653 } 5654 } 5655 5656 // C++2a [class.abstract]p6: 5657 // the effect of making a virtual call to a pure virtual function [...] is 5658 // undefined 5659 if (Callee->isPure()) { 5660 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5661 Info.Note(Callee->getLocation(), diag::note_declared_at); 5662 return nullptr; 5663 } 5664 5665 // If necessary, walk the rest of the path to determine the sequence of 5666 // covariant adjustment steps to apply. 5667 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5668 Found->getReturnType())) { 5669 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5670 for (unsigned CovariantPathLength = PathLength + 1; 5671 CovariantPathLength != This.Designator.Entries.size(); 5672 ++CovariantPathLength) { 5673 const CXXRecordDecl *NextClass = 5674 getBaseClassType(This.Designator, CovariantPathLength); 5675 const CXXMethodDecl *Next = 5676 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5677 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5678 Next->getReturnType(), CovariantAdjustmentPath.back())) 5679 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5680 } 5681 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5682 CovariantAdjustmentPath.back())) 5683 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5684 } 5685 5686 // Perform 'this' adjustment. 5687 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5688 return nullptr; 5689 5690 return Callee; 5691 } 5692 5693 /// Perform the adjustment from a value returned by a virtual function to 5694 /// a value of the statically expected type, which may be a pointer or 5695 /// reference to a base class of the returned type. 5696 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5697 APValue &Result, 5698 ArrayRef<QualType> Path) { 5699 assert(Result.isLValue() && 5700 "unexpected kind of APValue for covariant return"); 5701 if (Result.isNullPointer()) 5702 return true; 5703 5704 LValue LVal; 5705 LVal.setFrom(Info.Ctx, Result); 5706 5707 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5708 for (unsigned I = 1; I != Path.size(); ++I) { 5709 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5710 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5711 if (OldClass != NewClass && 5712 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5713 return false; 5714 OldClass = NewClass; 5715 } 5716 5717 LVal.moveInto(Result); 5718 return true; 5719 } 5720 5721 /// Determine whether \p Base, which is known to be a direct base class of 5722 /// \p Derived, is a public base class. 5723 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5724 const CXXRecordDecl *Base) { 5725 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5726 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5727 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5728 return BaseSpec.getAccessSpecifier() == AS_public; 5729 } 5730 llvm_unreachable("Base is not a direct base of Derived"); 5731 } 5732 5733 /// Apply the given dynamic cast operation on the provided lvalue. 5734 /// 5735 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5736 /// to find a suitable target subobject. 5737 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5738 LValue &Ptr) { 5739 // We can't do anything with a non-symbolic pointer value. 5740 SubobjectDesignator &D = Ptr.Designator; 5741 if (D.Invalid) 5742 return false; 5743 5744 // C++ [expr.dynamic.cast]p6: 5745 // If v is a null pointer value, the result is a null pointer value. 5746 if (Ptr.isNullPointer() && !E->isGLValue()) 5747 return true; 5748 5749 // For all the other cases, we need the pointer to point to an object within 5750 // its lifetime / period of construction / destruction, and we need to know 5751 // its dynamic type. 5752 Optional<DynamicType> DynType = 5753 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5754 if (!DynType) 5755 return false; 5756 5757 // C++ [expr.dynamic.cast]p7: 5758 // If T is "pointer to cv void", then the result is a pointer to the most 5759 // derived object 5760 if (E->getType()->isVoidPointerType()) 5761 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5762 5763 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5764 assert(C && "dynamic_cast target is not void pointer nor class"); 5765 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5766 5767 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5768 // C++ [expr.dynamic.cast]p9: 5769 if (!E->isGLValue()) { 5770 // The value of a failed cast to pointer type is the null pointer value 5771 // of the required result type. 5772 Ptr.setNull(Info.Ctx, E->getType()); 5773 return true; 5774 } 5775 5776 // A failed cast to reference type throws [...] std::bad_cast. 5777 unsigned DiagKind; 5778 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5779 DynType->Type->isDerivedFrom(C))) 5780 DiagKind = 0; 5781 else if (!Paths || Paths->begin() == Paths->end()) 5782 DiagKind = 1; 5783 else if (Paths->isAmbiguous(CQT)) 5784 DiagKind = 2; 5785 else { 5786 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5787 DiagKind = 3; 5788 } 5789 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5790 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5791 << Info.Ctx.getRecordType(DynType->Type) 5792 << E->getType().getUnqualifiedType(); 5793 return false; 5794 }; 5795 5796 // Runtime check, phase 1: 5797 // Walk from the base subobject towards the derived object looking for the 5798 // target type. 5799 for (int PathLength = Ptr.Designator.Entries.size(); 5800 PathLength >= (int)DynType->PathLength; --PathLength) { 5801 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5802 if (declaresSameEntity(Class, C)) 5803 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5804 // We can only walk across public inheritance edges. 5805 if (PathLength > (int)DynType->PathLength && 5806 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5807 Class)) 5808 return RuntimeCheckFailed(nullptr); 5809 } 5810 5811 // Runtime check, phase 2: 5812 // Search the dynamic type for an unambiguous public base of type C. 5813 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5814 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5815 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5816 Paths.front().Access == AS_public) { 5817 // Downcast to the dynamic type... 5818 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5819 return false; 5820 // ... then upcast to the chosen base class subobject. 5821 for (CXXBasePathElement &Elem : Paths.front()) 5822 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5823 return false; 5824 return true; 5825 } 5826 5827 // Otherwise, the runtime check fails. 5828 return RuntimeCheckFailed(&Paths); 5829 } 5830 5831 namespace { 5832 struct StartLifetimeOfUnionMemberHandler { 5833 EvalInfo &Info; 5834 const Expr *LHSExpr; 5835 const FieldDecl *Field; 5836 bool DuringInit; 5837 bool Failed = false; 5838 static const AccessKinds AccessKind = AK_Assign; 5839 5840 typedef bool result_type; 5841 bool failed() { return Failed; } 5842 bool found(APValue &Subobj, QualType SubobjType) { 5843 // We are supposed to perform no initialization but begin the lifetime of 5844 // the object. We interpret that as meaning to do what default 5845 // initialization of the object would do if all constructors involved were 5846 // trivial: 5847 // * All base, non-variant member, and array element subobjects' lifetimes 5848 // begin 5849 // * No variant members' lifetimes begin 5850 // * All scalar subobjects whose lifetimes begin have indeterminate values 5851 assert(SubobjType->isUnionType()); 5852 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5853 // This union member is already active. If it's also in-lifetime, there's 5854 // nothing to do. 5855 if (Subobj.getUnionValue().hasValue()) 5856 return true; 5857 } else if (DuringInit) { 5858 // We're currently in the process of initializing a different union 5859 // member. If we carried on, that initialization would attempt to 5860 // store to an inactive union member, resulting in undefined behavior. 5861 Info.FFDiag(LHSExpr, 5862 diag::note_constexpr_union_member_change_during_init); 5863 return false; 5864 } 5865 APValue Result; 5866 Failed = !getDefaultInitValue(Field->getType(), Result); 5867 Subobj.setUnion(Field, Result); 5868 return true; 5869 } 5870 bool found(APSInt &Value, QualType SubobjType) { 5871 llvm_unreachable("wrong value kind for union object"); 5872 } 5873 bool found(APFloat &Value, QualType SubobjType) { 5874 llvm_unreachable("wrong value kind for union object"); 5875 } 5876 }; 5877 } // end anonymous namespace 5878 5879 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5880 5881 /// Handle a builtin simple-assignment or a call to a trivial assignment 5882 /// operator whose left-hand side might involve a union member access. If it 5883 /// does, implicitly start the lifetime of any accessed union elements per 5884 /// C++20 [class.union]5. 5885 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5886 const LValue &LHS) { 5887 if (LHS.InvalidBase || LHS.Designator.Invalid) 5888 return false; 5889 5890 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5891 // C++ [class.union]p5: 5892 // define the set S(E) of subexpressions of E as follows: 5893 unsigned PathLength = LHS.Designator.Entries.size(); 5894 for (const Expr *E = LHSExpr; E != nullptr;) { 5895 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5896 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5897 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5898 // Note that we can't implicitly start the lifetime of a reference, 5899 // so we don't need to proceed any further if we reach one. 5900 if (!FD || FD->getType()->isReferenceType()) 5901 break; 5902 5903 // ... and also contains A.B if B names a union member ... 5904 if (FD->getParent()->isUnion()) { 5905 // ... of a non-class, non-array type, or of a class type with a 5906 // trivial default constructor that is not deleted, or an array of 5907 // such types. 5908 auto *RD = 5909 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5910 if (!RD || RD->hasTrivialDefaultConstructor()) 5911 UnionPathLengths.push_back({PathLength - 1, FD}); 5912 } 5913 5914 E = ME->getBase(); 5915 --PathLength; 5916 assert(declaresSameEntity(FD, 5917 LHS.Designator.Entries[PathLength] 5918 .getAsBaseOrMember().getPointer())); 5919 5920 // -- If E is of the form A[B] and is interpreted as a built-in array 5921 // subscripting operator, S(E) is [S(the array operand, if any)]. 5922 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5923 // Step over an ArrayToPointerDecay implicit cast. 5924 auto *Base = ASE->getBase()->IgnoreImplicit(); 5925 if (!Base->getType()->isArrayType()) 5926 break; 5927 5928 E = Base; 5929 --PathLength; 5930 5931 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5932 // Step over a derived-to-base conversion. 5933 E = ICE->getSubExpr(); 5934 if (ICE->getCastKind() == CK_NoOp) 5935 continue; 5936 if (ICE->getCastKind() != CK_DerivedToBase && 5937 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5938 break; 5939 // Walk path backwards as we walk up from the base to the derived class. 5940 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5941 --PathLength; 5942 (void)Elt; 5943 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5944 LHS.Designator.Entries[PathLength] 5945 .getAsBaseOrMember().getPointer())); 5946 } 5947 5948 // -- Otherwise, S(E) is empty. 5949 } else { 5950 break; 5951 } 5952 } 5953 5954 // Common case: no unions' lifetimes are started. 5955 if (UnionPathLengths.empty()) 5956 return true; 5957 5958 // if modification of X [would access an inactive union member], an object 5959 // of the type of X is implicitly created 5960 CompleteObject Obj = 5961 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5962 if (!Obj) 5963 return false; 5964 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5965 llvm::reverse(UnionPathLengths)) { 5966 // Form a designator for the union object. 5967 SubobjectDesignator D = LHS.Designator; 5968 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5969 5970 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5971 ConstructionPhase::AfterBases; 5972 StartLifetimeOfUnionMemberHandler StartLifetime{ 5973 Info, LHSExpr, LengthAndField.second, DuringInit}; 5974 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5975 return false; 5976 } 5977 5978 return true; 5979 } 5980 5981 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5982 CallRef Call, EvalInfo &Info, 5983 bool NonNull = false) { 5984 LValue LV; 5985 // Create the parameter slot and register its destruction. For a vararg 5986 // argument, create a temporary. 5987 // FIXME: For calling conventions that destroy parameters in the callee, 5988 // should we consider performing destruction when the function returns 5989 // instead? 5990 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5991 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5992 ScopeKind::Call, LV); 5993 if (!EvaluateInPlace(V, Info, LV, Arg)) 5994 return false; 5995 5996 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 5997 // undefined behavior, so is non-constant. 5998 if (NonNull && V.isLValue() && V.isNullPointer()) { 5999 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6000 return false; 6001 } 6002 6003 return true; 6004 } 6005 6006 /// Evaluate the arguments to a function call. 6007 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6008 EvalInfo &Info, const FunctionDecl *Callee, 6009 bool RightToLeft = false) { 6010 bool Success = true; 6011 llvm::SmallBitVector ForbiddenNullArgs; 6012 if (Callee->hasAttr<NonNullAttr>()) { 6013 ForbiddenNullArgs.resize(Args.size()); 6014 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6015 if (!Attr->args_size()) { 6016 ForbiddenNullArgs.set(); 6017 break; 6018 } else 6019 for (auto Idx : Attr->args()) { 6020 unsigned ASTIdx = Idx.getASTIndex(); 6021 if (ASTIdx >= Args.size()) 6022 continue; 6023 ForbiddenNullArgs[ASTIdx] = 1; 6024 } 6025 } 6026 } 6027 for (unsigned I = 0; I < Args.size(); I++) { 6028 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6029 const ParmVarDecl *PVD = 6030 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6031 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6032 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6033 // If we're checking for a potential constant expression, evaluate all 6034 // initializers even if some of them fail. 6035 if (!Info.noteFailure()) 6036 return false; 6037 Success = false; 6038 } 6039 } 6040 return Success; 6041 } 6042 6043 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6044 /// constructor or assignment operator. 6045 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6046 const Expr *E, APValue &Result, 6047 bool CopyObjectRepresentation) { 6048 // Find the reference argument. 6049 CallStackFrame *Frame = Info.CurrentCall; 6050 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6051 if (!RefValue) { 6052 Info.FFDiag(E); 6053 return false; 6054 } 6055 6056 // Copy out the contents of the RHS object. 6057 LValue RefLValue; 6058 RefLValue.setFrom(Info.Ctx, *RefValue); 6059 return handleLValueToRValueConversion( 6060 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6061 CopyObjectRepresentation); 6062 } 6063 6064 /// Evaluate a function call. 6065 static bool HandleFunctionCall(SourceLocation CallLoc, 6066 const FunctionDecl *Callee, const LValue *This, 6067 ArrayRef<const Expr *> Args, CallRef Call, 6068 const Stmt *Body, EvalInfo &Info, 6069 APValue &Result, const LValue *ResultSlot) { 6070 if (!Info.CheckCallLimit(CallLoc)) 6071 return false; 6072 6073 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6074 6075 // For a trivial copy or move assignment, perform an APValue copy. This is 6076 // essential for unions, where the operations performed by the assignment 6077 // operator cannot be represented as statements. 6078 // 6079 // Skip this for non-union classes with no fields; in that case, the defaulted 6080 // copy/move does not actually read the object. 6081 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6082 if (MD && MD->isDefaulted() && 6083 (MD->getParent()->isUnion() || 6084 (MD->isTrivial() && 6085 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6086 assert(This && 6087 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6088 APValue RHSValue; 6089 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6090 MD->getParent()->isUnion())) 6091 return false; 6092 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6093 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6094 return false; 6095 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6096 RHSValue)) 6097 return false; 6098 This->moveInto(Result); 6099 return true; 6100 } else if (MD && isLambdaCallOperator(MD)) { 6101 // We're in a lambda; determine the lambda capture field maps unless we're 6102 // just constexpr checking a lambda's call operator. constexpr checking is 6103 // done before the captures have been added to the closure object (unless 6104 // we're inferring constexpr-ness), so we don't have access to them in this 6105 // case. But since we don't need the captures to constexpr check, we can 6106 // just ignore them. 6107 if (!Info.checkingPotentialConstantExpression()) 6108 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6109 Frame.LambdaThisCaptureField); 6110 } 6111 6112 StmtResult Ret = {Result, ResultSlot}; 6113 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6114 if (ESR == ESR_Succeeded) { 6115 if (Callee->getReturnType()->isVoidType()) 6116 return true; 6117 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6118 } 6119 return ESR == ESR_Returned; 6120 } 6121 6122 /// Evaluate a constructor call. 6123 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6124 CallRef Call, 6125 const CXXConstructorDecl *Definition, 6126 EvalInfo &Info, APValue &Result) { 6127 SourceLocation CallLoc = E->getExprLoc(); 6128 if (!Info.CheckCallLimit(CallLoc)) 6129 return false; 6130 6131 const CXXRecordDecl *RD = Definition->getParent(); 6132 if (RD->getNumVBases()) { 6133 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6134 return false; 6135 } 6136 6137 EvalInfo::EvaluatingConstructorRAII EvalObj( 6138 Info, 6139 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6140 RD->getNumBases()); 6141 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6142 6143 // FIXME: Creating an APValue just to hold a nonexistent return value is 6144 // wasteful. 6145 APValue RetVal; 6146 StmtResult Ret = {RetVal, nullptr}; 6147 6148 // If it's a delegating constructor, delegate. 6149 if (Definition->isDelegatingConstructor()) { 6150 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6151 if ((*I)->getInit()->isValueDependent()) { 6152 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6153 return false; 6154 } else { 6155 FullExpressionRAII InitScope(Info); 6156 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6157 !InitScope.destroy()) 6158 return false; 6159 } 6160 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6161 } 6162 6163 // For a trivial copy or move constructor, perform an APValue copy. This is 6164 // essential for unions (or classes with anonymous union members), where the 6165 // operations performed by the constructor cannot be represented by 6166 // ctor-initializers. 6167 // 6168 // Skip this for empty non-union classes; we should not perform an 6169 // lvalue-to-rvalue conversion on them because their copy constructor does not 6170 // actually read them. 6171 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6172 (Definition->getParent()->isUnion() || 6173 (Definition->isTrivial() && 6174 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6175 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6176 Definition->getParent()->isUnion()); 6177 } 6178 6179 // Reserve space for the struct members. 6180 if (!Result.hasValue()) { 6181 if (!RD->isUnion()) 6182 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6183 std::distance(RD->field_begin(), RD->field_end())); 6184 else 6185 // A union starts with no active member. 6186 Result = APValue((const FieldDecl*)nullptr); 6187 } 6188 6189 if (RD->isInvalidDecl()) return false; 6190 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6191 6192 // A scope for temporaries lifetime-extended by reference members. 6193 BlockScopeRAII LifetimeExtendedScope(Info); 6194 6195 bool Success = true; 6196 unsigned BasesSeen = 0; 6197 #ifndef NDEBUG 6198 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6199 #endif 6200 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6201 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6202 // We might be initializing the same field again if this is an indirect 6203 // field initialization. 6204 if (FieldIt == RD->field_end() || 6205 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6206 assert(Indirect && "fields out of order?"); 6207 return; 6208 } 6209 6210 // Default-initialize any fields with no explicit initializer. 6211 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6212 assert(FieldIt != RD->field_end() && "missing field?"); 6213 if (!FieldIt->isUnnamedBitfield()) 6214 Success &= getDefaultInitValue( 6215 FieldIt->getType(), 6216 Result.getStructField(FieldIt->getFieldIndex())); 6217 } 6218 ++FieldIt; 6219 }; 6220 for (const auto *I : Definition->inits()) { 6221 LValue Subobject = This; 6222 LValue SubobjectParent = This; 6223 APValue *Value = &Result; 6224 6225 // Determine the subobject to initialize. 6226 FieldDecl *FD = nullptr; 6227 if (I->isBaseInitializer()) { 6228 QualType BaseType(I->getBaseClass(), 0); 6229 #ifndef NDEBUG 6230 // Non-virtual base classes are initialized in the order in the class 6231 // definition. We have already checked for virtual base classes. 6232 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6233 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6234 "base class initializers not in expected order"); 6235 ++BaseIt; 6236 #endif 6237 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6238 BaseType->getAsCXXRecordDecl(), &Layout)) 6239 return false; 6240 Value = &Result.getStructBase(BasesSeen++); 6241 } else if ((FD = I->getMember())) { 6242 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6243 return false; 6244 if (RD->isUnion()) { 6245 Result = APValue(FD); 6246 Value = &Result.getUnionValue(); 6247 } else { 6248 SkipToField(FD, false); 6249 Value = &Result.getStructField(FD->getFieldIndex()); 6250 } 6251 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6252 // Walk the indirect field decl's chain to find the object to initialize, 6253 // and make sure we've initialized every step along it. 6254 auto IndirectFieldChain = IFD->chain(); 6255 for (auto *C : IndirectFieldChain) { 6256 FD = cast<FieldDecl>(C); 6257 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6258 // Switch the union field if it differs. This happens if we had 6259 // preceding zero-initialization, and we're now initializing a union 6260 // subobject other than the first. 6261 // FIXME: In this case, the values of the other subobjects are 6262 // specified, since zero-initialization sets all padding bits to zero. 6263 if (!Value->hasValue() || 6264 (Value->isUnion() && Value->getUnionField() != FD)) { 6265 if (CD->isUnion()) 6266 *Value = APValue(FD); 6267 else 6268 // FIXME: This immediately starts the lifetime of all members of 6269 // an anonymous struct. It would be preferable to strictly start 6270 // member lifetime in initialization order. 6271 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6272 } 6273 // Store Subobject as its parent before updating it for the last element 6274 // in the chain. 6275 if (C == IndirectFieldChain.back()) 6276 SubobjectParent = Subobject; 6277 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6278 return false; 6279 if (CD->isUnion()) 6280 Value = &Value->getUnionValue(); 6281 else { 6282 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6283 SkipToField(FD, true); 6284 Value = &Value->getStructField(FD->getFieldIndex()); 6285 } 6286 } 6287 } else { 6288 llvm_unreachable("unknown base initializer kind"); 6289 } 6290 6291 // Need to override This for implicit field initializers as in this case 6292 // This refers to innermost anonymous struct/union containing initializer, 6293 // not to currently constructed class. 6294 const Expr *Init = I->getInit(); 6295 if (Init->isValueDependent()) { 6296 if (!EvaluateDependentExpr(Init, Info)) 6297 return false; 6298 } else { 6299 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6300 isa<CXXDefaultInitExpr>(Init)); 6301 FullExpressionRAII InitScope(Info); 6302 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6303 (FD && FD->isBitField() && 6304 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6305 // If we're checking for a potential constant expression, evaluate all 6306 // initializers even if some of them fail. 6307 if (!Info.noteFailure()) 6308 return false; 6309 Success = false; 6310 } 6311 } 6312 6313 // This is the point at which the dynamic type of the object becomes this 6314 // class type. 6315 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6316 EvalObj.finishedConstructingBases(); 6317 } 6318 6319 // Default-initialize any remaining fields. 6320 if (!RD->isUnion()) { 6321 for (; FieldIt != RD->field_end(); ++FieldIt) { 6322 if (!FieldIt->isUnnamedBitfield()) 6323 Success &= getDefaultInitValue( 6324 FieldIt->getType(), 6325 Result.getStructField(FieldIt->getFieldIndex())); 6326 } 6327 } 6328 6329 EvalObj.finishedConstructingFields(); 6330 6331 return Success && 6332 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6333 LifetimeExtendedScope.destroy(); 6334 } 6335 6336 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6337 ArrayRef<const Expr*> Args, 6338 const CXXConstructorDecl *Definition, 6339 EvalInfo &Info, APValue &Result) { 6340 CallScopeRAII CallScope(Info); 6341 CallRef Call = Info.CurrentCall->createCall(Definition); 6342 if (!EvaluateArgs(Args, Call, Info, Definition)) 6343 return false; 6344 6345 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6346 CallScope.destroy(); 6347 } 6348 6349 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6350 const LValue &This, APValue &Value, 6351 QualType T) { 6352 // Objects can only be destroyed while they're within their lifetimes. 6353 // FIXME: We have no representation for whether an object of type nullptr_t 6354 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6355 // as indeterminate instead? 6356 if (Value.isAbsent() && !T->isNullPtrType()) { 6357 APValue Printable; 6358 This.moveInto(Printable); 6359 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6360 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6361 return false; 6362 } 6363 6364 // Invent an expression for location purposes. 6365 // FIXME: We shouldn't need to do this. 6366 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6367 6368 // For arrays, destroy elements right-to-left. 6369 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6370 uint64_t Size = CAT->getSize().getZExtValue(); 6371 QualType ElemT = CAT->getElementType(); 6372 6373 LValue ElemLV = This; 6374 ElemLV.addArray(Info, &LocE, CAT); 6375 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6376 return false; 6377 6378 // Ensure that we have actual array elements available to destroy; the 6379 // destructors might mutate the value, so we can't run them on the array 6380 // filler. 6381 if (Size && Size > Value.getArrayInitializedElts()) 6382 expandArray(Value, Value.getArraySize() - 1); 6383 6384 for (; Size != 0; --Size) { 6385 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6386 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6387 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6388 return false; 6389 } 6390 6391 // End the lifetime of this array now. 6392 Value = APValue(); 6393 return true; 6394 } 6395 6396 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6397 if (!RD) { 6398 if (T.isDestructedType()) { 6399 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6400 return false; 6401 } 6402 6403 Value = APValue(); 6404 return true; 6405 } 6406 6407 if (RD->getNumVBases()) { 6408 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6409 return false; 6410 } 6411 6412 const CXXDestructorDecl *DD = RD->getDestructor(); 6413 if (!DD && !RD->hasTrivialDestructor()) { 6414 Info.FFDiag(CallLoc); 6415 return false; 6416 } 6417 6418 if (!DD || DD->isTrivial() || 6419 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6420 // A trivial destructor just ends the lifetime of the object. Check for 6421 // this case before checking for a body, because we might not bother 6422 // building a body for a trivial destructor. Note that it doesn't matter 6423 // whether the destructor is constexpr in this case; all trivial 6424 // destructors are constexpr. 6425 // 6426 // If an anonymous union would be destroyed, some enclosing destructor must 6427 // have been explicitly defined, and the anonymous union destruction should 6428 // have no effect. 6429 Value = APValue(); 6430 return true; 6431 } 6432 6433 if (!Info.CheckCallLimit(CallLoc)) 6434 return false; 6435 6436 const FunctionDecl *Definition = nullptr; 6437 const Stmt *Body = DD->getBody(Definition); 6438 6439 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6440 return false; 6441 6442 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6443 6444 // We're now in the period of destruction of this object. 6445 unsigned BasesLeft = RD->getNumBases(); 6446 EvalInfo::EvaluatingDestructorRAII EvalObj( 6447 Info, 6448 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6449 if (!EvalObj.DidInsert) { 6450 // C++2a [class.dtor]p19: 6451 // the behavior is undefined if the destructor is invoked for an object 6452 // whose lifetime has ended 6453 // (Note that formally the lifetime ends when the period of destruction 6454 // begins, even though certain uses of the object remain valid until the 6455 // period of destruction ends.) 6456 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6457 return false; 6458 } 6459 6460 // FIXME: Creating an APValue just to hold a nonexistent return value is 6461 // wasteful. 6462 APValue RetVal; 6463 StmtResult Ret = {RetVal, nullptr}; 6464 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6465 return false; 6466 6467 // A union destructor does not implicitly destroy its members. 6468 if (RD->isUnion()) 6469 return true; 6470 6471 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6472 6473 // We don't have a good way to iterate fields in reverse, so collect all the 6474 // fields first and then walk them backwards. 6475 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6476 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6477 if (FD->isUnnamedBitfield()) 6478 continue; 6479 6480 LValue Subobject = This; 6481 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6482 return false; 6483 6484 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6485 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6486 FD->getType())) 6487 return false; 6488 } 6489 6490 if (BasesLeft != 0) 6491 EvalObj.startedDestroyingBases(); 6492 6493 // Destroy base classes in reverse order. 6494 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6495 --BasesLeft; 6496 6497 QualType BaseType = Base.getType(); 6498 LValue Subobject = This; 6499 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6500 BaseType->getAsCXXRecordDecl(), &Layout)) 6501 return false; 6502 6503 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6504 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6505 BaseType)) 6506 return false; 6507 } 6508 assert(BasesLeft == 0 && "NumBases was wrong?"); 6509 6510 // The period of destruction ends now. The object is gone. 6511 Value = APValue(); 6512 return true; 6513 } 6514 6515 namespace { 6516 struct DestroyObjectHandler { 6517 EvalInfo &Info; 6518 const Expr *E; 6519 const LValue &This; 6520 const AccessKinds AccessKind; 6521 6522 typedef bool result_type; 6523 bool failed() { return false; } 6524 bool found(APValue &Subobj, QualType SubobjType) { 6525 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6526 SubobjType); 6527 } 6528 bool found(APSInt &Value, QualType SubobjType) { 6529 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6530 return false; 6531 } 6532 bool found(APFloat &Value, QualType SubobjType) { 6533 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6534 return false; 6535 } 6536 }; 6537 } 6538 6539 /// Perform a destructor or pseudo-destructor call on the given object, which 6540 /// might in general not be a complete object. 6541 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6542 const LValue &This, QualType ThisType) { 6543 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6544 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6545 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6546 } 6547 6548 /// Destroy and end the lifetime of the given complete object. 6549 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6550 APValue::LValueBase LVBase, APValue &Value, 6551 QualType T) { 6552 // If we've had an unmodeled side-effect, we can't rely on mutable state 6553 // (such as the object we're about to destroy) being correct. 6554 if (Info.EvalStatus.HasSideEffects) 6555 return false; 6556 6557 LValue LV; 6558 LV.set({LVBase}); 6559 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6560 } 6561 6562 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6563 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6564 LValue &Result) { 6565 if (Info.checkingPotentialConstantExpression() || 6566 Info.SpeculativeEvaluationDepth) 6567 return false; 6568 6569 // This is permitted only within a call to std::allocator<T>::allocate. 6570 auto Caller = Info.getStdAllocatorCaller("allocate"); 6571 if (!Caller) { 6572 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6573 ? diag::note_constexpr_new_untyped 6574 : diag::note_constexpr_new); 6575 return false; 6576 } 6577 6578 QualType ElemType = Caller.ElemType; 6579 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6580 Info.FFDiag(E->getExprLoc(), 6581 diag::note_constexpr_new_not_complete_object_type) 6582 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6583 return false; 6584 } 6585 6586 APSInt ByteSize; 6587 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6588 return false; 6589 bool IsNothrow = false; 6590 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6591 EvaluateIgnoredValue(Info, E->getArg(I)); 6592 IsNothrow |= E->getType()->isNothrowT(); 6593 } 6594 6595 CharUnits ElemSize; 6596 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6597 return false; 6598 APInt Size, Remainder; 6599 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6600 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6601 if (Remainder != 0) { 6602 // This likely indicates a bug in the implementation of 'std::allocator'. 6603 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6604 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6605 return false; 6606 } 6607 6608 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6609 if (IsNothrow) { 6610 Result.setNull(Info.Ctx, E->getType()); 6611 return true; 6612 } 6613 6614 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6615 return false; 6616 } 6617 6618 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6619 ArrayType::Normal, 0); 6620 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6621 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6622 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6623 return true; 6624 } 6625 6626 static bool hasVirtualDestructor(QualType T) { 6627 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6628 if (CXXDestructorDecl *DD = RD->getDestructor()) 6629 return DD->isVirtual(); 6630 return false; 6631 } 6632 6633 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6634 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6635 if (CXXDestructorDecl *DD = RD->getDestructor()) 6636 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6637 return nullptr; 6638 } 6639 6640 /// Check that the given object is a suitable pointer to a heap allocation that 6641 /// still exists and is of the right kind for the purpose of a deletion. 6642 /// 6643 /// On success, returns the heap allocation to deallocate. On failure, produces 6644 /// a diagnostic and returns None. 6645 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6646 const LValue &Pointer, 6647 DynAlloc::Kind DeallocKind) { 6648 auto PointerAsString = [&] { 6649 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6650 }; 6651 6652 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6653 if (!DA) { 6654 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6655 << PointerAsString(); 6656 if (Pointer.Base) 6657 NoteLValueLocation(Info, Pointer.Base); 6658 return None; 6659 } 6660 6661 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6662 if (!Alloc) { 6663 Info.FFDiag(E, diag::note_constexpr_double_delete); 6664 return None; 6665 } 6666 6667 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6668 if (DeallocKind != (*Alloc)->getKind()) { 6669 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6670 << DeallocKind << (*Alloc)->getKind() << AllocType; 6671 NoteLValueLocation(Info, Pointer.Base); 6672 return None; 6673 } 6674 6675 bool Subobject = false; 6676 if (DeallocKind == DynAlloc::New) { 6677 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6678 Pointer.Designator.isOnePastTheEnd(); 6679 } else { 6680 Subobject = Pointer.Designator.Entries.size() != 1 || 6681 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6682 } 6683 if (Subobject) { 6684 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6685 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6686 return None; 6687 } 6688 6689 return Alloc; 6690 } 6691 6692 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6693 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6694 if (Info.checkingPotentialConstantExpression() || 6695 Info.SpeculativeEvaluationDepth) 6696 return false; 6697 6698 // This is permitted only within a call to std::allocator<T>::deallocate. 6699 if (!Info.getStdAllocatorCaller("deallocate")) { 6700 Info.FFDiag(E->getExprLoc()); 6701 return true; 6702 } 6703 6704 LValue Pointer; 6705 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6706 return false; 6707 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6708 EvaluateIgnoredValue(Info, E->getArg(I)); 6709 6710 if (Pointer.Designator.Invalid) 6711 return false; 6712 6713 // Deleting a null pointer has no effect. 6714 if (Pointer.isNullPointer()) 6715 return true; 6716 6717 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6718 return false; 6719 6720 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6721 return true; 6722 } 6723 6724 //===----------------------------------------------------------------------===// 6725 // Generic Evaluation 6726 //===----------------------------------------------------------------------===// 6727 namespace { 6728 6729 class BitCastBuffer { 6730 // FIXME: We're going to need bit-level granularity when we support 6731 // bit-fields. 6732 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6733 // we don't support a host or target where that is the case. Still, we should 6734 // use a more generic type in case we ever do. 6735 SmallVector<Optional<unsigned char>, 32> Bytes; 6736 6737 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6738 "Need at least 8 bit unsigned char"); 6739 6740 bool TargetIsLittleEndian; 6741 6742 public: 6743 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6744 : Bytes(Width.getQuantity()), 6745 TargetIsLittleEndian(TargetIsLittleEndian) {} 6746 6747 LLVM_NODISCARD 6748 bool readObject(CharUnits Offset, CharUnits Width, 6749 SmallVectorImpl<unsigned char> &Output) const { 6750 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6751 // If a byte of an integer is uninitialized, then the whole integer is 6752 // uninitalized. 6753 if (!Bytes[I.getQuantity()]) 6754 return false; 6755 Output.push_back(*Bytes[I.getQuantity()]); 6756 } 6757 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6758 std::reverse(Output.begin(), Output.end()); 6759 return true; 6760 } 6761 6762 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6763 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6764 std::reverse(Input.begin(), Input.end()); 6765 6766 size_t Index = 0; 6767 for (unsigned char Byte : Input) { 6768 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6769 Bytes[Offset.getQuantity() + Index] = Byte; 6770 ++Index; 6771 } 6772 } 6773 6774 size_t size() { return Bytes.size(); } 6775 }; 6776 6777 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6778 /// target would represent the value at runtime. 6779 class APValueToBufferConverter { 6780 EvalInfo &Info; 6781 BitCastBuffer Buffer; 6782 const CastExpr *BCE; 6783 6784 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6785 const CastExpr *BCE) 6786 : Info(Info), 6787 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6788 BCE(BCE) {} 6789 6790 bool visit(const APValue &Val, QualType Ty) { 6791 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6792 } 6793 6794 // Write out Val with type Ty into Buffer starting at Offset. 6795 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6796 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6797 6798 // As a special case, nullptr_t has an indeterminate value. 6799 if (Ty->isNullPtrType()) 6800 return true; 6801 6802 // Dig through Src to find the byte at SrcOffset. 6803 switch (Val.getKind()) { 6804 case APValue::Indeterminate: 6805 case APValue::None: 6806 return true; 6807 6808 case APValue::Int: 6809 return visitInt(Val.getInt(), Ty, Offset); 6810 case APValue::Float: 6811 return visitFloat(Val.getFloat(), Ty, Offset); 6812 case APValue::Array: 6813 return visitArray(Val, Ty, Offset); 6814 case APValue::Struct: 6815 return visitRecord(Val, Ty, Offset); 6816 6817 case APValue::ComplexInt: 6818 case APValue::ComplexFloat: 6819 case APValue::Vector: 6820 case APValue::FixedPoint: 6821 // FIXME: We should support these. 6822 6823 case APValue::Union: 6824 case APValue::MemberPointer: 6825 case APValue::AddrLabelDiff: { 6826 Info.FFDiag(BCE->getBeginLoc(), 6827 diag::note_constexpr_bit_cast_unsupported_type) 6828 << Ty; 6829 return false; 6830 } 6831 6832 case APValue::LValue: 6833 llvm_unreachable("LValue subobject in bit_cast?"); 6834 } 6835 llvm_unreachable("Unhandled APValue::ValueKind"); 6836 } 6837 6838 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6839 const RecordDecl *RD = Ty->getAsRecordDecl(); 6840 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6841 6842 // Visit the base classes. 6843 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6844 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6845 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6846 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6847 6848 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6849 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6850 return false; 6851 } 6852 } 6853 6854 // Visit the fields. 6855 unsigned FieldIdx = 0; 6856 for (FieldDecl *FD : RD->fields()) { 6857 if (FD->isBitField()) { 6858 Info.FFDiag(BCE->getBeginLoc(), 6859 diag::note_constexpr_bit_cast_unsupported_bitfield); 6860 return false; 6861 } 6862 6863 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6864 6865 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6866 "only bit-fields can have sub-char alignment"); 6867 CharUnits FieldOffset = 6868 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6869 QualType FieldTy = FD->getType(); 6870 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6871 return false; 6872 ++FieldIdx; 6873 } 6874 6875 return true; 6876 } 6877 6878 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6879 const auto *CAT = 6880 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6881 if (!CAT) 6882 return false; 6883 6884 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6885 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6886 unsigned ArraySize = Val.getArraySize(); 6887 // First, initialize the initialized elements. 6888 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6889 const APValue &SubObj = Val.getArrayInitializedElt(I); 6890 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6891 return false; 6892 } 6893 6894 // Next, initialize the rest of the array using the filler. 6895 if (Val.hasArrayFiller()) { 6896 const APValue &Filler = Val.getArrayFiller(); 6897 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6898 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6899 return false; 6900 } 6901 } 6902 6903 return true; 6904 } 6905 6906 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6907 APSInt AdjustedVal = Val; 6908 unsigned Width = AdjustedVal.getBitWidth(); 6909 if (Ty->isBooleanType()) { 6910 Width = Info.Ctx.getTypeSize(Ty); 6911 AdjustedVal = AdjustedVal.extend(Width); 6912 } 6913 6914 SmallVector<unsigned char, 8> Bytes(Width / 8); 6915 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6916 Buffer.writeObject(Offset, Bytes); 6917 return true; 6918 } 6919 6920 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6921 APSInt AsInt(Val.bitcastToAPInt()); 6922 return visitInt(AsInt, Ty, Offset); 6923 } 6924 6925 public: 6926 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6927 const CastExpr *BCE) { 6928 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6929 APValueToBufferConverter Converter(Info, DstSize, BCE); 6930 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6931 return None; 6932 return Converter.Buffer; 6933 } 6934 }; 6935 6936 /// Write an BitCastBuffer into an APValue. 6937 class BufferToAPValueConverter { 6938 EvalInfo &Info; 6939 const BitCastBuffer &Buffer; 6940 const CastExpr *BCE; 6941 6942 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6943 const CastExpr *BCE) 6944 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6945 6946 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6947 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6948 // Ideally this will be unreachable. 6949 llvm::NoneType unsupportedType(QualType Ty) { 6950 Info.FFDiag(BCE->getBeginLoc(), 6951 diag::note_constexpr_bit_cast_unsupported_type) 6952 << Ty; 6953 return None; 6954 } 6955 6956 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6957 Info.FFDiag(BCE->getBeginLoc(), 6958 diag::note_constexpr_bit_cast_unrepresentable_value) 6959 << Ty << Val.toString(/*Radix=*/10); 6960 return None; 6961 } 6962 6963 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6964 const EnumType *EnumSugar = nullptr) { 6965 if (T->isNullPtrType()) { 6966 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6967 return APValue((Expr *)nullptr, 6968 /*Offset=*/CharUnits::fromQuantity(NullValue), 6969 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6970 } 6971 6972 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6973 6974 // Work around floating point types that contain unused padding bytes. This 6975 // is really just `long double` on x86, which is the only fundamental type 6976 // with padding bytes. 6977 if (T->isRealFloatingType()) { 6978 const llvm::fltSemantics &Semantics = 6979 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6980 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6981 assert(NumBits % 8 == 0); 6982 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6983 if (NumBytes != SizeOf) 6984 SizeOf = NumBytes; 6985 } 6986 6987 SmallVector<uint8_t, 8> Bytes; 6988 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6989 // If this is std::byte or unsigned char, then its okay to store an 6990 // indeterminate value. 6991 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6992 bool IsUChar = 6993 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6994 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6995 if (!IsStdByte && !IsUChar) { 6996 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6997 Info.FFDiag(BCE->getExprLoc(), 6998 diag::note_constexpr_bit_cast_indet_dest) 6999 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7000 return None; 7001 } 7002 7003 return APValue::IndeterminateValue(); 7004 } 7005 7006 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7007 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7008 7009 if (T->isIntegralOrEnumerationType()) { 7010 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7011 7012 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7013 if (IntWidth != Val.getBitWidth()) { 7014 APSInt Truncated = Val.trunc(IntWidth); 7015 if (Truncated.extend(Val.getBitWidth()) != Val) 7016 return unrepresentableValue(QualType(T, 0), Val); 7017 Val = Truncated; 7018 } 7019 7020 return APValue(Val); 7021 } 7022 7023 if (T->isRealFloatingType()) { 7024 const llvm::fltSemantics &Semantics = 7025 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7026 return APValue(APFloat(Semantics, Val)); 7027 } 7028 7029 return unsupportedType(QualType(T, 0)); 7030 } 7031 7032 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7033 const RecordDecl *RD = RTy->getAsRecordDecl(); 7034 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7035 7036 unsigned NumBases = 0; 7037 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7038 NumBases = CXXRD->getNumBases(); 7039 7040 APValue ResultVal(APValue::UninitStruct(), NumBases, 7041 std::distance(RD->field_begin(), RD->field_end())); 7042 7043 // Visit the base classes. 7044 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7045 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7046 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7047 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7048 if (BaseDecl->isEmpty() || 7049 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7050 continue; 7051 7052 Optional<APValue> SubObj = visitType( 7053 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7054 if (!SubObj) 7055 return None; 7056 ResultVal.getStructBase(I) = *SubObj; 7057 } 7058 } 7059 7060 // Visit the fields. 7061 unsigned FieldIdx = 0; 7062 for (FieldDecl *FD : RD->fields()) { 7063 // FIXME: We don't currently support bit-fields. A lot of the logic for 7064 // this is in CodeGen, so we need to factor it around. 7065 if (FD->isBitField()) { 7066 Info.FFDiag(BCE->getBeginLoc(), 7067 diag::note_constexpr_bit_cast_unsupported_bitfield); 7068 return None; 7069 } 7070 7071 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7072 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7073 7074 CharUnits FieldOffset = 7075 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7076 Offset; 7077 QualType FieldTy = FD->getType(); 7078 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7079 if (!SubObj) 7080 return None; 7081 ResultVal.getStructField(FieldIdx) = *SubObj; 7082 ++FieldIdx; 7083 } 7084 7085 return ResultVal; 7086 } 7087 7088 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7089 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7090 assert(!RepresentationType.isNull() && 7091 "enum forward decl should be caught by Sema"); 7092 const auto *AsBuiltin = 7093 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7094 // Recurse into the underlying type. Treat std::byte transparently as 7095 // unsigned char. 7096 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7097 } 7098 7099 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7100 size_t Size = Ty->getSize().getLimitedValue(); 7101 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7102 7103 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7104 for (size_t I = 0; I != Size; ++I) { 7105 Optional<APValue> ElementValue = 7106 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7107 if (!ElementValue) 7108 return None; 7109 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7110 } 7111 7112 return ArrayValue; 7113 } 7114 7115 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7116 return unsupportedType(QualType(Ty, 0)); 7117 } 7118 7119 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7120 QualType Can = Ty.getCanonicalType(); 7121 7122 switch (Can->getTypeClass()) { 7123 #define TYPE(Class, Base) \ 7124 case Type::Class: \ 7125 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7126 #define ABSTRACT_TYPE(Class, Base) 7127 #define NON_CANONICAL_TYPE(Class, Base) \ 7128 case Type::Class: \ 7129 llvm_unreachable("non-canonical type should be impossible!"); 7130 #define DEPENDENT_TYPE(Class, Base) \ 7131 case Type::Class: \ 7132 llvm_unreachable( \ 7133 "dependent types aren't supported in the constant evaluator!"); 7134 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7135 case Type::Class: \ 7136 llvm_unreachable("either dependent or not canonical!"); 7137 #include "clang/AST/TypeNodes.inc" 7138 } 7139 llvm_unreachable("Unhandled Type::TypeClass"); 7140 } 7141 7142 public: 7143 // Pull out a full value of type DstType. 7144 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7145 const CastExpr *BCE) { 7146 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7147 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7148 } 7149 }; 7150 7151 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7152 QualType Ty, EvalInfo *Info, 7153 const ASTContext &Ctx, 7154 bool CheckingDest) { 7155 Ty = Ty.getCanonicalType(); 7156 7157 auto diag = [&](int Reason) { 7158 if (Info) 7159 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7160 << CheckingDest << (Reason == 4) << Reason; 7161 return false; 7162 }; 7163 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7164 if (Info) 7165 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7166 << NoteTy << Construct << Ty; 7167 return false; 7168 }; 7169 7170 if (Ty->isUnionType()) 7171 return diag(0); 7172 if (Ty->isPointerType()) 7173 return diag(1); 7174 if (Ty->isMemberPointerType()) 7175 return diag(2); 7176 if (Ty.isVolatileQualified()) 7177 return diag(3); 7178 7179 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7180 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7181 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7182 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7183 CheckingDest)) 7184 return note(1, BS.getType(), BS.getBeginLoc()); 7185 } 7186 for (FieldDecl *FD : Record->fields()) { 7187 if (FD->getType()->isReferenceType()) 7188 return diag(4); 7189 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7190 CheckingDest)) 7191 return note(0, FD->getType(), FD->getBeginLoc()); 7192 } 7193 } 7194 7195 if (Ty->isArrayType() && 7196 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7197 Info, Ctx, CheckingDest)) 7198 return false; 7199 7200 return true; 7201 } 7202 7203 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7204 const ASTContext &Ctx, 7205 const CastExpr *BCE) { 7206 bool DestOK = checkBitCastConstexprEligibilityType( 7207 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7208 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7209 BCE->getBeginLoc(), 7210 BCE->getSubExpr()->getType(), Info, Ctx, false); 7211 return SourceOK; 7212 } 7213 7214 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7215 APValue &SourceValue, 7216 const CastExpr *BCE) { 7217 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7218 "no host or target supports non 8-bit chars"); 7219 assert(SourceValue.isLValue() && 7220 "LValueToRValueBitcast requires an lvalue operand!"); 7221 7222 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7223 return false; 7224 7225 LValue SourceLValue; 7226 APValue SourceRValue; 7227 SourceLValue.setFrom(Info.Ctx, SourceValue); 7228 if (!handleLValueToRValueConversion( 7229 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7230 SourceRValue, /*WantObjectRepresentation=*/true)) 7231 return false; 7232 7233 // Read out SourceValue into a char buffer. 7234 Optional<BitCastBuffer> Buffer = 7235 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7236 if (!Buffer) 7237 return false; 7238 7239 // Write out the buffer into a new APValue. 7240 Optional<APValue> MaybeDestValue = 7241 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7242 if (!MaybeDestValue) 7243 return false; 7244 7245 DestValue = std::move(*MaybeDestValue); 7246 return true; 7247 } 7248 7249 template <class Derived> 7250 class ExprEvaluatorBase 7251 : public ConstStmtVisitor<Derived, bool> { 7252 private: 7253 Derived &getDerived() { return static_cast<Derived&>(*this); } 7254 bool DerivedSuccess(const APValue &V, const Expr *E) { 7255 return getDerived().Success(V, E); 7256 } 7257 bool DerivedZeroInitialization(const Expr *E) { 7258 return getDerived().ZeroInitialization(E); 7259 } 7260 7261 // Check whether a conditional operator with a non-constant condition is a 7262 // potential constant expression. If neither arm is a potential constant 7263 // expression, then the conditional operator is not either. 7264 template<typename ConditionalOperator> 7265 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7266 assert(Info.checkingPotentialConstantExpression()); 7267 7268 // Speculatively evaluate both arms. 7269 SmallVector<PartialDiagnosticAt, 8> Diag; 7270 { 7271 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7272 StmtVisitorTy::Visit(E->getFalseExpr()); 7273 if (Diag.empty()) 7274 return; 7275 } 7276 7277 { 7278 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7279 Diag.clear(); 7280 StmtVisitorTy::Visit(E->getTrueExpr()); 7281 if (Diag.empty()) 7282 return; 7283 } 7284 7285 Error(E, diag::note_constexpr_conditional_never_const); 7286 } 7287 7288 7289 template<typename ConditionalOperator> 7290 bool HandleConditionalOperator(const ConditionalOperator *E) { 7291 bool BoolResult; 7292 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7293 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7294 CheckPotentialConstantConditional(E); 7295 return false; 7296 } 7297 if (Info.noteFailure()) { 7298 StmtVisitorTy::Visit(E->getTrueExpr()); 7299 StmtVisitorTy::Visit(E->getFalseExpr()); 7300 } 7301 return false; 7302 } 7303 7304 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7305 return StmtVisitorTy::Visit(EvalExpr); 7306 } 7307 7308 protected: 7309 EvalInfo &Info; 7310 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7311 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7312 7313 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7314 return Info.CCEDiag(E, D); 7315 } 7316 7317 bool ZeroInitialization(const Expr *E) { return Error(E); } 7318 7319 public: 7320 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7321 7322 EvalInfo &getEvalInfo() { return Info; } 7323 7324 /// Report an evaluation error. This should only be called when an error is 7325 /// first discovered. When propagating an error, just return false. 7326 bool Error(const Expr *E, diag::kind D) { 7327 Info.FFDiag(E, D); 7328 return false; 7329 } 7330 bool Error(const Expr *E) { 7331 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7332 } 7333 7334 bool VisitStmt(const Stmt *) { 7335 llvm_unreachable("Expression evaluator should not be called on stmts"); 7336 } 7337 bool VisitExpr(const Expr *E) { 7338 return Error(E); 7339 } 7340 7341 bool VisitConstantExpr(const ConstantExpr *E) { 7342 if (E->hasAPValueResult()) 7343 return DerivedSuccess(E->getAPValueResult(), E); 7344 7345 return StmtVisitorTy::Visit(E->getSubExpr()); 7346 } 7347 7348 bool VisitParenExpr(const ParenExpr *E) 7349 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7350 bool VisitUnaryExtension(const UnaryOperator *E) 7351 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7352 bool VisitUnaryPlus(const UnaryOperator *E) 7353 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7354 bool VisitChooseExpr(const ChooseExpr *E) 7355 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7356 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7357 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7358 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7359 { return StmtVisitorTy::Visit(E->getReplacement()); } 7360 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7361 TempVersionRAII RAII(*Info.CurrentCall); 7362 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7363 return StmtVisitorTy::Visit(E->getExpr()); 7364 } 7365 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7366 TempVersionRAII RAII(*Info.CurrentCall); 7367 // The initializer may not have been parsed yet, or might be erroneous. 7368 if (!E->getExpr()) 7369 return Error(E); 7370 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7371 return StmtVisitorTy::Visit(E->getExpr()); 7372 } 7373 7374 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7375 FullExpressionRAII Scope(Info); 7376 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7377 } 7378 7379 // Temporaries are registered when created, so we don't care about 7380 // CXXBindTemporaryExpr. 7381 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7382 return StmtVisitorTy::Visit(E->getSubExpr()); 7383 } 7384 7385 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7386 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7387 return static_cast<Derived*>(this)->VisitCastExpr(E); 7388 } 7389 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7390 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7391 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7392 return static_cast<Derived*>(this)->VisitCastExpr(E); 7393 } 7394 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7395 return static_cast<Derived*>(this)->VisitCastExpr(E); 7396 } 7397 7398 bool VisitBinaryOperator(const BinaryOperator *E) { 7399 switch (E->getOpcode()) { 7400 default: 7401 return Error(E); 7402 7403 case BO_Comma: 7404 VisitIgnoredValue(E->getLHS()); 7405 return StmtVisitorTy::Visit(E->getRHS()); 7406 7407 case BO_PtrMemD: 7408 case BO_PtrMemI: { 7409 LValue Obj; 7410 if (!HandleMemberPointerAccess(Info, E, Obj)) 7411 return false; 7412 APValue Result; 7413 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7414 return false; 7415 return DerivedSuccess(Result, E); 7416 } 7417 } 7418 } 7419 7420 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7421 return StmtVisitorTy::Visit(E->getSemanticForm()); 7422 } 7423 7424 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7425 // Evaluate and cache the common expression. We treat it as a temporary, 7426 // even though it's not quite the same thing. 7427 LValue CommonLV; 7428 if (!Evaluate(Info.CurrentCall->createTemporary( 7429 E->getOpaqueValue(), 7430 getStorageType(Info.Ctx, E->getOpaqueValue()), 7431 ScopeKind::FullExpression, CommonLV), 7432 Info, E->getCommon())) 7433 return false; 7434 7435 return HandleConditionalOperator(E); 7436 } 7437 7438 bool VisitConditionalOperator(const ConditionalOperator *E) { 7439 bool IsBcpCall = false; 7440 // If the condition (ignoring parens) is a __builtin_constant_p call, 7441 // the result is a constant expression if it can be folded without 7442 // side-effects. This is an important GNU extension. See GCC PR38377 7443 // for discussion. 7444 if (const CallExpr *CallCE = 7445 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7446 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7447 IsBcpCall = true; 7448 7449 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7450 // constant expression; we can't check whether it's potentially foldable. 7451 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7452 // it would return 'false' in this mode. 7453 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7454 return false; 7455 7456 FoldConstant Fold(Info, IsBcpCall); 7457 if (!HandleConditionalOperator(E)) { 7458 Fold.keepDiagnostics(); 7459 return false; 7460 } 7461 7462 return true; 7463 } 7464 7465 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7466 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7467 return DerivedSuccess(*Value, E); 7468 7469 const Expr *Source = E->getSourceExpr(); 7470 if (!Source) 7471 return Error(E); 7472 if (Source == E) { // sanity checking. 7473 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7474 return Error(E); 7475 } 7476 return StmtVisitorTy::Visit(Source); 7477 } 7478 7479 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7480 for (const Expr *SemE : E->semantics()) { 7481 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7482 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7483 // result expression: there could be two different LValues that would 7484 // refer to the same object in that case, and we can't model that. 7485 if (SemE == E->getResultExpr()) 7486 return Error(E); 7487 7488 // Unique OVEs get evaluated if and when we encounter them when 7489 // emitting the rest of the semantic form, rather than eagerly. 7490 if (OVE->isUnique()) 7491 continue; 7492 7493 LValue LV; 7494 if (!Evaluate(Info.CurrentCall->createTemporary( 7495 OVE, getStorageType(Info.Ctx, OVE), 7496 ScopeKind::FullExpression, LV), 7497 Info, OVE->getSourceExpr())) 7498 return false; 7499 } else if (SemE == E->getResultExpr()) { 7500 if (!StmtVisitorTy::Visit(SemE)) 7501 return false; 7502 } else { 7503 if (!EvaluateIgnoredValue(Info, SemE)) 7504 return false; 7505 } 7506 } 7507 return true; 7508 } 7509 7510 bool VisitCallExpr(const CallExpr *E) { 7511 APValue Result; 7512 if (!handleCallExpr(E, Result, nullptr)) 7513 return false; 7514 return DerivedSuccess(Result, E); 7515 } 7516 7517 bool handleCallExpr(const CallExpr *E, APValue &Result, 7518 const LValue *ResultSlot) { 7519 CallScopeRAII CallScope(Info); 7520 7521 const Expr *Callee = E->getCallee()->IgnoreParens(); 7522 QualType CalleeType = Callee->getType(); 7523 7524 const FunctionDecl *FD = nullptr; 7525 LValue *This = nullptr, ThisVal; 7526 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7527 bool HasQualifier = false; 7528 7529 CallRef Call; 7530 7531 // Extract function decl and 'this' pointer from the callee. 7532 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7533 const CXXMethodDecl *Member = nullptr; 7534 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7535 // Explicit bound member calls, such as x.f() or p->g(); 7536 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7537 return false; 7538 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7539 if (!Member) 7540 return Error(Callee); 7541 This = &ThisVal; 7542 HasQualifier = ME->hasQualifier(); 7543 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7544 // Indirect bound member calls ('.*' or '->*'). 7545 const ValueDecl *D = 7546 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7547 if (!D) 7548 return false; 7549 Member = dyn_cast<CXXMethodDecl>(D); 7550 if (!Member) 7551 return Error(Callee); 7552 This = &ThisVal; 7553 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7554 if (!Info.getLangOpts().CPlusPlus20) 7555 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7556 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7557 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7558 } else 7559 return Error(Callee); 7560 FD = Member; 7561 } else if (CalleeType->isFunctionPointerType()) { 7562 LValue CalleeLV; 7563 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7564 return false; 7565 7566 if (!CalleeLV.getLValueOffset().isZero()) 7567 return Error(Callee); 7568 FD = dyn_cast_or_null<FunctionDecl>( 7569 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7570 if (!FD) 7571 return Error(Callee); 7572 // Don't call function pointers which have been cast to some other type. 7573 // Per DR (no number yet), the caller and callee can differ in noexcept. 7574 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7575 CalleeType->getPointeeType(), FD->getType())) { 7576 return Error(E); 7577 } 7578 7579 // For an (overloaded) assignment expression, evaluate the RHS before the 7580 // LHS. 7581 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7582 if (OCE && OCE->isAssignmentOp()) { 7583 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7584 Call = Info.CurrentCall->createCall(FD); 7585 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7586 Info, FD, /*RightToLeft=*/true)) 7587 return false; 7588 } 7589 7590 // Overloaded operator calls to member functions are represented as normal 7591 // calls with '*this' as the first argument. 7592 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7593 if (MD && !MD->isStatic()) { 7594 // FIXME: When selecting an implicit conversion for an overloaded 7595 // operator delete, we sometimes try to evaluate calls to conversion 7596 // operators without a 'this' parameter! 7597 if (Args.empty()) 7598 return Error(E); 7599 7600 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7601 return false; 7602 This = &ThisVal; 7603 Args = Args.slice(1); 7604 } else if (MD && MD->isLambdaStaticInvoker()) { 7605 // Map the static invoker for the lambda back to the call operator. 7606 // Conveniently, we don't have to slice out the 'this' argument (as is 7607 // being done for the non-static case), since a static member function 7608 // doesn't have an implicit argument passed in. 7609 const CXXRecordDecl *ClosureClass = MD->getParent(); 7610 assert( 7611 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7612 "Number of captures must be zero for conversion to function-ptr"); 7613 7614 const CXXMethodDecl *LambdaCallOp = 7615 ClosureClass->getLambdaCallOperator(); 7616 7617 // Set 'FD', the function that will be called below, to the call 7618 // operator. If the closure object represents a generic lambda, find 7619 // the corresponding specialization of the call operator. 7620 7621 if (ClosureClass->isGenericLambda()) { 7622 assert(MD->isFunctionTemplateSpecialization() && 7623 "A generic lambda's static-invoker function must be a " 7624 "template specialization"); 7625 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7626 FunctionTemplateDecl *CallOpTemplate = 7627 LambdaCallOp->getDescribedFunctionTemplate(); 7628 void *InsertPos = nullptr; 7629 FunctionDecl *CorrespondingCallOpSpecialization = 7630 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7631 assert(CorrespondingCallOpSpecialization && 7632 "We must always have a function call operator specialization " 7633 "that corresponds to our static invoker specialization"); 7634 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7635 } else 7636 FD = LambdaCallOp; 7637 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7638 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7639 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7640 LValue Ptr; 7641 if (!HandleOperatorNewCall(Info, E, Ptr)) 7642 return false; 7643 Ptr.moveInto(Result); 7644 return CallScope.destroy(); 7645 } else { 7646 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7647 } 7648 } 7649 } else 7650 return Error(E); 7651 7652 // Evaluate the arguments now if we've not already done so. 7653 if (!Call) { 7654 Call = Info.CurrentCall->createCall(FD); 7655 if (!EvaluateArgs(Args, Call, Info, FD)) 7656 return false; 7657 } 7658 7659 SmallVector<QualType, 4> CovariantAdjustmentPath; 7660 if (This) { 7661 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7662 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7663 // Perform virtual dispatch, if necessary. 7664 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7665 CovariantAdjustmentPath); 7666 if (!FD) 7667 return false; 7668 } else { 7669 // Check that the 'this' pointer points to an object of the right type. 7670 // FIXME: If this is an assignment operator call, we may need to change 7671 // the active union member before we check this. 7672 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7673 return false; 7674 } 7675 } 7676 7677 // Destructor calls are different enough that they have their own codepath. 7678 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7679 assert(This && "no 'this' pointer for destructor call"); 7680 return HandleDestruction(Info, E, *This, 7681 Info.Ctx.getRecordType(DD->getParent())) && 7682 CallScope.destroy(); 7683 } 7684 7685 const FunctionDecl *Definition = nullptr; 7686 Stmt *Body = FD->getBody(Definition); 7687 7688 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7689 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7690 Body, Info, Result, ResultSlot)) 7691 return false; 7692 7693 if (!CovariantAdjustmentPath.empty() && 7694 !HandleCovariantReturnAdjustment(Info, E, Result, 7695 CovariantAdjustmentPath)) 7696 return false; 7697 7698 return CallScope.destroy(); 7699 } 7700 7701 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7702 return StmtVisitorTy::Visit(E->getInitializer()); 7703 } 7704 bool VisitInitListExpr(const InitListExpr *E) { 7705 if (E->getNumInits() == 0) 7706 return DerivedZeroInitialization(E); 7707 if (E->getNumInits() == 1) 7708 return StmtVisitorTy::Visit(E->getInit(0)); 7709 return Error(E); 7710 } 7711 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7712 return DerivedZeroInitialization(E); 7713 } 7714 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7715 return DerivedZeroInitialization(E); 7716 } 7717 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7718 return DerivedZeroInitialization(E); 7719 } 7720 7721 /// A member expression where the object is a prvalue is itself a prvalue. 7722 bool VisitMemberExpr(const MemberExpr *E) { 7723 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7724 "missing temporary materialization conversion"); 7725 assert(!E->isArrow() && "missing call to bound member function?"); 7726 7727 APValue Val; 7728 if (!Evaluate(Val, Info, E->getBase())) 7729 return false; 7730 7731 QualType BaseTy = E->getBase()->getType(); 7732 7733 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7734 if (!FD) return Error(E); 7735 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7736 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7737 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7738 7739 // Note: there is no lvalue base here. But this case should only ever 7740 // happen in C or in C++98, where we cannot be evaluating a constexpr 7741 // constructor, which is the only case the base matters. 7742 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7743 SubobjectDesignator Designator(BaseTy); 7744 Designator.addDeclUnchecked(FD); 7745 7746 APValue Result; 7747 return extractSubobject(Info, E, Obj, Designator, Result) && 7748 DerivedSuccess(Result, E); 7749 } 7750 7751 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7752 APValue Val; 7753 if (!Evaluate(Val, Info, E->getBase())) 7754 return false; 7755 7756 if (Val.isVector()) { 7757 SmallVector<uint32_t, 4> Indices; 7758 E->getEncodedElementAccess(Indices); 7759 if (Indices.size() == 1) { 7760 // Return scalar. 7761 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7762 } else { 7763 // Construct new APValue vector. 7764 SmallVector<APValue, 4> Elts; 7765 for (unsigned I = 0; I < Indices.size(); ++I) { 7766 Elts.push_back(Val.getVectorElt(Indices[I])); 7767 } 7768 APValue VecResult(Elts.data(), Indices.size()); 7769 return DerivedSuccess(VecResult, E); 7770 } 7771 } 7772 7773 return false; 7774 } 7775 7776 bool VisitCastExpr(const CastExpr *E) { 7777 switch (E->getCastKind()) { 7778 default: 7779 break; 7780 7781 case CK_AtomicToNonAtomic: { 7782 APValue AtomicVal; 7783 // This does not need to be done in place even for class/array types: 7784 // atomic-to-non-atomic conversion implies copying the object 7785 // representation. 7786 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7787 return false; 7788 return DerivedSuccess(AtomicVal, E); 7789 } 7790 7791 case CK_NoOp: 7792 case CK_UserDefinedConversion: 7793 return StmtVisitorTy::Visit(E->getSubExpr()); 7794 7795 case CK_LValueToRValue: { 7796 LValue LVal; 7797 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7798 return false; 7799 APValue RVal; 7800 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7801 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7802 LVal, RVal)) 7803 return false; 7804 return DerivedSuccess(RVal, E); 7805 } 7806 case CK_LValueToRValueBitCast: { 7807 APValue DestValue, SourceValue; 7808 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7809 return false; 7810 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7811 return false; 7812 return DerivedSuccess(DestValue, E); 7813 } 7814 7815 case CK_AddressSpaceConversion: { 7816 APValue Value; 7817 if (!Evaluate(Value, Info, E->getSubExpr())) 7818 return false; 7819 return DerivedSuccess(Value, E); 7820 } 7821 } 7822 7823 return Error(E); 7824 } 7825 7826 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7827 return VisitUnaryPostIncDec(UO); 7828 } 7829 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7830 return VisitUnaryPostIncDec(UO); 7831 } 7832 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7833 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7834 return Error(UO); 7835 7836 LValue LVal; 7837 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7838 return false; 7839 APValue RVal; 7840 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7841 UO->isIncrementOp(), &RVal)) 7842 return false; 7843 return DerivedSuccess(RVal, UO); 7844 } 7845 7846 bool VisitStmtExpr(const StmtExpr *E) { 7847 // We will have checked the full-expressions inside the statement expression 7848 // when they were completed, and don't need to check them again now. 7849 if (Info.checkingForUndefinedBehavior()) 7850 return Error(E); 7851 7852 const CompoundStmt *CS = E->getSubStmt(); 7853 if (CS->body_empty()) 7854 return true; 7855 7856 BlockScopeRAII Scope(Info); 7857 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7858 BE = CS->body_end(); 7859 /**/; ++BI) { 7860 if (BI + 1 == BE) { 7861 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7862 if (!FinalExpr) { 7863 Info.FFDiag((*BI)->getBeginLoc(), 7864 diag::note_constexpr_stmt_expr_unsupported); 7865 return false; 7866 } 7867 return this->Visit(FinalExpr) && Scope.destroy(); 7868 } 7869 7870 APValue ReturnValue; 7871 StmtResult Result = { ReturnValue, nullptr }; 7872 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7873 if (ESR != ESR_Succeeded) { 7874 // FIXME: If the statement-expression terminated due to 'return', 7875 // 'break', or 'continue', it would be nice to propagate that to 7876 // the outer statement evaluation rather than bailing out. 7877 if (ESR != ESR_Failed) 7878 Info.FFDiag((*BI)->getBeginLoc(), 7879 diag::note_constexpr_stmt_expr_unsupported); 7880 return false; 7881 } 7882 } 7883 7884 llvm_unreachable("Return from function from the loop above."); 7885 } 7886 7887 /// Visit a value which is evaluated, but whose value is ignored. 7888 void VisitIgnoredValue(const Expr *E) { 7889 EvaluateIgnoredValue(Info, E); 7890 } 7891 7892 /// Potentially visit a MemberExpr's base expression. 7893 void VisitIgnoredBaseExpression(const Expr *E) { 7894 // While MSVC doesn't evaluate the base expression, it does diagnose the 7895 // presence of side-effecting behavior. 7896 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7897 return; 7898 VisitIgnoredValue(E); 7899 } 7900 }; 7901 7902 } // namespace 7903 7904 //===----------------------------------------------------------------------===// 7905 // Common base class for lvalue and temporary evaluation. 7906 //===----------------------------------------------------------------------===// 7907 namespace { 7908 template<class Derived> 7909 class LValueExprEvaluatorBase 7910 : public ExprEvaluatorBase<Derived> { 7911 protected: 7912 LValue &Result; 7913 bool InvalidBaseOK; 7914 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7915 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7916 7917 bool Success(APValue::LValueBase B) { 7918 Result.set(B); 7919 return true; 7920 } 7921 7922 bool evaluatePointer(const Expr *E, LValue &Result) { 7923 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7924 } 7925 7926 public: 7927 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7928 : ExprEvaluatorBaseTy(Info), Result(Result), 7929 InvalidBaseOK(InvalidBaseOK) {} 7930 7931 bool Success(const APValue &V, const Expr *E) { 7932 Result.setFrom(this->Info.Ctx, V); 7933 return true; 7934 } 7935 7936 bool VisitMemberExpr(const MemberExpr *E) { 7937 // Handle non-static data members. 7938 QualType BaseTy; 7939 bool EvalOK; 7940 if (E->isArrow()) { 7941 EvalOK = evaluatePointer(E->getBase(), Result); 7942 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7943 } else if (E->getBase()->isRValue()) { 7944 assert(E->getBase()->getType()->isRecordType()); 7945 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7946 BaseTy = E->getBase()->getType(); 7947 } else { 7948 EvalOK = this->Visit(E->getBase()); 7949 BaseTy = E->getBase()->getType(); 7950 } 7951 if (!EvalOK) { 7952 if (!InvalidBaseOK) 7953 return false; 7954 Result.setInvalid(E); 7955 return true; 7956 } 7957 7958 const ValueDecl *MD = E->getMemberDecl(); 7959 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7960 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7961 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7962 (void)BaseTy; 7963 if (!HandleLValueMember(this->Info, E, Result, FD)) 7964 return false; 7965 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7966 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7967 return false; 7968 } else 7969 return this->Error(E); 7970 7971 if (MD->getType()->isReferenceType()) { 7972 APValue RefValue; 7973 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7974 RefValue)) 7975 return false; 7976 return Success(RefValue, E); 7977 } 7978 return true; 7979 } 7980 7981 bool VisitBinaryOperator(const BinaryOperator *E) { 7982 switch (E->getOpcode()) { 7983 default: 7984 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7985 7986 case BO_PtrMemD: 7987 case BO_PtrMemI: 7988 return HandleMemberPointerAccess(this->Info, E, Result); 7989 } 7990 } 7991 7992 bool VisitCastExpr(const CastExpr *E) { 7993 switch (E->getCastKind()) { 7994 default: 7995 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7996 7997 case CK_DerivedToBase: 7998 case CK_UncheckedDerivedToBase: 7999 if (!this->Visit(E->getSubExpr())) 8000 return false; 8001 8002 // Now figure out the necessary offset to add to the base LV to get from 8003 // the derived class to the base class. 8004 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8005 Result); 8006 } 8007 } 8008 }; 8009 } 8010 8011 //===----------------------------------------------------------------------===// 8012 // LValue Evaluation 8013 // 8014 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8015 // function designators (in C), decl references to void objects (in C), and 8016 // temporaries (if building with -Wno-address-of-temporary). 8017 // 8018 // LValue evaluation produces values comprising a base expression of one of the 8019 // following types: 8020 // - Declarations 8021 // * VarDecl 8022 // * FunctionDecl 8023 // - Literals 8024 // * CompoundLiteralExpr in C (and in global scope in C++) 8025 // * StringLiteral 8026 // * PredefinedExpr 8027 // * ObjCStringLiteralExpr 8028 // * ObjCEncodeExpr 8029 // * AddrLabelExpr 8030 // * BlockExpr 8031 // * CallExpr for a MakeStringConstant builtin 8032 // - typeid(T) expressions, as TypeInfoLValues 8033 // - Locals and temporaries 8034 // * MaterializeTemporaryExpr 8035 // * Any Expr, with a CallIndex indicating the function in which the temporary 8036 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8037 // from the AST (FIXME). 8038 // * A MaterializeTemporaryExpr that has static storage duration, with no 8039 // CallIndex, for a lifetime-extended temporary. 8040 // * The ConstantExpr that is currently being evaluated during evaluation of an 8041 // immediate invocation. 8042 // plus an offset in bytes. 8043 //===----------------------------------------------------------------------===// 8044 namespace { 8045 class LValueExprEvaluator 8046 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8047 public: 8048 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8049 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8050 8051 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8052 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8053 8054 bool VisitDeclRefExpr(const DeclRefExpr *E); 8055 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8056 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8057 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8058 bool VisitMemberExpr(const MemberExpr *E); 8059 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8060 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8061 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8062 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8063 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8064 bool VisitUnaryDeref(const UnaryOperator *E); 8065 bool VisitUnaryReal(const UnaryOperator *E); 8066 bool VisitUnaryImag(const UnaryOperator *E); 8067 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8068 return VisitUnaryPreIncDec(UO); 8069 } 8070 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8071 return VisitUnaryPreIncDec(UO); 8072 } 8073 bool VisitBinAssign(const BinaryOperator *BO); 8074 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8075 8076 bool VisitCastExpr(const CastExpr *E) { 8077 switch (E->getCastKind()) { 8078 default: 8079 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8080 8081 case CK_LValueBitCast: 8082 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8083 if (!Visit(E->getSubExpr())) 8084 return false; 8085 Result.Designator.setInvalid(); 8086 return true; 8087 8088 case CK_BaseToDerived: 8089 if (!Visit(E->getSubExpr())) 8090 return false; 8091 return HandleBaseToDerivedCast(Info, E, Result); 8092 8093 case CK_Dynamic: 8094 if (!Visit(E->getSubExpr())) 8095 return false; 8096 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8097 } 8098 } 8099 }; 8100 } // end anonymous namespace 8101 8102 /// Evaluate an expression as an lvalue. This can be legitimately called on 8103 /// expressions which are not glvalues, in three cases: 8104 /// * function designators in C, and 8105 /// * "extern void" objects 8106 /// * @selector() expressions in Objective-C 8107 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8108 bool InvalidBaseOK) { 8109 assert(!E->isValueDependent()); 8110 assert(E->isGLValue() || E->getType()->isFunctionType() || 8111 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8112 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8113 } 8114 8115 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8116 const NamedDecl *D = E->getDecl(); 8117 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8118 return Success(cast<ValueDecl>(D)); 8119 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8120 return VisitVarDecl(E, VD); 8121 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8122 return Visit(BD->getBinding()); 8123 return Error(E); 8124 } 8125 8126 8127 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8128 8129 // If we are within a lambda's call operator, check whether the 'VD' referred 8130 // to within 'E' actually represents a lambda-capture that maps to a 8131 // data-member/field within the closure object, and if so, evaluate to the 8132 // field or what the field refers to. 8133 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8134 isa<DeclRefExpr>(E) && 8135 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8136 // We don't always have a complete capture-map when checking or inferring if 8137 // the function call operator meets the requirements of a constexpr function 8138 // - but we don't need to evaluate the captures to determine constexprness 8139 // (dcl.constexpr C++17). 8140 if (Info.checkingPotentialConstantExpression()) 8141 return false; 8142 8143 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8144 // Start with 'Result' referring to the complete closure object... 8145 Result = *Info.CurrentCall->This; 8146 // ... then update it to refer to the field of the closure object 8147 // that represents the capture. 8148 if (!HandleLValueMember(Info, E, Result, FD)) 8149 return false; 8150 // And if the field is of reference type, update 'Result' to refer to what 8151 // the field refers to. 8152 if (FD->getType()->isReferenceType()) { 8153 APValue RVal; 8154 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8155 RVal)) 8156 return false; 8157 Result.setFrom(Info.Ctx, RVal); 8158 } 8159 return true; 8160 } 8161 } 8162 8163 CallStackFrame *Frame = nullptr; 8164 unsigned Version = 0; 8165 if (VD->hasLocalStorage()) { 8166 // Only if a local variable was declared in the function currently being 8167 // evaluated, do we expect to be able to find its value in the current 8168 // frame. (Otherwise it was likely declared in an enclosing context and 8169 // could either have a valid evaluatable value (for e.g. a constexpr 8170 // variable) or be ill-formed (and trigger an appropriate evaluation 8171 // diagnostic)). 8172 CallStackFrame *CurrFrame = Info.CurrentCall; 8173 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8174 // Function parameters are stored in some caller's frame. (Usually the 8175 // immediate caller, but for an inherited constructor they may be more 8176 // distant.) 8177 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8178 if (CurrFrame->Arguments) { 8179 VD = CurrFrame->Arguments.getOrigParam(PVD); 8180 Frame = 8181 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8182 Version = CurrFrame->Arguments.Version; 8183 } 8184 } else { 8185 Frame = CurrFrame; 8186 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8187 } 8188 } 8189 } 8190 8191 if (!VD->getType()->isReferenceType()) { 8192 if (Frame) { 8193 Result.set({VD, Frame->Index, Version}); 8194 return true; 8195 } 8196 return Success(VD); 8197 } 8198 8199 if (!Info.getLangOpts().CPlusPlus11) { 8200 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8201 << VD << VD->getType(); 8202 Info.Note(VD->getLocation(), diag::note_declared_at); 8203 } 8204 8205 APValue *V; 8206 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8207 return false; 8208 if (!V->hasValue()) { 8209 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8210 // adjust the diagnostic to say that. 8211 if (!Info.checkingPotentialConstantExpression()) 8212 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8213 return false; 8214 } 8215 return Success(*V, E); 8216 } 8217 8218 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8219 const MaterializeTemporaryExpr *E) { 8220 // Walk through the expression to find the materialized temporary itself. 8221 SmallVector<const Expr *, 2> CommaLHSs; 8222 SmallVector<SubobjectAdjustment, 2> Adjustments; 8223 const Expr *Inner = 8224 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8225 8226 // If we passed any comma operators, evaluate their LHSs. 8227 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8228 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8229 return false; 8230 8231 // A materialized temporary with static storage duration can appear within the 8232 // result of a constant expression evaluation, so we need to preserve its 8233 // value for use outside this evaluation. 8234 APValue *Value; 8235 if (E->getStorageDuration() == SD_Static) { 8236 // FIXME: What about SD_Thread? 8237 Value = E->getOrCreateValue(true); 8238 *Value = APValue(); 8239 Result.set(E); 8240 } else { 8241 Value = &Info.CurrentCall->createTemporary( 8242 E, E->getType(), 8243 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8244 : ScopeKind::Block, 8245 Result); 8246 } 8247 8248 QualType Type = Inner->getType(); 8249 8250 // Materialize the temporary itself. 8251 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8252 *Value = APValue(); 8253 return false; 8254 } 8255 8256 // Adjust our lvalue to refer to the desired subobject. 8257 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8258 --I; 8259 switch (Adjustments[I].Kind) { 8260 case SubobjectAdjustment::DerivedToBaseAdjustment: 8261 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8262 Type, Result)) 8263 return false; 8264 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8265 break; 8266 8267 case SubobjectAdjustment::FieldAdjustment: 8268 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8269 return false; 8270 Type = Adjustments[I].Field->getType(); 8271 break; 8272 8273 case SubobjectAdjustment::MemberPointerAdjustment: 8274 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8275 Adjustments[I].Ptr.RHS)) 8276 return false; 8277 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8278 break; 8279 } 8280 } 8281 8282 return true; 8283 } 8284 8285 bool 8286 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8287 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8288 "lvalue compound literal in c++?"); 8289 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8290 // only see this when folding in C, so there's no standard to follow here. 8291 return Success(E); 8292 } 8293 8294 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8295 TypeInfoLValue TypeInfo; 8296 8297 if (!E->isPotentiallyEvaluated()) { 8298 if (E->isTypeOperand()) 8299 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8300 else 8301 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8302 } else { 8303 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8304 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8305 << E->getExprOperand()->getType() 8306 << E->getExprOperand()->getSourceRange(); 8307 } 8308 8309 if (!Visit(E->getExprOperand())) 8310 return false; 8311 8312 Optional<DynamicType> DynType = 8313 ComputeDynamicType(Info, E, Result, AK_TypeId); 8314 if (!DynType) 8315 return false; 8316 8317 TypeInfo = 8318 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8319 } 8320 8321 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8322 } 8323 8324 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8325 return Success(E->getGuidDecl()); 8326 } 8327 8328 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8329 // Handle static data members. 8330 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8331 VisitIgnoredBaseExpression(E->getBase()); 8332 return VisitVarDecl(E, VD); 8333 } 8334 8335 // Handle static member functions. 8336 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8337 if (MD->isStatic()) { 8338 VisitIgnoredBaseExpression(E->getBase()); 8339 return Success(MD); 8340 } 8341 } 8342 8343 // Handle non-static data members. 8344 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8345 } 8346 8347 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8348 // FIXME: Deal with vectors as array subscript bases. 8349 if (E->getBase()->getType()->isVectorType()) 8350 return Error(E); 8351 8352 APSInt Index; 8353 bool Success = true; 8354 8355 // C++17's rules require us to evaluate the LHS first, regardless of which 8356 // side is the base. 8357 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8358 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8359 : !EvaluateInteger(SubExpr, Index, Info)) { 8360 if (!Info.noteFailure()) 8361 return false; 8362 Success = false; 8363 } 8364 } 8365 8366 return Success && 8367 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8368 } 8369 8370 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8371 return evaluatePointer(E->getSubExpr(), Result); 8372 } 8373 8374 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8375 if (!Visit(E->getSubExpr())) 8376 return false; 8377 // __real is a no-op on scalar lvalues. 8378 if (E->getSubExpr()->getType()->isAnyComplexType()) 8379 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8380 return true; 8381 } 8382 8383 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8384 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8385 "lvalue __imag__ on scalar?"); 8386 if (!Visit(E->getSubExpr())) 8387 return false; 8388 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8389 return true; 8390 } 8391 8392 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8393 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8394 return Error(UO); 8395 8396 if (!this->Visit(UO->getSubExpr())) 8397 return false; 8398 8399 return handleIncDec( 8400 this->Info, UO, Result, UO->getSubExpr()->getType(), 8401 UO->isIncrementOp(), nullptr); 8402 } 8403 8404 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8405 const CompoundAssignOperator *CAO) { 8406 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8407 return Error(CAO); 8408 8409 bool Success = true; 8410 8411 // C++17 onwards require that we evaluate the RHS first. 8412 APValue RHS; 8413 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8414 if (!Info.noteFailure()) 8415 return false; 8416 Success = false; 8417 } 8418 8419 // The overall lvalue result is the result of evaluating the LHS. 8420 if (!this->Visit(CAO->getLHS()) || !Success) 8421 return false; 8422 8423 return handleCompoundAssignment( 8424 this->Info, CAO, 8425 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8426 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8427 } 8428 8429 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8430 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8431 return Error(E); 8432 8433 bool Success = true; 8434 8435 // C++17 onwards require that we evaluate the RHS first. 8436 APValue NewVal; 8437 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8438 if (!Info.noteFailure()) 8439 return false; 8440 Success = false; 8441 } 8442 8443 if (!this->Visit(E->getLHS()) || !Success) 8444 return false; 8445 8446 if (Info.getLangOpts().CPlusPlus20 && 8447 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8448 return false; 8449 8450 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8451 NewVal); 8452 } 8453 8454 //===----------------------------------------------------------------------===// 8455 // Pointer Evaluation 8456 //===----------------------------------------------------------------------===// 8457 8458 /// Attempts to compute the number of bytes available at the pointer 8459 /// returned by a function with the alloc_size attribute. Returns true if we 8460 /// were successful. Places an unsigned number into `Result`. 8461 /// 8462 /// This expects the given CallExpr to be a call to a function with an 8463 /// alloc_size attribute. 8464 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8465 const CallExpr *Call, 8466 llvm::APInt &Result) { 8467 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8468 8469 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8470 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8471 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8472 if (Call->getNumArgs() <= SizeArgNo) 8473 return false; 8474 8475 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8476 Expr::EvalResult ExprResult; 8477 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8478 return false; 8479 Into = ExprResult.Val.getInt(); 8480 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8481 return false; 8482 Into = Into.zextOrSelf(BitsInSizeT); 8483 return true; 8484 }; 8485 8486 APSInt SizeOfElem; 8487 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8488 return false; 8489 8490 if (!AllocSize->getNumElemsParam().isValid()) { 8491 Result = std::move(SizeOfElem); 8492 return true; 8493 } 8494 8495 APSInt NumberOfElems; 8496 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8497 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8498 return false; 8499 8500 bool Overflow; 8501 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8502 if (Overflow) 8503 return false; 8504 8505 Result = std::move(BytesAvailable); 8506 return true; 8507 } 8508 8509 /// Convenience function. LVal's base must be a call to an alloc_size 8510 /// function. 8511 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8512 const LValue &LVal, 8513 llvm::APInt &Result) { 8514 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8515 "Can't get the size of a non alloc_size function"); 8516 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8517 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8518 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8519 } 8520 8521 /// Attempts to evaluate the given LValueBase as the result of a call to 8522 /// a function with the alloc_size attribute. If it was possible to do so, this 8523 /// function will return true, make Result's Base point to said function call, 8524 /// and mark Result's Base as invalid. 8525 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8526 LValue &Result) { 8527 if (Base.isNull()) 8528 return false; 8529 8530 // Because we do no form of static analysis, we only support const variables. 8531 // 8532 // Additionally, we can't support parameters, nor can we support static 8533 // variables (in the latter case, use-before-assign isn't UB; in the former, 8534 // we have no clue what they'll be assigned to). 8535 const auto *VD = 8536 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8537 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8538 return false; 8539 8540 const Expr *Init = VD->getAnyInitializer(); 8541 if (!Init) 8542 return false; 8543 8544 const Expr *E = Init->IgnoreParens(); 8545 if (!tryUnwrapAllocSizeCall(E)) 8546 return false; 8547 8548 // Store E instead of E unwrapped so that the type of the LValue's base is 8549 // what the user wanted. 8550 Result.setInvalid(E); 8551 8552 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8553 Result.addUnsizedArray(Info, E, Pointee); 8554 return true; 8555 } 8556 8557 namespace { 8558 class PointerExprEvaluator 8559 : public ExprEvaluatorBase<PointerExprEvaluator> { 8560 LValue &Result; 8561 bool InvalidBaseOK; 8562 8563 bool Success(const Expr *E) { 8564 Result.set(E); 8565 return true; 8566 } 8567 8568 bool evaluateLValue(const Expr *E, LValue &Result) { 8569 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8570 } 8571 8572 bool evaluatePointer(const Expr *E, LValue &Result) { 8573 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8574 } 8575 8576 bool visitNonBuiltinCallExpr(const CallExpr *E); 8577 public: 8578 8579 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8580 : ExprEvaluatorBaseTy(info), Result(Result), 8581 InvalidBaseOK(InvalidBaseOK) {} 8582 8583 bool Success(const APValue &V, const Expr *E) { 8584 Result.setFrom(Info.Ctx, V); 8585 return true; 8586 } 8587 bool ZeroInitialization(const Expr *E) { 8588 Result.setNull(Info.Ctx, E->getType()); 8589 return true; 8590 } 8591 8592 bool VisitBinaryOperator(const BinaryOperator *E); 8593 bool VisitCastExpr(const CastExpr* E); 8594 bool VisitUnaryAddrOf(const UnaryOperator *E); 8595 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8596 { return Success(E); } 8597 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8598 if (E->isExpressibleAsConstantInitializer()) 8599 return Success(E); 8600 if (Info.noteFailure()) 8601 EvaluateIgnoredValue(Info, E->getSubExpr()); 8602 return Error(E); 8603 } 8604 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8605 { return Success(E); } 8606 bool VisitCallExpr(const CallExpr *E); 8607 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8608 bool VisitBlockExpr(const BlockExpr *E) { 8609 if (!E->getBlockDecl()->hasCaptures()) 8610 return Success(E); 8611 return Error(E); 8612 } 8613 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8614 // Can't look at 'this' when checking a potential constant expression. 8615 if (Info.checkingPotentialConstantExpression()) 8616 return false; 8617 if (!Info.CurrentCall->This) { 8618 if (Info.getLangOpts().CPlusPlus11) 8619 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8620 else 8621 Info.FFDiag(E); 8622 return false; 8623 } 8624 Result = *Info.CurrentCall->This; 8625 // If we are inside a lambda's call operator, the 'this' expression refers 8626 // to the enclosing '*this' object (either by value or reference) which is 8627 // either copied into the closure object's field that represents the '*this' 8628 // or refers to '*this'. 8629 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8630 // Ensure we actually have captured 'this'. (an error will have 8631 // been previously reported if not). 8632 if (!Info.CurrentCall->LambdaThisCaptureField) 8633 return false; 8634 8635 // Update 'Result' to refer to the data member/field of the closure object 8636 // that represents the '*this' capture. 8637 if (!HandleLValueMember(Info, E, Result, 8638 Info.CurrentCall->LambdaThisCaptureField)) 8639 return false; 8640 // If we captured '*this' by reference, replace the field with its referent. 8641 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8642 ->isPointerType()) { 8643 APValue RVal; 8644 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8645 RVal)) 8646 return false; 8647 8648 Result.setFrom(Info.Ctx, RVal); 8649 } 8650 } 8651 return true; 8652 } 8653 8654 bool VisitCXXNewExpr(const CXXNewExpr *E); 8655 8656 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8657 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8658 APValue LValResult = E->EvaluateInContext( 8659 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8660 Result.setFrom(Info.Ctx, LValResult); 8661 return true; 8662 } 8663 8664 // FIXME: Missing: @protocol, @selector 8665 }; 8666 } // end anonymous namespace 8667 8668 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8669 bool InvalidBaseOK) { 8670 assert(!E->isValueDependent()); 8671 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8672 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8673 } 8674 8675 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8676 if (E->getOpcode() != BO_Add && 8677 E->getOpcode() != BO_Sub) 8678 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8679 8680 const Expr *PExp = E->getLHS(); 8681 const Expr *IExp = E->getRHS(); 8682 if (IExp->getType()->isPointerType()) 8683 std::swap(PExp, IExp); 8684 8685 bool EvalPtrOK = evaluatePointer(PExp, Result); 8686 if (!EvalPtrOK && !Info.noteFailure()) 8687 return false; 8688 8689 llvm::APSInt Offset; 8690 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8691 return false; 8692 8693 if (E->getOpcode() == BO_Sub) 8694 negateAsSigned(Offset); 8695 8696 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8697 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8698 } 8699 8700 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8701 return evaluateLValue(E->getSubExpr(), Result); 8702 } 8703 8704 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8705 const Expr *SubExpr = E->getSubExpr(); 8706 8707 switch (E->getCastKind()) { 8708 default: 8709 break; 8710 case CK_BitCast: 8711 case CK_CPointerToObjCPointerCast: 8712 case CK_BlockPointerToObjCPointerCast: 8713 case CK_AnyPointerToBlockPointerCast: 8714 case CK_AddressSpaceConversion: 8715 if (!Visit(SubExpr)) 8716 return false; 8717 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8718 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8719 // also static_casts, but we disallow them as a resolution to DR1312. 8720 if (!E->getType()->isVoidPointerType()) { 8721 if (!Result.InvalidBase && !Result.Designator.Invalid && 8722 !Result.IsNullPtr && 8723 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8724 E->getType()->getPointeeType()) && 8725 Info.getStdAllocatorCaller("allocate")) { 8726 // Inside a call to std::allocator::allocate and friends, we permit 8727 // casting from void* back to cv1 T* for a pointer that points to a 8728 // cv2 T. 8729 } else { 8730 Result.Designator.setInvalid(); 8731 if (SubExpr->getType()->isVoidPointerType()) 8732 CCEDiag(E, diag::note_constexpr_invalid_cast) 8733 << 3 << SubExpr->getType(); 8734 else 8735 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8736 } 8737 } 8738 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8739 ZeroInitialization(E); 8740 return true; 8741 8742 case CK_DerivedToBase: 8743 case CK_UncheckedDerivedToBase: 8744 if (!evaluatePointer(E->getSubExpr(), Result)) 8745 return false; 8746 if (!Result.Base && Result.Offset.isZero()) 8747 return true; 8748 8749 // Now figure out the necessary offset to add to the base LV to get from 8750 // the derived class to the base class. 8751 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8752 castAs<PointerType>()->getPointeeType(), 8753 Result); 8754 8755 case CK_BaseToDerived: 8756 if (!Visit(E->getSubExpr())) 8757 return false; 8758 if (!Result.Base && Result.Offset.isZero()) 8759 return true; 8760 return HandleBaseToDerivedCast(Info, E, Result); 8761 8762 case CK_Dynamic: 8763 if (!Visit(E->getSubExpr())) 8764 return false; 8765 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8766 8767 case CK_NullToPointer: 8768 VisitIgnoredValue(E->getSubExpr()); 8769 return ZeroInitialization(E); 8770 8771 case CK_IntegralToPointer: { 8772 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8773 8774 APValue Value; 8775 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8776 break; 8777 8778 if (Value.isInt()) { 8779 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8780 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8781 Result.Base = (Expr*)nullptr; 8782 Result.InvalidBase = false; 8783 Result.Offset = CharUnits::fromQuantity(N); 8784 Result.Designator.setInvalid(); 8785 Result.IsNullPtr = false; 8786 return true; 8787 } else { 8788 // Cast is of an lvalue, no need to change value. 8789 Result.setFrom(Info.Ctx, Value); 8790 return true; 8791 } 8792 } 8793 8794 case CK_ArrayToPointerDecay: { 8795 if (SubExpr->isGLValue()) { 8796 if (!evaluateLValue(SubExpr, Result)) 8797 return false; 8798 } else { 8799 APValue &Value = Info.CurrentCall->createTemporary( 8800 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8801 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8802 return false; 8803 } 8804 // The result is a pointer to the first element of the array. 8805 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8806 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8807 Result.addArray(Info, E, CAT); 8808 else 8809 Result.addUnsizedArray(Info, E, AT->getElementType()); 8810 return true; 8811 } 8812 8813 case CK_FunctionToPointerDecay: 8814 return evaluateLValue(SubExpr, Result); 8815 8816 case CK_LValueToRValue: { 8817 LValue LVal; 8818 if (!evaluateLValue(E->getSubExpr(), LVal)) 8819 return false; 8820 8821 APValue RVal; 8822 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8823 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8824 LVal, RVal)) 8825 return InvalidBaseOK && 8826 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8827 return Success(RVal, E); 8828 } 8829 } 8830 8831 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8832 } 8833 8834 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8835 UnaryExprOrTypeTrait ExprKind) { 8836 // C++ [expr.alignof]p3: 8837 // When alignof is applied to a reference type, the result is the 8838 // alignment of the referenced type. 8839 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8840 T = Ref->getPointeeType(); 8841 8842 if (T.getQualifiers().hasUnaligned()) 8843 return CharUnits::One(); 8844 8845 const bool AlignOfReturnsPreferred = 8846 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8847 8848 // __alignof is defined to return the preferred alignment. 8849 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8850 // as well. 8851 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8852 return Info.Ctx.toCharUnitsFromBits( 8853 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8854 // alignof and _Alignof are defined to return the ABI alignment. 8855 else if (ExprKind == UETT_AlignOf) 8856 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8857 else 8858 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8859 } 8860 8861 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8862 UnaryExprOrTypeTrait ExprKind) { 8863 E = E->IgnoreParens(); 8864 8865 // The kinds of expressions that we have special-case logic here for 8866 // should be kept up to date with the special checks for those 8867 // expressions in Sema. 8868 8869 // alignof decl is always accepted, even if it doesn't make sense: we default 8870 // to 1 in those cases. 8871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8872 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8873 /*RefAsPointee*/true); 8874 8875 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8876 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8877 /*RefAsPointee*/true); 8878 8879 return GetAlignOfType(Info, E->getType(), ExprKind); 8880 } 8881 8882 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8883 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8884 return Info.Ctx.getDeclAlign(VD); 8885 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8886 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8887 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8888 } 8889 8890 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8891 /// __builtin_is_aligned and __builtin_assume_aligned. 8892 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8893 EvalInfo &Info, APSInt &Alignment) { 8894 if (!EvaluateInteger(E, Alignment, Info)) 8895 return false; 8896 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8897 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8898 return false; 8899 } 8900 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8901 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8902 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8903 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8904 << MaxValue << ForType << Alignment; 8905 return false; 8906 } 8907 // Ensure both alignment and source value have the same bit width so that we 8908 // don't assert when computing the resulting value. 8909 APSInt ExtAlignment = 8910 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8911 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8912 "Alignment should not be changed by ext/trunc"); 8913 Alignment = ExtAlignment; 8914 assert(Alignment.getBitWidth() == SrcWidth); 8915 return true; 8916 } 8917 8918 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8919 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8920 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8921 return true; 8922 8923 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8924 return false; 8925 8926 Result.setInvalid(E); 8927 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8928 Result.addUnsizedArray(Info, E, PointeeTy); 8929 return true; 8930 } 8931 8932 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8933 if (IsStringLiteralCall(E)) 8934 return Success(E); 8935 8936 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8937 return VisitBuiltinCallExpr(E, BuiltinOp); 8938 8939 return visitNonBuiltinCallExpr(E); 8940 } 8941 8942 // Determine if T is a character type for which we guarantee that 8943 // sizeof(T) == 1. 8944 static bool isOneByteCharacterType(QualType T) { 8945 return T->isCharType() || T->isChar8Type(); 8946 } 8947 8948 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8949 unsigned BuiltinOp) { 8950 switch (BuiltinOp) { 8951 case Builtin::BI__builtin_addressof: 8952 return evaluateLValue(E->getArg(0), Result); 8953 case Builtin::BI__builtin_assume_aligned: { 8954 // We need to be very careful here because: if the pointer does not have the 8955 // asserted alignment, then the behavior is undefined, and undefined 8956 // behavior is non-constant. 8957 if (!evaluatePointer(E->getArg(0), Result)) 8958 return false; 8959 8960 LValue OffsetResult(Result); 8961 APSInt Alignment; 8962 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8963 Alignment)) 8964 return false; 8965 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8966 8967 if (E->getNumArgs() > 2) { 8968 APSInt Offset; 8969 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8970 return false; 8971 8972 int64_t AdditionalOffset = -Offset.getZExtValue(); 8973 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8974 } 8975 8976 // If there is a base object, then it must have the correct alignment. 8977 if (OffsetResult.Base) { 8978 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8979 8980 if (BaseAlignment < Align) { 8981 Result.Designator.setInvalid(); 8982 // FIXME: Add support to Diagnostic for long / long long. 8983 CCEDiag(E->getArg(0), 8984 diag::note_constexpr_baa_insufficient_alignment) << 0 8985 << (unsigned)BaseAlignment.getQuantity() 8986 << (unsigned)Align.getQuantity(); 8987 return false; 8988 } 8989 } 8990 8991 // The offset must also have the correct alignment. 8992 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8993 Result.Designator.setInvalid(); 8994 8995 (OffsetResult.Base 8996 ? CCEDiag(E->getArg(0), 8997 diag::note_constexpr_baa_insufficient_alignment) << 1 8998 : CCEDiag(E->getArg(0), 8999 diag::note_constexpr_baa_value_insufficient_alignment)) 9000 << (int)OffsetResult.Offset.getQuantity() 9001 << (unsigned)Align.getQuantity(); 9002 return false; 9003 } 9004 9005 return true; 9006 } 9007 case Builtin::BI__builtin_align_up: 9008 case Builtin::BI__builtin_align_down: { 9009 if (!evaluatePointer(E->getArg(0), Result)) 9010 return false; 9011 APSInt Alignment; 9012 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9013 Alignment)) 9014 return false; 9015 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9016 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9017 // For align_up/align_down, we can return the same value if the alignment 9018 // is known to be greater or equal to the requested value. 9019 if (PtrAlign.getQuantity() >= Alignment) 9020 return true; 9021 9022 // The alignment could be greater than the minimum at run-time, so we cannot 9023 // infer much about the resulting pointer value. One case is possible: 9024 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9025 // can infer the correct index if the requested alignment is smaller than 9026 // the base alignment so we can perform the computation on the offset. 9027 if (BaseAlignment.getQuantity() >= Alignment) { 9028 assert(Alignment.getBitWidth() <= 64 && 9029 "Cannot handle > 64-bit address-space"); 9030 uint64_t Alignment64 = Alignment.getZExtValue(); 9031 CharUnits NewOffset = CharUnits::fromQuantity( 9032 BuiltinOp == Builtin::BI__builtin_align_down 9033 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9034 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9035 Result.adjustOffset(NewOffset - Result.Offset); 9036 // TODO: diagnose out-of-bounds values/only allow for arrays? 9037 return true; 9038 } 9039 // Otherwise, we cannot constant-evaluate the result. 9040 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9041 << Alignment; 9042 return false; 9043 } 9044 case Builtin::BI__builtin_operator_new: 9045 return HandleOperatorNewCall(Info, E, Result); 9046 case Builtin::BI__builtin_launder: 9047 return evaluatePointer(E->getArg(0), Result); 9048 case Builtin::BIstrchr: 9049 case Builtin::BIwcschr: 9050 case Builtin::BImemchr: 9051 case Builtin::BIwmemchr: 9052 if (Info.getLangOpts().CPlusPlus11) 9053 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9054 << /*isConstexpr*/0 << /*isConstructor*/0 9055 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9056 else 9057 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9058 LLVM_FALLTHROUGH; 9059 case Builtin::BI__builtin_strchr: 9060 case Builtin::BI__builtin_wcschr: 9061 case Builtin::BI__builtin_memchr: 9062 case Builtin::BI__builtin_char_memchr: 9063 case Builtin::BI__builtin_wmemchr: { 9064 if (!Visit(E->getArg(0))) 9065 return false; 9066 APSInt Desired; 9067 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9068 return false; 9069 uint64_t MaxLength = uint64_t(-1); 9070 if (BuiltinOp != Builtin::BIstrchr && 9071 BuiltinOp != Builtin::BIwcschr && 9072 BuiltinOp != Builtin::BI__builtin_strchr && 9073 BuiltinOp != Builtin::BI__builtin_wcschr) { 9074 APSInt N; 9075 if (!EvaluateInteger(E->getArg(2), N, Info)) 9076 return false; 9077 MaxLength = N.getExtValue(); 9078 } 9079 // We cannot find the value if there are no candidates to match against. 9080 if (MaxLength == 0u) 9081 return ZeroInitialization(E); 9082 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9083 Result.Designator.Invalid) 9084 return false; 9085 QualType CharTy = Result.Designator.getType(Info.Ctx); 9086 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9087 BuiltinOp == Builtin::BI__builtin_memchr; 9088 assert(IsRawByte || 9089 Info.Ctx.hasSameUnqualifiedType( 9090 CharTy, E->getArg(0)->getType()->getPointeeType())); 9091 // Pointers to const void may point to objects of incomplete type. 9092 if (IsRawByte && CharTy->isIncompleteType()) { 9093 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9094 return false; 9095 } 9096 // Give up on byte-oriented matching against multibyte elements. 9097 // FIXME: We can compare the bytes in the correct order. 9098 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9099 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9100 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9101 << CharTy; 9102 return false; 9103 } 9104 // Figure out what value we're actually looking for (after converting to 9105 // the corresponding unsigned type if necessary). 9106 uint64_t DesiredVal; 9107 bool StopAtNull = false; 9108 switch (BuiltinOp) { 9109 case Builtin::BIstrchr: 9110 case Builtin::BI__builtin_strchr: 9111 // strchr compares directly to the passed integer, and therefore 9112 // always fails if given an int that is not a char. 9113 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9114 E->getArg(1)->getType(), 9115 Desired), 9116 Desired)) 9117 return ZeroInitialization(E); 9118 StopAtNull = true; 9119 LLVM_FALLTHROUGH; 9120 case Builtin::BImemchr: 9121 case Builtin::BI__builtin_memchr: 9122 case Builtin::BI__builtin_char_memchr: 9123 // memchr compares by converting both sides to unsigned char. That's also 9124 // correct for strchr if we get this far (to cope with plain char being 9125 // unsigned in the strchr case). 9126 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9127 break; 9128 9129 case Builtin::BIwcschr: 9130 case Builtin::BI__builtin_wcschr: 9131 StopAtNull = true; 9132 LLVM_FALLTHROUGH; 9133 case Builtin::BIwmemchr: 9134 case Builtin::BI__builtin_wmemchr: 9135 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9136 DesiredVal = Desired.getZExtValue(); 9137 break; 9138 } 9139 9140 for (; MaxLength; --MaxLength) { 9141 APValue Char; 9142 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9143 !Char.isInt()) 9144 return false; 9145 if (Char.getInt().getZExtValue() == DesiredVal) 9146 return true; 9147 if (StopAtNull && !Char.getInt()) 9148 break; 9149 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9150 return false; 9151 } 9152 // Not found: return nullptr. 9153 return ZeroInitialization(E); 9154 } 9155 9156 case Builtin::BImemcpy: 9157 case Builtin::BImemmove: 9158 case Builtin::BIwmemcpy: 9159 case Builtin::BIwmemmove: 9160 if (Info.getLangOpts().CPlusPlus11) 9161 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9162 << /*isConstexpr*/0 << /*isConstructor*/0 9163 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9164 else 9165 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9166 LLVM_FALLTHROUGH; 9167 case Builtin::BI__builtin_memcpy: 9168 case Builtin::BI__builtin_memmove: 9169 case Builtin::BI__builtin_wmemcpy: 9170 case Builtin::BI__builtin_wmemmove: { 9171 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9172 BuiltinOp == Builtin::BIwmemmove || 9173 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9174 BuiltinOp == Builtin::BI__builtin_wmemmove; 9175 bool Move = BuiltinOp == Builtin::BImemmove || 9176 BuiltinOp == Builtin::BIwmemmove || 9177 BuiltinOp == Builtin::BI__builtin_memmove || 9178 BuiltinOp == Builtin::BI__builtin_wmemmove; 9179 9180 // The result of mem* is the first argument. 9181 if (!Visit(E->getArg(0))) 9182 return false; 9183 LValue Dest = Result; 9184 9185 LValue Src; 9186 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9187 return false; 9188 9189 APSInt N; 9190 if (!EvaluateInteger(E->getArg(2), N, Info)) 9191 return false; 9192 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9193 9194 // If the size is zero, we treat this as always being a valid no-op. 9195 // (Even if one of the src and dest pointers is null.) 9196 if (!N) 9197 return true; 9198 9199 // Otherwise, if either of the operands is null, we can't proceed. Don't 9200 // try to determine the type of the copied objects, because there aren't 9201 // any. 9202 if (!Src.Base || !Dest.Base) { 9203 APValue Val; 9204 (!Src.Base ? Src : Dest).moveInto(Val); 9205 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9206 << Move << WChar << !!Src.Base 9207 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9208 return false; 9209 } 9210 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9211 return false; 9212 9213 // We require that Src and Dest are both pointers to arrays of 9214 // trivially-copyable type. (For the wide version, the designator will be 9215 // invalid if the designated object is not a wchar_t.) 9216 QualType T = Dest.Designator.getType(Info.Ctx); 9217 QualType SrcT = Src.Designator.getType(Info.Ctx); 9218 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9219 // FIXME: Consider using our bit_cast implementation to support this. 9220 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9221 return false; 9222 } 9223 if (T->isIncompleteType()) { 9224 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9225 return false; 9226 } 9227 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9228 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9229 return false; 9230 } 9231 9232 // Figure out how many T's we're copying. 9233 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9234 if (!WChar) { 9235 uint64_t Remainder; 9236 llvm::APInt OrigN = N; 9237 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9238 if (Remainder) { 9239 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9240 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9241 << (unsigned)TSize; 9242 return false; 9243 } 9244 } 9245 9246 // Check that the copying will remain within the arrays, just so that we 9247 // can give a more meaningful diagnostic. This implicitly also checks that 9248 // N fits into 64 bits. 9249 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9250 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9251 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9252 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9253 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9254 << N.toString(10, /*Signed*/false); 9255 return false; 9256 } 9257 uint64_t NElems = N.getZExtValue(); 9258 uint64_t NBytes = NElems * TSize; 9259 9260 // Check for overlap. 9261 int Direction = 1; 9262 if (HasSameBase(Src, Dest)) { 9263 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9264 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9265 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9266 // Dest is inside the source region. 9267 if (!Move) { 9268 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9269 return false; 9270 } 9271 // For memmove and friends, copy backwards. 9272 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9273 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9274 return false; 9275 Direction = -1; 9276 } else if (!Move && SrcOffset >= DestOffset && 9277 SrcOffset - DestOffset < NBytes) { 9278 // Src is inside the destination region for memcpy: invalid. 9279 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9280 return false; 9281 } 9282 } 9283 9284 while (true) { 9285 APValue Val; 9286 // FIXME: Set WantObjectRepresentation to true if we're copying a 9287 // char-like type? 9288 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9289 !handleAssignment(Info, E, Dest, T, Val)) 9290 return false; 9291 // Do not iterate past the last element; if we're copying backwards, that 9292 // might take us off the start of the array. 9293 if (--NElems == 0) 9294 return true; 9295 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9296 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9297 return false; 9298 } 9299 } 9300 9301 default: 9302 break; 9303 } 9304 9305 return visitNonBuiltinCallExpr(E); 9306 } 9307 9308 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9309 APValue &Result, const InitListExpr *ILE, 9310 QualType AllocType); 9311 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9312 APValue &Result, 9313 const CXXConstructExpr *CCE, 9314 QualType AllocType); 9315 9316 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9317 if (!Info.getLangOpts().CPlusPlus20) 9318 Info.CCEDiag(E, diag::note_constexpr_new); 9319 9320 // We cannot speculatively evaluate a delete expression. 9321 if (Info.SpeculativeEvaluationDepth) 9322 return false; 9323 9324 FunctionDecl *OperatorNew = E->getOperatorNew(); 9325 9326 bool IsNothrow = false; 9327 bool IsPlacement = false; 9328 if (OperatorNew->isReservedGlobalPlacementOperator() && 9329 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9330 // FIXME Support array placement new. 9331 assert(E->getNumPlacementArgs() == 1); 9332 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9333 return false; 9334 if (Result.Designator.Invalid) 9335 return false; 9336 IsPlacement = true; 9337 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9338 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9339 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9340 return false; 9341 } else if (E->getNumPlacementArgs()) { 9342 // The only new-placement list we support is of the form (std::nothrow). 9343 // 9344 // FIXME: There is no restriction on this, but it's not clear that any 9345 // other form makes any sense. We get here for cases such as: 9346 // 9347 // new (std::align_val_t{N}) X(int) 9348 // 9349 // (which should presumably be valid only if N is a multiple of 9350 // alignof(int), and in any case can't be deallocated unless N is 9351 // alignof(X) and X has new-extended alignment). 9352 if (E->getNumPlacementArgs() != 1 || 9353 !E->getPlacementArg(0)->getType()->isNothrowT()) 9354 return Error(E, diag::note_constexpr_new_placement); 9355 9356 LValue Nothrow; 9357 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9358 return false; 9359 IsNothrow = true; 9360 } 9361 9362 const Expr *Init = E->getInitializer(); 9363 const InitListExpr *ResizedArrayILE = nullptr; 9364 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9365 bool ValueInit = false; 9366 9367 QualType AllocType = E->getAllocatedType(); 9368 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9369 const Expr *Stripped = *ArraySize; 9370 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9371 Stripped = ICE->getSubExpr()) 9372 if (ICE->getCastKind() != CK_NoOp && 9373 ICE->getCastKind() != CK_IntegralCast) 9374 break; 9375 9376 llvm::APSInt ArrayBound; 9377 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9378 return false; 9379 9380 // C++ [expr.new]p9: 9381 // The expression is erroneous if: 9382 // -- [...] its value before converting to size_t [or] applying the 9383 // second standard conversion sequence is less than zero 9384 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9385 if (IsNothrow) 9386 return ZeroInitialization(E); 9387 9388 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9389 << ArrayBound << (*ArraySize)->getSourceRange(); 9390 return false; 9391 } 9392 9393 // -- its value is such that the size of the allocated object would 9394 // exceed the implementation-defined limit 9395 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9396 ArrayBound) > 9397 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9398 if (IsNothrow) 9399 return ZeroInitialization(E); 9400 9401 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9402 << ArrayBound << (*ArraySize)->getSourceRange(); 9403 return false; 9404 } 9405 9406 // -- the new-initializer is a braced-init-list and the number of 9407 // array elements for which initializers are provided [...] 9408 // exceeds the number of elements to initialize 9409 if (!Init) { 9410 // No initialization is performed. 9411 } else if (isa<CXXScalarValueInitExpr>(Init) || 9412 isa<ImplicitValueInitExpr>(Init)) { 9413 ValueInit = true; 9414 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9415 ResizedArrayCCE = CCE; 9416 } else { 9417 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9418 assert(CAT && "unexpected type for array initializer"); 9419 9420 unsigned Bits = 9421 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9422 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9423 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9424 if (InitBound.ugt(AllocBound)) { 9425 if (IsNothrow) 9426 return ZeroInitialization(E); 9427 9428 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9429 << AllocBound.toString(10, /*Signed=*/false) 9430 << InitBound.toString(10, /*Signed=*/false) 9431 << (*ArraySize)->getSourceRange(); 9432 return false; 9433 } 9434 9435 // If the sizes differ, we must have an initializer list, and we need 9436 // special handling for this case when we initialize. 9437 if (InitBound != AllocBound) 9438 ResizedArrayILE = cast<InitListExpr>(Init); 9439 } 9440 9441 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9442 ArrayType::Normal, 0); 9443 } else { 9444 assert(!AllocType->isArrayType() && 9445 "array allocation with non-array new"); 9446 } 9447 9448 APValue *Val; 9449 if (IsPlacement) { 9450 AccessKinds AK = AK_Construct; 9451 struct FindObjectHandler { 9452 EvalInfo &Info; 9453 const Expr *E; 9454 QualType AllocType; 9455 const AccessKinds AccessKind; 9456 APValue *Value; 9457 9458 typedef bool result_type; 9459 bool failed() { return false; } 9460 bool found(APValue &Subobj, QualType SubobjType) { 9461 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9462 // old name of the object to be used to name the new object. 9463 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9464 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9465 SubobjType << AllocType; 9466 return false; 9467 } 9468 Value = &Subobj; 9469 return true; 9470 } 9471 bool found(APSInt &Value, QualType SubobjType) { 9472 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9473 return false; 9474 } 9475 bool found(APFloat &Value, QualType SubobjType) { 9476 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9477 return false; 9478 } 9479 } Handler = {Info, E, AllocType, AK, nullptr}; 9480 9481 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9482 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9483 return false; 9484 9485 Val = Handler.Value; 9486 9487 // [basic.life]p1: 9488 // The lifetime of an object o of type T ends when [...] the storage 9489 // which the object occupies is [...] reused by an object that is not 9490 // nested within o (6.6.2). 9491 *Val = APValue(); 9492 } else { 9493 // Perform the allocation and obtain a pointer to the resulting object. 9494 Val = Info.createHeapAlloc(E, AllocType, Result); 9495 if (!Val) 9496 return false; 9497 } 9498 9499 if (ValueInit) { 9500 ImplicitValueInitExpr VIE(AllocType); 9501 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9502 return false; 9503 } else if (ResizedArrayILE) { 9504 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9505 AllocType)) 9506 return false; 9507 } else if (ResizedArrayCCE) { 9508 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9509 AllocType)) 9510 return false; 9511 } else if (Init) { 9512 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9513 return false; 9514 } else if (!getDefaultInitValue(AllocType, *Val)) { 9515 return false; 9516 } 9517 9518 // Array new returns a pointer to the first element, not a pointer to the 9519 // array. 9520 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9521 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9522 9523 return true; 9524 } 9525 //===----------------------------------------------------------------------===// 9526 // Member Pointer Evaluation 9527 //===----------------------------------------------------------------------===// 9528 9529 namespace { 9530 class MemberPointerExprEvaluator 9531 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9532 MemberPtr &Result; 9533 9534 bool Success(const ValueDecl *D) { 9535 Result = MemberPtr(D); 9536 return true; 9537 } 9538 public: 9539 9540 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9541 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9542 9543 bool Success(const APValue &V, const Expr *E) { 9544 Result.setFrom(V); 9545 return true; 9546 } 9547 bool ZeroInitialization(const Expr *E) { 9548 return Success((const ValueDecl*)nullptr); 9549 } 9550 9551 bool VisitCastExpr(const CastExpr *E); 9552 bool VisitUnaryAddrOf(const UnaryOperator *E); 9553 }; 9554 } // end anonymous namespace 9555 9556 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9557 EvalInfo &Info) { 9558 assert(!E->isValueDependent()); 9559 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9560 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9561 } 9562 9563 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9564 switch (E->getCastKind()) { 9565 default: 9566 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9567 9568 case CK_NullToMemberPointer: 9569 VisitIgnoredValue(E->getSubExpr()); 9570 return ZeroInitialization(E); 9571 9572 case CK_BaseToDerivedMemberPointer: { 9573 if (!Visit(E->getSubExpr())) 9574 return false; 9575 if (E->path_empty()) 9576 return true; 9577 // Base-to-derived member pointer casts store the path in derived-to-base 9578 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9579 // the wrong end of the derived->base arc, so stagger the path by one class. 9580 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9581 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9582 PathI != PathE; ++PathI) { 9583 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9584 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9585 if (!Result.castToDerived(Derived)) 9586 return Error(E); 9587 } 9588 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9589 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9590 return Error(E); 9591 return true; 9592 } 9593 9594 case CK_DerivedToBaseMemberPointer: 9595 if (!Visit(E->getSubExpr())) 9596 return false; 9597 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9598 PathE = E->path_end(); PathI != PathE; ++PathI) { 9599 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9600 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9601 if (!Result.castToBase(Base)) 9602 return Error(E); 9603 } 9604 return true; 9605 } 9606 } 9607 9608 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9609 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9610 // member can be formed. 9611 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9612 } 9613 9614 //===----------------------------------------------------------------------===// 9615 // Record Evaluation 9616 //===----------------------------------------------------------------------===// 9617 9618 namespace { 9619 class RecordExprEvaluator 9620 : public ExprEvaluatorBase<RecordExprEvaluator> { 9621 const LValue &This; 9622 APValue &Result; 9623 public: 9624 9625 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9626 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9627 9628 bool Success(const APValue &V, const Expr *E) { 9629 Result = V; 9630 return true; 9631 } 9632 bool ZeroInitialization(const Expr *E) { 9633 return ZeroInitialization(E, E->getType()); 9634 } 9635 bool ZeroInitialization(const Expr *E, QualType T); 9636 9637 bool VisitCallExpr(const CallExpr *E) { 9638 return handleCallExpr(E, Result, &This); 9639 } 9640 bool VisitCastExpr(const CastExpr *E); 9641 bool VisitInitListExpr(const InitListExpr *E); 9642 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9643 return VisitCXXConstructExpr(E, E->getType()); 9644 } 9645 bool VisitLambdaExpr(const LambdaExpr *E); 9646 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9647 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9648 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9649 bool VisitBinCmp(const BinaryOperator *E); 9650 }; 9651 } 9652 9653 /// Perform zero-initialization on an object of non-union class type. 9654 /// C++11 [dcl.init]p5: 9655 /// To zero-initialize an object or reference of type T means: 9656 /// [...] 9657 /// -- if T is a (possibly cv-qualified) non-union class type, 9658 /// each non-static data member and each base-class subobject is 9659 /// zero-initialized 9660 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9661 const RecordDecl *RD, 9662 const LValue &This, APValue &Result) { 9663 assert(!RD->isUnion() && "Expected non-union class type"); 9664 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9665 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9666 std::distance(RD->field_begin(), RD->field_end())); 9667 9668 if (RD->isInvalidDecl()) return false; 9669 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9670 9671 if (CD) { 9672 unsigned Index = 0; 9673 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9674 End = CD->bases_end(); I != End; ++I, ++Index) { 9675 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9676 LValue Subobject = This; 9677 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9678 return false; 9679 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9680 Result.getStructBase(Index))) 9681 return false; 9682 } 9683 } 9684 9685 for (const auto *I : RD->fields()) { 9686 // -- if T is a reference type, no initialization is performed. 9687 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9688 continue; 9689 9690 LValue Subobject = This; 9691 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9692 return false; 9693 9694 ImplicitValueInitExpr VIE(I->getType()); 9695 if (!EvaluateInPlace( 9696 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9697 return false; 9698 } 9699 9700 return true; 9701 } 9702 9703 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9704 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9705 if (RD->isInvalidDecl()) return false; 9706 if (RD->isUnion()) { 9707 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9708 // object's first non-static named data member is zero-initialized 9709 RecordDecl::field_iterator I = RD->field_begin(); 9710 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9711 ++I; 9712 if (I == RD->field_end()) { 9713 Result = APValue((const FieldDecl*)nullptr); 9714 return true; 9715 } 9716 9717 LValue Subobject = This; 9718 if (!HandleLValueMember(Info, E, Subobject, *I)) 9719 return false; 9720 Result = APValue(*I); 9721 ImplicitValueInitExpr VIE(I->getType()); 9722 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9723 } 9724 9725 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9726 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9727 return false; 9728 } 9729 9730 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9731 } 9732 9733 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9734 switch (E->getCastKind()) { 9735 default: 9736 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9737 9738 case CK_ConstructorConversion: 9739 return Visit(E->getSubExpr()); 9740 9741 case CK_DerivedToBase: 9742 case CK_UncheckedDerivedToBase: { 9743 APValue DerivedObject; 9744 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9745 return false; 9746 if (!DerivedObject.isStruct()) 9747 return Error(E->getSubExpr()); 9748 9749 // Derived-to-base rvalue conversion: just slice off the derived part. 9750 APValue *Value = &DerivedObject; 9751 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9752 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9753 PathE = E->path_end(); PathI != PathE; ++PathI) { 9754 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9755 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9756 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9757 RD = Base; 9758 } 9759 Result = *Value; 9760 return true; 9761 } 9762 } 9763 } 9764 9765 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9766 if (E->isTransparent()) 9767 return Visit(E->getInit(0)); 9768 9769 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9770 if (RD->isInvalidDecl()) return false; 9771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9772 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9773 9774 EvalInfo::EvaluatingConstructorRAII EvalObj( 9775 Info, 9776 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9777 CXXRD && CXXRD->getNumBases()); 9778 9779 if (RD->isUnion()) { 9780 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9781 Result = APValue(Field); 9782 if (!Field) 9783 return true; 9784 9785 // If the initializer list for a union does not contain any elements, the 9786 // first element of the union is value-initialized. 9787 // FIXME: The element should be initialized from an initializer list. 9788 // Is this difference ever observable for initializer lists which 9789 // we don't build? 9790 ImplicitValueInitExpr VIE(Field->getType()); 9791 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9792 9793 LValue Subobject = This; 9794 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9795 return false; 9796 9797 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9798 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9799 isa<CXXDefaultInitExpr>(InitExpr)); 9800 9801 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9802 if (Field->isBitField()) 9803 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9804 Field); 9805 return true; 9806 } 9807 9808 return false; 9809 } 9810 9811 if (!Result.hasValue()) 9812 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9813 std::distance(RD->field_begin(), RD->field_end())); 9814 unsigned ElementNo = 0; 9815 bool Success = true; 9816 9817 // Initialize base classes. 9818 if (CXXRD && CXXRD->getNumBases()) { 9819 for (const auto &Base : CXXRD->bases()) { 9820 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9821 const Expr *Init = E->getInit(ElementNo); 9822 9823 LValue Subobject = This; 9824 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9825 return false; 9826 9827 APValue &FieldVal = Result.getStructBase(ElementNo); 9828 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9829 if (!Info.noteFailure()) 9830 return false; 9831 Success = false; 9832 } 9833 ++ElementNo; 9834 } 9835 9836 EvalObj.finishedConstructingBases(); 9837 } 9838 9839 // Initialize members. 9840 for (const auto *Field : RD->fields()) { 9841 // Anonymous bit-fields are not considered members of the class for 9842 // purposes of aggregate initialization. 9843 if (Field->isUnnamedBitfield()) 9844 continue; 9845 9846 LValue Subobject = This; 9847 9848 bool HaveInit = ElementNo < E->getNumInits(); 9849 9850 // FIXME: Diagnostics here should point to the end of the initializer 9851 // list, not the start. 9852 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9853 Subobject, Field, &Layout)) 9854 return false; 9855 9856 // Perform an implicit value-initialization for members beyond the end of 9857 // the initializer list. 9858 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9859 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9860 9861 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9862 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9863 isa<CXXDefaultInitExpr>(Init)); 9864 9865 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9866 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9867 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9868 FieldVal, Field))) { 9869 if (!Info.noteFailure()) 9870 return false; 9871 Success = false; 9872 } 9873 } 9874 9875 EvalObj.finishedConstructingFields(); 9876 9877 return Success; 9878 } 9879 9880 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9881 QualType T) { 9882 // Note that E's type is not necessarily the type of our class here; we might 9883 // be initializing an array element instead. 9884 const CXXConstructorDecl *FD = E->getConstructor(); 9885 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9886 9887 bool ZeroInit = E->requiresZeroInitialization(); 9888 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9889 // If we've already performed zero-initialization, we're already done. 9890 if (Result.hasValue()) 9891 return true; 9892 9893 if (ZeroInit) 9894 return ZeroInitialization(E, T); 9895 9896 return getDefaultInitValue(T, Result); 9897 } 9898 9899 const FunctionDecl *Definition = nullptr; 9900 auto Body = FD->getBody(Definition); 9901 9902 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9903 return false; 9904 9905 // Avoid materializing a temporary for an elidable copy/move constructor. 9906 if (E->isElidable() && !ZeroInit) 9907 if (const MaterializeTemporaryExpr *ME 9908 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9909 return Visit(ME->getSubExpr()); 9910 9911 if (ZeroInit && !ZeroInitialization(E, T)) 9912 return false; 9913 9914 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9915 return HandleConstructorCall(E, This, Args, 9916 cast<CXXConstructorDecl>(Definition), Info, 9917 Result); 9918 } 9919 9920 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9921 const CXXInheritedCtorInitExpr *E) { 9922 if (!Info.CurrentCall) { 9923 assert(Info.checkingPotentialConstantExpression()); 9924 return false; 9925 } 9926 9927 const CXXConstructorDecl *FD = E->getConstructor(); 9928 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9929 return false; 9930 9931 const FunctionDecl *Definition = nullptr; 9932 auto Body = FD->getBody(Definition); 9933 9934 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9935 return false; 9936 9937 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9938 cast<CXXConstructorDecl>(Definition), Info, 9939 Result); 9940 } 9941 9942 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9943 const CXXStdInitializerListExpr *E) { 9944 const ConstantArrayType *ArrayType = 9945 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9946 9947 LValue Array; 9948 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9949 return false; 9950 9951 // Get a pointer to the first element of the array. 9952 Array.addArray(Info, E, ArrayType); 9953 9954 auto InvalidType = [&] { 9955 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9956 << E->getType(); 9957 return false; 9958 }; 9959 9960 // FIXME: Perform the checks on the field types in SemaInit. 9961 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9962 RecordDecl::field_iterator Field = Record->field_begin(); 9963 if (Field == Record->field_end()) 9964 return InvalidType(); 9965 9966 // Start pointer. 9967 if (!Field->getType()->isPointerType() || 9968 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9969 ArrayType->getElementType())) 9970 return InvalidType(); 9971 9972 // FIXME: What if the initializer_list type has base classes, etc? 9973 Result = APValue(APValue::UninitStruct(), 0, 2); 9974 Array.moveInto(Result.getStructField(0)); 9975 9976 if (++Field == Record->field_end()) 9977 return InvalidType(); 9978 9979 if (Field->getType()->isPointerType() && 9980 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9981 ArrayType->getElementType())) { 9982 // End pointer. 9983 if (!HandleLValueArrayAdjustment(Info, E, Array, 9984 ArrayType->getElementType(), 9985 ArrayType->getSize().getZExtValue())) 9986 return false; 9987 Array.moveInto(Result.getStructField(1)); 9988 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9989 // Length. 9990 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9991 else 9992 return InvalidType(); 9993 9994 if (++Field != Record->field_end()) 9995 return InvalidType(); 9996 9997 return true; 9998 } 9999 10000 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10001 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10002 if (ClosureClass->isInvalidDecl()) 10003 return false; 10004 10005 const size_t NumFields = 10006 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10007 10008 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10009 E->capture_init_end()) && 10010 "The number of lambda capture initializers should equal the number of " 10011 "fields within the closure type"); 10012 10013 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10014 // Iterate through all the lambda's closure object's fields and initialize 10015 // them. 10016 auto *CaptureInitIt = E->capture_init_begin(); 10017 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10018 bool Success = true; 10019 for (const auto *Field : ClosureClass->fields()) { 10020 assert(CaptureInitIt != E->capture_init_end()); 10021 // Get the initializer for this field 10022 Expr *const CurFieldInit = *CaptureInitIt++; 10023 10024 // If there is no initializer, either this is a VLA or an error has 10025 // occurred. 10026 if (!CurFieldInit) 10027 return Error(E); 10028 10029 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10030 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 10031 if (!Info.keepEvaluatingAfterFailure()) 10032 return false; 10033 Success = false; 10034 } 10035 ++CaptureIt; 10036 } 10037 return Success; 10038 } 10039 10040 static bool EvaluateRecord(const Expr *E, const LValue &This, 10041 APValue &Result, EvalInfo &Info) { 10042 assert(!E->isValueDependent()); 10043 assert(E->isRValue() && E->getType()->isRecordType() && 10044 "can't evaluate expression as a record rvalue"); 10045 return RecordExprEvaluator(Info, This, Result).Visit(E); 10046 } 10047 10048 //===----------------------------------------------------------------------===// 10049 // Temporary Evaluation 10050 // 10051 // Temporaries are represented in the AST as rvalues, but generally behave like 10052 // lvalues. The full-object of which the temporary is a subobject is implicitly 10053 // materialized so that a reference can bind to it. 10054 //===----------------------------------------------------------------------===// 10055 namespace { 10056 class TemporaryExprEvaluator 10057 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10058 public: 10059 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10060 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10061 10062 /// Visit an expression which constructs the value of this temporary. 10063 bool VisitConstructExpr(const Expr *E) { 10064 APValue &Value = Info.CurrentCall->createTemporary( 10065 E, E->getType(), ScopeKind::FullExpression, Result); 10066 return EvaluateInPlace(Value, Info, Result, E); 10067 } 10068 10069 bool VisitCastExpr(const CastExpr *E) { 10070 switch (E->getCastKind()) { 10071 default: 10072 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10073 10074 case CK_ConstructorConversion: 10075 return VisitConstructExpr(E->getSubExpr()); 10076 } 10077 } 10078 bool VisitInitListExpr(const InitListExpr *E) { 10079 return VisitConstructExpr(E); 10080 } 10081 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10082 return VisitConstructExpr(E); 10083 } 10084 bool VisitCallExpr(const CallExpr *E) { 10085 return VisitConstructExpr(E); 10086 } 10087 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10088 return VisitConstructExpr(E); 10089 } 10090 bool VisitLambdaExpr(const LambdaExpr *E) { 10091 return VisitConstructExpr(E); 10092 } 10093 }; 10094 } // end anonymous namespace 10095 10096 /// Evaluate an expression of record type as a temporary. 10097 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10098 assert(!E->isValueDependent()); 10099 assert(E->isRValue() && E->getType()->isRecordType()); 10100 return TemporaryExprEvaluator(Info, Result).Visit(E); 10101 } 10102 10103 //===----------------------------------------------------------------------===// 10104 // Vector Evaluation 10105 //===----------------------------------------------------------------------===// 10106 10107 namespace { 10108 class VectorExprEvaluator 10109 : public ExprEvaluatorBase<VectorExprEvaluator> { 10110 APValue &Result; 10111 public: 10112 10113 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10114 : ExprEvaluatorBaseTy(info), Result(Result) {} 10115 10116 bool Success(ArrayRef<APValue> V, const Expr *E) { 10117 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10118 // FIXME: remove this APValue copy. 10119 Result = APValue(V.data(), V.size()); 10120 return true; 10121 } 10122 bool Success(const APValue &V, const Expr *E) { 10123 assert(V.isVector()); 10124 Result = V; 10125 return true; 10126 } 10127 bool ZeroInitialization(const Expr *E); 10128 10129 bool VisitUnaryReal(const UnaryOperator *E) 10130 { return Visit(E->getSubExpr()); } 10131 bool VisitCastExpr(const CastExpr* E); 10132 bool VisitInitListExpr(const InitListExpr *E); 10133 bool VisitUnaryImag(const UnaryOperator *E); 10134 bool VisitBinaryOperator(const BinaryOperator *E); 10135 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10136 // conditional select), shufflevector, ExtVectorElementExpr 10137 }; 10138 } // end anonymous namespace 10139 10140 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10141 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10142 return VectorExprEvaluator(Info, Result).Visit(E); 10143 } 10144 10145 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10146 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10147 unsigned NElts = VTy->getNumElements(); 10148 10149 const Expr *SE = E->getSubExpr(); 10150 QualType SETy = SE->getType(); 10151 10152 switch (E->getCastKind()) { 10153 case CK_VectorSplat: { 10154 APValue Val = APValue(); 10155 if (SETy->isIntegerType()) { 10156 APSInt IntResult; 10157 if (!EvaluateInteger(SE, IntResult, Info)) 10158 return false; 10159 Val = APValue(std::move(IntResult)); 10160 } else if (SETy->isRealFloatingType()) { 10161 APFloat FloatResult(0.0); 10162 if (!EvaluateFloat(SE, FloatResult, Info)) 10163 return false; 10164 Val = APValue(std::move(FloatResult)); 10165 } else { 10166 return Error(E); 10167 } 10168 10169 // Splat and create vector APValue. 10170 SmallVector<APValue, 4> Elts(NElts, Val); 10171 return Success(Elts, E); 10172 } 10173 case CK_BitCast: { 10174 // Evaluate the operand into an APInt we can extract from. 10175 llvm::APInt SValInt; 10176 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10177 return false; 10178 // Extract the elements 10179 QualType EltTy = VTy->getElementType(); 10180 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10181 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10182 SmallVector<APValue, 4> Elts; 10183 if (EltTy->isRealFloatingType()) { 10184 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10185 unsigned FloatEltSize = EltSize; 10186 if (&Sem == &APFloat::x87DoubleExtended()) 10187 FloatEltSize = 80; 10188 for (unsigned i = 0; i < NElts; i++) { 10189 llvm::APInt Elt; 10190 if (BigEndian) 10191 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10192 else 10193 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10194 Elts.push_back(APValue(APFloat(Sem, Elt))); 10195 } 10196 } else if (EltTy->isIntegerType()) { 10197 for (unsigned i = 0; i < NElts; i++) { 10198 llvm::APInt Elt; 10199 if (BigEndian) 10200 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10201 else 10202 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10203 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10204 } 10205 } else { 10206 return Error(E); 10207 } 10208 return Success(Elts, E); 10209 } 10210 default: 10211 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10212 } 10213 } 10214 10215 bool 10216 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10217 const VectorType *VT = E->getType()->castAs<VectorType>(); 10218 unsigned NumInits = E->getNumInits(); 10219 unsigned NumElements = VT->getNumElements(); 10220 10221 QualType EltTy = VT->getElementType(); 10222 SmallVector<APValue, 4> Elements; 10223 10224 // The number of initializers can be less than the number of 10225 // vector elements. For OpenCL, this can be due to nested vector 10226 // initialization. For GCC compatibility, missing trailing elements 10227 // should be initialized with zeroes. 10228 unsigned CountInits = 0, CountElts = 0; 10229 while (CountElts < NumElements) { 10230 // Handle nested vector initialization. 10231 if (CountInits < NumInits 10232 && E->getInit(CountInits)->getType()->isVectorType()) { 10233 APValue v; 10234 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10235 return Error(E); 10236 unsigned vlen = v.getVectorLength(); 10237 for (unsigned j = 0; j < vlen; j++) 10238 Elements.push_back(v.getVectorElt(j)); 10239 CountElts += vlen; 10240 } else if (EltTy->isIntegerType()) { 10241 llvm::APSInt sInt(32); 10242 if (CountInits < NumInits) { 10243 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10244 return false; 10245 } else // trailing integer zero. 10246 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10247 Elements.push_back(APValue(sInt)); 10248 CountElts++; 10249 } else { 10250 llvm::APFloat f(0.0); 10251 if (CountInits < NumInits) { 10252 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10253 return false; 10254 } else // trailing float zero. 10255 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10256 Elements.push_back(APValue(f)); 10257 CountElts++; 10258 } 10259 CountInits++; 10260 } 10261 return Success(Elements, E); 10262 } 10263 10264 bool 10265 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10266 const auto *VT = E->getType()->castAs<VectorType>(); 10267 QualType EltTy = VT->getElementType(); 10268 APValue ZeroElement; 10269 if (EltTy->isIntegerType()) 10270 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10271 else 10272 ZeroElement = 10273 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10274 10275 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10276 return Success(Elements, E); 10277 } 10278 10279 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10280 VisitIgnoredValue(E->getSubExpr()); 10281 return ZeroInitialization(E); 10282 } 10283 10284 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10285 BinaryOperatorKind Op = E->getOpcode(); 10286 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10287 "Operation not supported on vector types"); 10288 10289 if (Op == BO_Comma) 10290 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10291 10292 Expr *LHS = E->getLHS(); 10293 Expr *RHS = E->getRHS(); 10294 10295 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10296 "Must both be vector types"); 10297 // Checking JUST the types are the same would be fine, except shifts don't 10298 // need to have their types be the same (since you always shift by an int). 10299 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10300 E->getType()->getAs<VectorType>()->getNumElements() && 10301 RHS->getType()->getAs<VectorType>()->getNumElements() == 10302 E->getType()->getAs<VectorType>()->getNumElements() && 10303 "All operands must be the same size."); 10304 10305 APValue LHSValue; 10306 APValue RHSValue; 10307 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10308 if (!LHSOK && !Info.noteFailure()) 10309 return false; 10310 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10311 return false; 10312 10313 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10314 return false; 10315 10316 return Success(LHSValue, E); 10317 } 10318 10319 //===----------------------------------------------------------------------===// 10320 // Array Evaluation 10321 //===----------------------------------------------------------------------===// 10322 10323 namespace { 10324 class ArrayExprEvaluator 10325 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10326 const LValue &This; 10327 APValue &Result; 10328 public: 10329 10330 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10331 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10332 10333 bool Success(const APValue &V, const Expr *E) { 10334 assert(V.isArray() && "expected array"); 10335 Result = V; 10336 return true; 10337 } 10338 10339 bool ZeroInitialization(const Expr *E) { 10340 const ConstantArrayType *CAT = 10341 Info.Ctx.getAsConstantArrayType(E->getType()); 10342 if (!CAT) { 10343 if (E->getType()->isIncompleteArrayType()) { 10344 // We can be asked to zero-initialize a flexible array member; this 10345 // is represented as an ImplicitValueInitExpr of incomplete array 10346 // type. In this case, the array has zero elements. 10347 Result = APValue(APValue::UninitArray(), 0, 0); 10348 return true; 10349 } 10350 // FIXME: We could handle VLAs here. 10351 return Error(E); 10352 } 10353 10354 Result = APValue(APValue::UninitArray(), 0, 10355 CAT->getSize().getZExtValue()); 10356 if (!Result.hasArrayFiller()) return true; 10357 10358 // Zero-initialize all elements. 10359 LValue Subobject = This; 10360 Subobject.addArray(Info, E, CAT); 10361 ImplicitValueInitExpr VIE(CAT->getElementType()); 10362 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10363 } 10364 10365 bool VisitCallExpr(const CallExpr *E) { 10366 return handleCallExpr(E, Result, &This); 10367 } 10368 bool VisitInitListExpr(const InitListExpr *E, 10369 QualType AllocType = QualType()); 10370 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10371 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10372 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10373 const LValue &Subobject, 10374 APValue *Value, QualType Type); 10375 bool VisitStringLiteral(const StringLiteral *E, 10376 QualType AllocType = QualType()) { 10377 expandStringLiteral(Info, E, Result, AllocType); 10378 return true; 10379 } 10380 }; 10381 } // end anonymous namespace 10382 10383 static bool EvaluateArray(const Expr *E, const LValue &This, 10384 APValue &Result, EvalInfo &Info) { 10385 assert(!E->isValueDependent()); 10386 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10387 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10388 } 10389 10390 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10391 APValue &Result, const InitListExpr *ILE, 10392 QualType AllocType) { 10393 assert(!ILE->isValueDependent()); 10394 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10395 "not an array rvalue"); 10396 return ArrayExprEvaluator(Info, This, Result) 10397 .VisitInitListExpr(ILE, AllocType); 10398 } 10399 10400 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10401 APValue &Result, 10402 const CXXConstructExpr *CCE, 10403 QualType AllocType) { 10404 assert(!CCE->isValueDependent()); 10405 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10406 "not an array rvalue"); 10407 return ArrayExprEvaluator(Info, This, Result) 10408 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10409 } 10410 10411 // Return true iff the given array filler may depend on the element index. 10412 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10413 // For now, just allow non-class value-initialization and initialization 10414 // lists comprised of them. 10415 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10416 return false; 10417 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10418 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10419 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10420 return true; 10421 } 10422 return false; 10423 } 10424 return true; 10425 } 10426 10427 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10428 QualType AllocType) { 10429 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10430 AllocType.isNull() ? E->getType() : AllocType); 10431 if (!CAT) 10432 return Error(E); 10433 10434 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10435 // an appropriately-typed string literal enclosed in braces. 10436 if (E->isStringLiteralInit()) { 10437 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10438 // FIXME: Support ObjCEncodeExpr here once we support it in 10439 // ArrayExprEvaluator generally. 10440 if (!SL) 10441 return Error(E); 10442 return VisitStringLiteral(SL, AllocType); 10443 } 10444 10445 bool Success = true; 10446 10447 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10448 "zero-initialized array shouldn't have any initialized elts"); 10449 APValue Filler; 10450 if (Result.isArray() && Result.hasArrayFiller()) 10451 Filler = Result.getArrayFiller(); 10452 10453 unsigned NumEltsToInit = E->getNumInits(); 10454 unsigned NumElts = CAT->getSize().getZExtValue(); 10455 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10456 10457 // If the initializer might depend on the array index, run it for each 10458 // array element. 10459 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10460 NumEltsToInit = NumElts; 10461 10462 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10463 << NumEltsToInit << ".\n"); 10464 10465 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10466 10467 // If the array was previously zero-initialized, preserve the 10468 // zero-initialized values. 10469 if (Filler.hasValue()) { 10470 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10471 Result.getArrayInitializedElt(I) = Filler; 10472 if (Result.hasArrayFiller()) 10473 Result.getArrayFiller() = Filler; 10474 } 10475 10476 LValue Subobject = This; 10477 Subobject.addArray(Info, E, CAT); 10478 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10479 const Expr *Init = 10480 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10481 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10482 Info, Subobject, Init) || 10483 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10484 CAT->getElementType(), 1)) { 10485 if (!Info.noteFailure()) 10486 return false; 10487 Success = false; 10488 } 10489 } 10490 10491 if (!Result.hasArrayFiller()) 10492 return Success; 10493 10494 // If we get here, we have a trivial filler, which we can just evaluate 10495 // once and splat over the rest of the array elements. 10496 assert(FillerExpr && "no array filler for incomplete init list"); 10497 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10498 FillerExpr) && Success; 10499 } 10500 10501 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10502 LValue CommonLV; 10503 if (E->getCommonExpr() && 10504 !Evaluate(Info.CurrentCall->createTemporary( 10505 E->getCommonExpr(), 10506 getStorageType(Info.Ctx, E->getCommonExpr()), 10507 ScopeKind::FullExpression, CommonLV), 10508 Info, E->getCommonExpr()->getSourceExpr())) 10509 return false; 10510 10511 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10512 10513 uint64_t Elements = CAT->getSize().getZExtValue(); 10514 Result = APValue(APValue::UninitArray(), Elements, Elements); 10515 10516 LValue Subobject = This; 10517 Subobject.addArray(Info, E, CAT); 10518 10519 bool Success = true; 10520 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10521 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10522 Info, Subobject, E->getSubExpr()) || 10523 !HandleLValueArrayAdjustment(Info, E, Subobject, 10524 CAT->getElementType(), 1)) { 10525 if (!Info.noteFailure()) 10526 return false; 10527 Success = false; 10528 } 10529 } 10530 10531 return Success; 10532 } 10533 10534 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10535 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10536 } 10537 10538 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10539 const LValue &Subobject, 10540 APValue *Value, 10541 QualType Type) { 10542 bool HadZeroInit = Value->hasValue(); 10543 10544 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10545 unsigned N = CAT->getSize().getZExtValue(); 10546 10547 // Preserve the array filler if we had prior zero-initialization. 10548 APValue Filler = 10549 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10550 : APValue(); 10551 10552 *Value = APValue(APValue::UninitArray(), N, N); 10553 10554 if (HadZeroInit) 10555 for (unsigned I = 0; I != N; ++I) 10556 Value->getArrayInitializedElt(I) = Filler; 10557 10558 // Initialize the elements. 10559 LValue ArrayElt = Subobject; 10560 ArrayElt.addArray(Info, E, CAT); 10561 for (unsigned I = 0; I != N; ++I) 10562 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10563 CAT->getElementType()) || 10564 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10565 CAT->getElementType(), 1)) 10566 return false; 10567 10568 return true; 10569 } 10570 10571 if (!Type->isRecordType()) 10572 return Error(E); 10573 10574 return RecordExprEvaluator(Info, Subobject, *Value) 10575 .VisitCXXConstructExpr(E, Type); 10576 } 10577 10578 //===----------------------------------------------------------------------===// 10579 // Integer Evaluation 10580 // 10581 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10582 // types and back in constant folding. Integer values are thus represented 10583 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10584 //===----------------------------------------------------------------------===// 10585 10586 namespace { 10587 class IntExprEvaluator 10588 : public ExprEvaluatorBase<IntExprEvaluator> { 10589 APValue &Result; 10590 public: 10591 IntExprEvaluator(EvalInfo &info, APValue &result) 10592 : ExprEvaluatorBaseTy(info), Result(result) {} 10593 10594 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10595 assert(E->getType()->isIntegralOrEnumerationType() && 10596 "Invalid evaluation result."); 10597 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10598 "Invalid evaluation result."); 10599 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10600 "Invalid evaluation result."); 10601 Result = APValue(SI); 10602 return true; 10603 } 10604 bool Success(const llvm::APSInt &SI, const Expr *E) { 10605 return Success(SI, E, Result); 10606 } 10607 10608 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10609 assert(E->getType()->isIntegralOrEnumerationType() && 10610 "Invalid evaluation result."); 10611 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10612 "Invalid evaluation result."); 10613 Result = APValue(APSInt(I)); 10614 Result.getInt().setIsUnsigned( 10615 E->getType()->isUnsignedIntegerOrEnumerationType()); 10616 return true; 10617 } 10618 bool Success(const llvm::APInt &I, const Expr *E) { 10619 return Success(I, E, Result); 10620 } 10621 10622 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10623 assert(E->getType()->isIntegralOrEnumerationType() && 10624 "Invalid evaluation result."); 10625 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10626 return true; 10627 } 10628 bool Success(uint64_t Value, const Expr *E) { 10629 return Success(Value, E, Result); 10630 } 10631 10632 bool Success(CharUnits Size, const Expr *E) { 10633 return Success(Size.getQuantity(), E); 10634 } 10635 10636 bool Success(const APValue &V, const Expr *E) { 10637 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10638 Result = V; 10639 return true; 10640 } 10641 return Success(V.getInt(), E); 10642 } 10643 10644 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10645 10646 //===--------------------------------------------------------------------===// 10647 // Visitor Methods 10648 //===--------------------------------------------------------------------===// 10649 10650 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10651 return Success(E->getValue(), E); 10652 } 10653 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10654 return Success(E->getValue(), E); 10655 } 10656 10657 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10658 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10659 if (CheckReferencedDecl(E, E->getDecl())) 10660 return true; 10661 10662 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10663 } 10664 bool VisitMemberExpr(const MemberExpr *E) { 10665 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10666 VisitIgnoredBaseExpression(E->getBase()); 10667 return true; 10668 } 10669 10670 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10671 } 10672 10673 bool VisitCallExpr(const CallExpr *E); 10674 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10675 bool VisitBinaryOperator(const BinaryOperator *E); 10676 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10677 bool VisitUnaryOperator(const UnaryOperator *E); 10678 10679 bool VisitCastExpr(const CastExpr* E); 10680 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10681 10682 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10683 return Success(E->getValue(), E); 10684 } 10685 10686 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10687 return Success(E->getValue(), E); 10688 } 10689 10690 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10691 if (Info.ArrayInitIndex == uint64_t(-1)) { 10692 // We were asked to evaluate this subexpression independent of the 10693 // enclosing ArrayInitLoopExpr. We can't do that. 10694 Info.FFDiag(E); 10695 return false; 10696 } 10697 return Success(Info.ArrayInitIndex, E); 10698 } 10699 10700 // Note, GNU defines __null as an integer, not a pointer. 10701 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10702 return ZeroInitialization(E); 10703 } 10704 10705 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10706 return Success(E->getValue(), E); 10707 } 10708 10709 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10710 return Success(E->getValue(), E); 10711 } 10712 10713 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10714 return Success(E->getValue(), E); 10715 } 10716 10717 bool VisitUnaryReal(const UnaryOperator *E); 10718 bool VisitUnaryImag(const UnaryOperator *E); 10719 10720 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10721 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10722 bool VisitSourceLocExpr(const SourceLocExpr *E); 10723 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10724 bool VisitRequiresExpr(const RequiresExpr *E); 10725 // FIXME: Missing: array subscript of vector, member of vector 10726 }; 10727 10728 class FixedPointExprEvaluator 10729 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10730 APValue &Result; 10731 10732 public: 10733 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10734 : ExprEvaluatorBaseTy(info), Result(result) {} 10735 10736 bool Success(const llvm::APInt &I, const Expr *E) { 10737 return Success( 10738 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10739 } 10740 10741 bool Success(uint64_t Value, const Expr *E) { 10742 return Success( 10743 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10744 } 10745 10746 bool Success(const APValue &V, const Expr *E) { 10747 return Success(V.getFixedPoint(), E); 10748 } 10749 10750 bool Success(const APFixedPoint &V, const Expr *E) { 10751 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10752 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10753 "Invalid evaluation result."); 10754 Result = APValue(V); 10755 return true; 10756 } 10757 10758 //===--------------------------------------------------------------------===// 10759 // Visitor Methods 10760 //===--------------------------------------------------------------------===// 10761 10762 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10763 return Success(E->getValue(), E); 10764 } 10765 10766 bool VisitCastExpr(const CastExpr *E); 10767 bool VisitUnaryOperator(const UnaryOperator *E); 10768 bool VisitBinaryOperator(const BinaryOperator *E); 10769 }; 10770 } // end anonymous namespace 10771 10772 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10773 /// produce either the integer value or a pointer. 10774 /// 10775 /// GCC has a heinous extension which folds casts between pointer types and 10776 /// pointer-sized integral types. We support this by allowing the evaluation of 10777 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10778 /// Some simple arithmetic on such values is supported (they are treated much 10779 /// like char*). 10780 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10781 EvalInfo &Info) { 10782 assert(!E->isValueDependent()); 10783 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10784 return IntExprEvaluator(Info, Result).Visit(E); 10785 } 10786 10787 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10788 assert(!E->isValueDependent()); 10789 APValue Val; 10790 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10791 return false; 10792 if (!Val.isInt()) { 10793 // FIXME: It would be better to produce the diagnostic for casting 10794 // a pointer to an integer. 10795 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10796 return false; 10797 } 10798 Result = Val.getInt(); 10799 return true; 10800 } 10801 10802 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10803 APValue Evaluated = E->EvaluateInContext( 10804 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10805 return Success(Evaluated, E); 10806 } 10807 10808 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10809 EvalInfo &Info) { 10810 assert(!E->isValueDependent()); 10811 if (E->getType()->isFixedPointType()) { 10812 APValue Val; 10813 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10814 return false; 10815 if (!Val.isFixedPoint()) 10816 return false; 10817 10818 Result = Val.getFixedPoint(); 10819 return true; 10820 } 10821 return false; 10822 } 10823 10824 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10825 EvalInfo &Info) { 10826 assert(!E->isValueDependent()); 10827 if (E->getType()->isIntegerType()) { 10828 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10829 APSInt Val; 10830 if (!EvaluateInteger(E, Val, Info)) 10831 return false; 10832 Result = APFixedPoint(Val, FXSema); 10833 return true; 10834 } else if (E->getType()->isFixedPointType()) { 10835 return EvaluateFixedPoint(E, Result, Info); 10836 } 10837 return false; 10838 } 10839 10840 /// Check whether the given declaration can be directly converted to an integral 10841 /// rvalue. If not, no diagnostic is produced; there are other things we can 10842 /// try. 10843 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10844 // Enums are integer constant exprs. 10845 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10846 // Check for signedness/width mismatches between E type and ECD value. 10847 bool SameSign = (ECD->getInitVal().isSigned() 10848 == E->getType()->isSignedIntegerOrEnumerationType()); 10849 bool SameWidth = (ECD->getInitVal().getBitWidth() 10850 == Info.Ctx.getIntWidth(E->getType())); 10851 if (SameSign && SameWidth) 10852 return Success(ECD->getInitVal(), E); 10853 else { 10854 // Get rid of mismatch (otherwise Success assertions will fail) 10855 // by computing a new value matching the type of E. 10856 llvm::APSInt Val = ECD->getInitVal(); 10857 if (!SameSign) 10858 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10859 if (!SameWidth) 10860 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10861 return Success(Val, E); 10862 } 10863 } 10864 return false; 10865 } 10866 10867 /// Values returned by __builtin_classify_type, chosen to match the values 10868 /// produced by GCC's builtin. 10869 enum class GCCTypeClass { 10870 None = -1, 10871 Void = 0, 10872 Integer = 1, 10873 // GCC reserves 2 for character types, but instead classifies them as 10874 // integers. 10875 Enum = 3, 10876 Bool = 4, 10877 Pointer = 5, 10878 // GCC reserves 6 for references, but appears to never use it (because 10879 // expressions never have reference type, presumably). 10880 PointerToDataMember = 7, 10881 RealFloat = 8, 10882 Complex = 9, 10883 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10884 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10885 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10886 // uses 12 for that purpose, same as for a class or struct. Maybe it 10887 // internally implements a pointer to member as a struct? Who knows. 10888 PointerToMemberFunction = 12, // Not a bug, see above. 10889 ClassOrStruct = 12, 10890 Union = 13, 10891 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10892 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10893 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10894 // literals. 10895 }; 10896 10897 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10898 /// as GCC. 10899 static GCCTypeClass 10900 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10901 assert(!T->isDependentType() && "unexpected dependent type"); 10902 10903 QualType CanTy = T.getCanonicalType(); 10904 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10905 10906 switch (CanTy->getTypeClass()) { 10907 #define TYPE(ID, BASE) 10908 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10909 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10910 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10911 #include "clang/AST/TypeNodes.inc" 10912 case Type::Auto: 10913 case Type::DeducedTemplateSpecialization: 10914 llvm_unreachable("unexpected non-canonical or dependent type"); 10915 10916 case Type::Builtin: 10917 switch (BT->getKind()) { 10918 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10919 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10920 case BuiltinType::ID: return GCCTypeClass::Integer; 10921 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10922 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10923 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10924 case BuiltinType::ID: break; 10925 #include "clang/AST/BuiltinTypes.def" 10926 case BuiltinType::Void: 10927 return GCCTypeClass::Void; 10928 10929 case BuiltinType::Bool: 10930 return GCCTypeClass::Bool; 10931 10932 case BuiltinType::Char_U: 10933 case BuiltinType::UChar: 10934 case BuiltinType::WChar_U: 10935 case BuiltinType::Char8: 10936 case BuiltinType::Char16: 10937 case BuiltinType::Char32: 10938 case BuiltinType::UShort: 10939 case BuiltinType::UInt: 10940 case BuiltinType::ULong: 10941 case BuiltinType::ULongLong: 10942 case BuiltinType::UInt128: 10943 return GCCTypeClass::Integer; 10944 10945 case BuiltinType::UShortAccum: 10946 case BuiltinType::UAccum: 10947 case BuiltinType::ULongAccum: 10948 case BuiltinType::UShortFract: 10949 case BuiltinType::UFract: 10950 case BuiltinType::ULongFract: 10951 case BuiltinType::SatUShortAccum: 10952 case BuiltinType::SatUAccum: 10953 case BuiltinType::SatULongAccum: 10954 case BuiltinType::SatUShortFract: 10955 case BuiltinType::SatUFract: 10956 case BuiltinType::SatULongFract: 10957 return GCCTypeClass::None; 10958 10959 case BuiltinType::NullPtr: 10960 10961 case BuiltinType::ObjCId: 10962 case BuiltinType::ObjCClass: 10963 case BuiltinType::ObjCSel: 10964 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10965 case BuiltinType::Id: 10966 #include "clang/Basic/OpenCLImageTypes.def" 10967 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10968 case BuiltinType::Id: 10969 #include "clang/Basic/OpenCLExtensionTypes.def" 10970 case BuiltinType::OCLSampler: 10971 case BuiltinType::OCLEvent: 10972 case BuiltinType::OCLClkEvent: 10973 case BuiltinType::OCLQueue: 10974 case BuiltinType::OCLReserveID: 10975 #define SVE_TYPE(Name, Id, SingletonId) \ 10976 case BuiltinType::Id: 10977 #include "clang/Basic/AArch64SVEACLETypes.def" 10978 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 10979 case BuiltinType::Id: 10980 #include "clang/Basic/PPCTypes.def" 10981 return GCCTypeClass::None; 10982 10983 case BuiltinType::Dependent: 10984 llvm_unreachable("unexpected dependent type"); 10985 }; 10986 llvm_unreachable("unexpected placeholder type"); 10987 10988 case Type::Enum: 10989 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10990 10991 case Type::Pointer: 10992 case Type::ConstantArray: 10993 case Type::VariableArray: 10994 case Type::IncompleteArray: 10995 case Type::FunctionNoProto: 10996 case Type::FunctionProto: 10997 return GCCTypeClass::Pointer; 10998 10999 case Type::MemberPointer: 11000 return CanTy->isMemberDataPointerType() 11001 ? GCCTypeClass::PointerToDataMember 11002 : GCCTypeClass::PointerToMemberFunction; 11003 11004 case Type::Complex: 11005 return GCCTypeClass::Complex; 11006 11007 case Type::Record: 11008 return CanTy->isUnionType() ? GCCTypeClass::Union 11009 : GCCTypeClass::ClassOrStruct; 11010 11011 case Type::Atomic: 11012 // GCC classifies _Atomic T the same as T. 11013 return EvaluateBuiltinClassifyType( 11014 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11015 11016 case Type::BlockPointer: 11017 case Type::Vector: 11018 case Type::ExtVector: 11019 case Type::ConstantMatrix: 11020 case Type::ObjCObject: 11021 case Type::ObjCInterface: 11022 case Type::ObjCObjectPointer: 11023 case Type::Pipe: 11024 case Type::ExtInt: 11025 // GCC classifies vectors as None. We follow its lead and classify all 11026 // other types that don't fit into the regular classification the same way. 11027 return GCCTypeClass::None; 11028 11029 case Type::LValueReference: 11030 case Type::RValueReference: 11031 llvm_unreachable("invalid type for expression"); 11032 } 11033 11034 llvm_unreachable("unexpected type class"); 11035 } 11036 11037 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11038 /// as GCC. 11039 static GCCTypeClass 11040 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11041 // If no argument was supplied, default to None. This isn't 11042 // ideal, however it is what gcc does. 11043 if (E->getNumArgs() == 0) 11044 return GCCTypeClass::None; 11045 11046 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11047 // being an ICE, but still folds it to a constant using the type of the first 11048 // argument. 11049 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11050 } 11051 11052 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11053 /// __builtin_constant_p when applied to the given pointer. 11054 /// 11055 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11056 /// or it points to the first character of a string literal. 11057 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11058 APValue::LValueBase Base = LV.getLValueBase(); 11059 if (Base.isNull()) { 11060 // A null base is acceptable. 11061 return true; 11062 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11063 if (!isa<StringLiteral>(E)) 11064 return false; 11065 return LV.getLValueOffset().isZero(); 11066 } else if (Base.is<TypeInfoLValue>()) { 11067 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11068 // evaluate to true. 11069 return true; 11070 } else { 11071 // Any other base is not constant enough for GCC. 11072 return false; 11073 } 11074 } 11075 11076 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11077 /// GCC as we can manage. 11078 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11079 // This evaluation is not permitted to have side-effects, so evaluate it in 11080 // a speculative evaluation context. 11081 SpeculativeEvaluationRAII SpeculativeEval(Info); 11082 11083 // Constant-folding is always enabled for the operand of __builtin_constant_p 11084 // (even when the enclosing evaluation context otherwise requires a strict 11085 // language-specific constant expression). 11086 FoldConstant Fold(Info, true); 11087 11088 QualType ArgType = Arg->getType(); 11089 11090 // __builtin_constant_p always has one operand. The rules which gcc follows 11091 // are not precisely documented, but are as follows: 11092 // 11093 // - If the operand is of integral, floating, complex or enumeration type, 11094 // and can be folded to a known value of that type, it returns 1. 11095 // - If the operand can be folded to a pointer to the first character 11096 // of a string literal (or such a pointer cast to an integral type) 11097 // or to a null pointer or an integer cast to a pointer, it returns 1. 11098 // 11099 // Otherwise, it returns 0. 11100 // 11101 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11102 // its support for this did not work prior to GCC 9 and is not yet well 11103 // understood. 11104 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11105 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11106 ArgType->isNullPtrType()) { 11107 APValue V; 11108 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11109 Fold.keepDiagnostics(); 11110 return false; 11111 } 11112 11113 // For a pointer (possibly cast to integer), there are special rules. 11114 if (V.getKind() == APValue::LValue) 11115 return EvaluateBuiltinConstantPForLValue(V); 11116 11117 // Otherwise, any constant value is good enough. 11118 return V.hasValue(); 11119 } 11120 11121 // Anything else isn't considered to be sufficiently constant. 11122 return false; 11123 } 11124 11125 /// Retrieves the "underlying object type" of the given expression, 11126 /// as used by __builtin_object_size. 11127 static QualType getObjectType(APValue::LValueBase B) { 11128 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11129 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11130 return VD->getType(); 11131 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11132 if (isa<CompoundLiteralExpr>(E)) 11133 return E->getType(); 11134 } else if (B.is<TypeInfoLValue>()) { 11135 return B.getTypeInfoType(); 11136 } else if (B.is<DynamicAllocLValue>()) { 11137 return B.getDynamicAllocType(); 11138 } 11139 11140 return QualType(); 11141 } 11142 11143 /// A more selective version of E->IgnoreParenCasts for 11144 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11145 /// to change the type of E. 11146 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11147 /// 11148 /// Always returns an RValue with a pointer representation. 11149 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11150 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11151 11152 auto *NoParens = E->IgnoreParens(); 11153 auto *Cast = dyn_cast<CastExpr>(NoParens); 11154 if (Cast == nullptr) 11155 return NoParens; 11156 11157 // We only conservatively allow a few kinds of casts, because this code is 11158 // inherently a simple solution that seeks to support the common case. 11159 auto CastKind = Cast->getCastKind(); 11160 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11161 CastKind != CK_AddressSpaceConversion) 11162 return NoParens; 11163 11164 auto *SubExpr = Cast->getSubExpr(); 11165 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11166 return NoParens; 11167 return ignorePointerCastsAndParens(SubExpr); 11168 } 11169 11170 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11171 /// record layout. e.g. 11172 /// struct { struct { int a, b; } fst, snd; } obj; 11173 /// obj.fst // no 11174 /// obj.snd // yes 11175 /// obj.fst.a // no 11176 /// obj.fst.b // no 11177 /// obj.snd.a // no 11178 /// obj.snd.b // yes 11179 /// 11180 /// Please note: this function is specialized for how __builtin_object_size 11181 /// views "objects". 11182 /// 11183 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11184 /// correct result, it will always return true. 11185 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11186 assert(!LVal.Designator.Invalid); 11187 11188 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11189 const RecordDecl *Parent = FD->getParent(); 11190 Invalid = Parent->isInvalidDecl(); 11191 if (Invalid || Parent->isUnion()) 11192 return true; 11193 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11194 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11195 }; 11196 11197 auto &Base = LVal.getLValueBase(); 11198 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11199 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11200 bool Invalid; 11201 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11202 return Invalid; 11203 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11204 for (auto *FD : IFD->chain()) { 11205 bool Invalid; 11206 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11207 return Invalid; 11208 } 11209 } 11210 } 11211 11212 unsigned I = 0; 11213 QualType BaseType = getType(Base); 11214 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11215 // If we don't know the array bound, conservatively assume we're looking at 11216 // the final array element. 11217 ++I; 11218 if (BaseType->isIncompleteArrayType()) 11219 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11220 else 11221 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11222 } 11223 11224 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11225 const auto &Entry = LVal.Designator.Entries[I]; 11226 if (BaseType->isArrayType()) { 11227 // Because __builtin_object_size treats arrays as objects, we can ignore 11228 // the index iff this is the last array in the Designator. 11229 if (I + 1 == E) 11230 return true; 11231 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11232 uint64_t Index = Entry.getAsArrayIndex(); 11233 if (Index + 1 != CAT->getSize()) 11234 return false; 11235 BaseType = CAT->getElementType(); 11236 } else if (BaseType->isAnyComplexType()) { 11237 const auto *CT = BaseType->castAs<ComplexType>(); 11238 uint64_t Index = Entry.getAsArrayIndex(); 11239 if (Index != 1) 11240 return false; 11241 BaseType = CT->getElementType(); 11242 } else if (auto *FD = getAsField(Entry)) { 11243 bool Invalid; 11244 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11245 return Invalid; 11246 BaseType = FD->getType(); 11247 } else { 11248 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11249 return false; 11250 } 11251 } 11252 return true; 11253 } 11254 11255 /// Tests to see if the LValue has a user-specified designator (that isn't 11256 /// necessarily valid). Note that this always returns 'true' if the LValue has 11257 /// an unsized array as its first designator entry, because there's currently no 11258 /// way to tell if the user typed *foo or foo[0]. 11259 static bool refersToCompleteObject(const LValue &LVal) { 11260 if (LVal.Designator.Invalid) 11261 return false; 11262 11263 if (!LVal.Designator.Entries.empty()) 11264 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11265 11266 if (!LVal.InvalidBase) 11267 return true; 11268 11269 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11270 // the LValueBase. 11271 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11272 return !E || !isa<MemberExpr>(E); 11273 } 11274 11275 /// Attempts to detect a user writing into a piece of memory that's impossible 11276 /// to figure out the size of by just using types. 11277 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11278 const SubobjectDesignator &Designator = LVal.Designator; 11279 // Notes: 11280 // - Users can only write off of the end when we have an invalid base. Invalid 11281 // bases imply we don't know where the memory came from. 11282 // - We used to be a bit more aggressive here; we'd only be conservative if 11283 // the array at the end was flexible, or if it had 0 or 1 elements. This 11284 // broke some common standard library extensions (PR30346), but was 11285 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11286 // with some sort of list. OTOH, it seems that GCC is always 11287 // conservative with the last element in structs (if it's an array), so our 11288 // current behavior is more compatible than an explicit list approach would 11289 // be. 11290 return LVal.InvalidBase && 11291 Designator.Entries.size() == Designator.MostDerivedPathLength && 11292 Designator.MostDerivedIsArrayElement && 11293 isDesignatorAtObjectEnd(Ctx, LVal); 11294 } 11295 11296 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11297 /// Fails if the conversion would cause loss of precision. 11298 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11299 CharUnits &Result) { 11300 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11301 if (Int.ugt(CharUnitsMax)) 11302 return false; 11303 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11304 return true; 11305 } 11306 11307 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11308 /// determine how many bytes exist from the beginning of the object to either 11309 /// the end of the current subobject, or the end of the object itself, depending 11310 /// on what the LValue looks like + the value of Type. 11311 /// 11312 /// If this returns false, the value of Result is undefined. 11313 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11314 unsigned Type, const LValue &LVal, 11315 CharUnits &EndOffset) { 11316 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11317 11318 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11319 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11320 return false; 11321 return HandleSizeof(Info, ExprLoc, Ty, Result); 11322 }; 11323 11324 // We want to evaluate the size of the entire object. This is a valid fallback 11325 // for when Type=1 and the designator is invalid, because we're asked for an 11326 // upper-bound. 11327 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11328 // Type=3 wants a lower bound, so we can't fall back to this. 11329 if (Type == 3 && !DetermineForCompleteObject) 11330 return false; 11331 11332 llvm::APInt APEndOffset; 11333 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11334 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11335 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11336 11337 if (LVal.InvalidBase) 11338 return false; 11339 11340 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11341 return CheckedHandleSizeof(BaseTy, EndOffset); 11342 } 11343 11344 // We want to evaluate the size of a subobject. 11345 const SubobjectDesignator &Designator = LVal.Designator; 11346 11347 // The following is a moderately common idiom in C: 11348 // 11349 // struct Foo { int a; char c[1]; }; 11350 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11351 // strcpy(&F->c[0], Bar); 11352 // 11353 // In order to not break too much legacy code, we need to support it. 11354 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11355 // If we can resolve this to an alloc_size call, we can hand that back, 11356 // because we know for certain how many bytes there are to write to. 11357 llvm::APInt APEndOffset; 11358 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11359 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11360 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11361 11362 // If we cannot determine the size of the initial allocation, then we can't 11363 // given an accurate upper-bound. However, we are still able to give 11364 // conservative lower-bounds for Type=3. 11365 if (Type == 1) 11366 return false; 11367 } 11368 11369 CharUnits BytesPerElem; 11370 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11371 return false; 11372 11373 // According to the GCC documentation, we want the size of the subobject 11374 // denoted by the pointer. But that's not quite right -- what we actually 11375 // want is the size of the immediately-enclosing array, if there is one. 11376 int64_t ElemsRemaining; 11377 if (Designator.MostDerivedIsArrayElement && 11378 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11379 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11380 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11381 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11382 } else { 11383 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11384 } 11385 11386 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11387 return true; 11388 } 11389 11390 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11391 /// returns true and stores the result in @p Size. 11392 /// 11393 /// If @p WasError is non-null, this will report whether the failure to evaluate 11394 /// is to be treated as an Error in IntExprEvaluator. 11395 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11396 EvalInfo &Info, uint64_t &Size) { 11397 // Determine the denoted object. 11398 LValue LVal; 11399 { 11400 // The operand of __builtin_object_size is never evaluated for side-effects. 11401 // If there are any, but we can determine the pointed-to object anyway, then 11402 // ignore the side-effects. 11403 SpeculativeEvaluationRAII SpeculativeEval(Info); 11404 IgnoreSideEffectsRAII Fold(Info); 11405 11406 if (E->isGLValue()) { 11407 // It's possible for us to be given GLValues if we're called via 11408 // Expr::tryEvaluateObjectSize. 11409 APValue RVal; 11410 if (!EvaluateAsRValue(Info, E, RVal)) 11411 return false; 11412 LVal.setFrom(Info.Ctx, RVal); 11413 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11414 /*InvalidBaseOK=*/true)) 11415 return false; 11416 } 11417 11418 // If we point to before the start of the object, there are no accessible 11419 // bytes. 11420 if (LVal.getLValueOffset().isNegative()) { 11421 Size = 0; 11422 return true; 11423 } 11424 11425 CharUnits EndOffset; 11426 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11427 return false; 11428 11429 // If we've fallen outside of the end offset, just pretend there's nothing to 11430 // write to/read from. 11431 if (EndOffset <= LVal.getLValueOffset()) 11432 Size = 0; 11433 else 11434 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11435 return true; 11436 } 11437 11438 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11439 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11440 return VisitBuiltinCallExpr(E, BuiltinOp); 11441 11442 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11443 } 11444 11445 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11446 APValue &Val, APSInt &Alignment) { 11447 QualType SrcTy = E->getArg(0)->getType(); 11448 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11449 return false; 11450 // Even though we are evaluating integer expressions we could get a pointer 11451 // argument for the __builtin_is_aligned() case. 11452 if (SrcTy->isPointerType()) { 11453 LValue Ptr; 11454 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11455 return false; 11456 Ptr.moveInto(Val); 11457 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11458 Info.FFDiag(E->getArg(0)); 11459 return false; 11460 } else { 11461 APSInt SrcInt; 11462 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11463 return false; 11464 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11465 "Bit widths must be the same"); 11466 Val = APValue(SrcInt); 11467 } 11468 assert(Val.hasValue()); 11469 return true; 11470 } 11471 11472 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11473 unsigned BuiltinOp) { 11474 switch (BuiltinOp) { 11475 default: 11476 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11477 11478 case Builtin::BI__builtin_dynamic_object_size: 11479 case Builtin::BI__builtin_object_size: { 11480 // The type was checked when we built the expression. 11481 unsigned Type = 11482 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11483 assert(Type <= 3 && "unexpected type"); 11484 11485 uint64_t Size; 11486 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11487 return Success(Size, E); 11488 11489 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11490 return Success((Type & 2) ? 0 : -1, E); 11491 11492 // Expression had no side effects, but we couldn't statically determine the 11493 // size of the referenced object. 11494 switch (Info.EvalMode) { 11495 case EvalInfo::EM_ConstantExpression: 11496 case EvalInfo::EM_ConstantFold: 11497 case EvalInfo::EM_IgnoreSideEffects: 11498 // Leave it to IR generation. 11499 return Error(E); 11500 case EvalInfo::EM_ConstantExpressionUnevaluated: 11501 // Reduce it to a constant now. 11502 return Success((Type & 2) ? 0 : -1, E); 11503 } 11504 11505 llvm_unreachable("unexpected EvalMode"); 11506 } 11507 11508 case Builtin::BI__builtin_os_log_format_buffer_size: { 11509 analyze_os_log::OSLogBufferLayout Layout; 11510 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11511 return Success(Layout.size().getQuantity(), E); 11512 } 11513 11514 case Builtin::BI__builtin_is_aligned: { 11515 APValue Src; 11516 APSInt Alignment; 11517 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11518 return false; 11519 if (Src.isLValue()) { 11520 // If we evaluated a pointer, check the minimum known alignment. 11521 LValue Ptr; 11522 Ptr.setFrom(Info.Ctx, Src); 11523 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11524 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11525 // We can return true if the known alignment at the computed offset is 11526 // greater than the requested alignment. 11527 assert(PtrAlign.isPowerOfTwo()); 11528 assert(Alignment.isPowerOf2()); 11529 if (PtrAlign.getQuantity() >= Alignment) 11530 return Success(1, E); 11531 // If the alignment is not known to be sufficient, some cases could still 11532 // be aligned at run time. However, if the requested alignment is less or 11533 // equal to the base alignment and the offset is not aligned, we know that 11534 // the run-time value can never be aligned. 11535 if (BaseAlignment.getQuantity() >= Alignment && 11536 PtrAlign.getQuantity() < Alignment) 11537 return Success(0, E); 11538 // Otherwise we can't infer whether the value is sufficiently aligned. 11539 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11540 // in cases where we can't fully evaluate the pointer. 11541 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11542 << Alignment; 11543 return false; 11544 } 11545 assert(Src.isInt()); 11546 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11547 } 11548 case Builtin::BI__builtin_align_up: { 11549 APValue Src; 11550 APSInt Alignment; 11551 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11552 return false; 11553 if (!Src.isInt()) 11554 return Error(E); 11555 APSInt AlignedVal = 11556 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11557 Src.getInt().isUnsigned()); 11558 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11559 return Success(AlignedVal, E); 11560 } 11561 case Builtin::BI__builtin_align_down: { 11562 APValue Src; 11563 APSInt Alignment; 11564 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11565 return false; 11566 if (!Src.isInt()) 11567 return Error(E); 11568 APSInt AlignedVal = 11569 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11570 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11571 return Success(AlignedVal, E); 11572 } 11573 11574 case Builtin::BI__builtin_bitreverse8: 11575 case Builtin::BI__builtin_bitreverse16: 11576 case Builtin::BI__builtin_bitreverse32: 11577 case Builtin::BI__builtin_bitreverse64: { 11578 APSInt Val; 11579 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11580 return false; 11581 11582 return Success(Val.reverseBits(), E); 11583 } 11584 11585 case Builtin::BI__builtin_bswap16: 11586 case Builtin::BI__builtin_bswap32: 11587 case Builtin::BI__builtin_bswap64: { 11588 APSInt Val; 11589 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11590 return false; 11591 11592 return Success(Val.byteSwap(), E); 11593 } 11594 11595 case Builtin::BI__builtin_classify_type: 11596 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11597 11598 case Builtin::BI__builtin_clrsb: 11599 case Builtin::BI__builtin_clrsbl: 11600 case Builtin::BI__builtin_clrsbll: { 11601 APSInt Val; 11602 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11603 return false; 11604 11605 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11606 } 11607 11608 case Builtin::BI__builtin_clz: 11609 case Builtin::BI__builtin_clzl: 11610 case Builtin::BI__builtin_clzll: 11611 case Builtin::BI__builtin_clzs: { 11612 APSInt Val; 11613 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11614 return false; 11615 if (!Val) 11616 return Error(E); 11617 11618 return Success(Val.countLeadingZeros(), E); 11619 } 11620 11621 case Builtin::BI__builtin_constant_p: { 11622 const Expr *Arg = E->getArg(0); 11623 if (EvaluateBuiltinConstantP(Info, Arg)) 11624 return Success(true, E); 11625 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11626 // Outside a constant context, eagerly evaluate to false in the presence 11627 // of side-effects in order to avoid -Wunsequenced false-positives in 11628 // a branch on __builtin_constant_p(expr). 11629 return Success(false, E); 11630 } 11631 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11632 return false; 11633 } 11634 11635 case Builtin::BI__builtin_is_constant_evaluated: { 11636 const auto *Callee = Info.CurrentCall->getCallee(); 11637 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11638 (Info.CallStackDepth == 1 || 11639 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11640 Callee->getIdentifier() && 11641 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11642 // FIXME: Find a better way to avoid duplicated diagnostics. 11643 if (Info.EvalStatus.Diag) 11644 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11645 : Info.CurrentCall->CallLoc, 11646 diag::warn_is_constant_evaluated_always_true_constexpr) 11647 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11648 : "std::is_constant_evaluated"); 11649 } 11650 11651 return Success(Info.InConstantContext, E); 11652 } 11653 11654 case Builtin::BI__builtin_ctz: 11655 case Builtin::BI__builtin_ctzl: 11656 case Builtin::BI__builtin_ctzll: 11657 case Builtin::BI__builtin_ctzs: { 11658 APSInt Val; 11659 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11660 return false; 11661 if (!Val) 11662 return Error(E); 11663 11664 return Success(Val.countTrailingZeros(), E); 11665 } 11666 11667 case Builtin::BI__builtin_eh_return_data_regno: { 11668 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11669 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11670 return Success(Operand, E); 11671 } 11672 11673 case Builtin::BI__builtin_expect: 11674 case Builtin::BI__builtin_expect_with_probability: 11675 return Visit(E->getArg(0)); 11676 11677 case Builtin::BI__builtin_ffs: 11678 case Builtin::BI__builtin_ffsl: 11679 case Builtin::BI__builtin_ffsll: { 11680 APSInt Val; 11681 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11682 return false; 11683 11684 unsigned N = Val.countTrailingZeros(); 11685 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11686 } 11687 11688 case Builtin::BI__builtin_fpclassify: { 11689 APFloat Val(0.0); 11690 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11691 return false; 11692 unsigned Arg; 11693 switch (Val.getCategory()) { 11694 case APFloat::fcNaN: Arg = 0; break; 11695 case APFloat::fcInfinity: Arg = 1; break; 11696 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11697 case APFloat::fcZero: Arg = 4; break; 11698 } 11699 return Visit(E->getArg(Arg)); 11700 } 11701 11702 case Builtin::BI__builtin_isinf_sign: { 11703 APFloat Val(0.0); 11704 return EvaluateFloat(E->getArg(0), Val, Info) && 11705 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11706 } 11707 11708 case Builtin::BI__builtin_isinf: { 11709 APFloat Val(0.0); 11710 return EvaluateFloat(E->getArg(0), Val, Info) && 11711 Success(Val.isInfinity() ? 1 : 0, E); 11712 } 11713 11714 case Builtin::BI__builtin_isfinite: { 11715 APFloat Val(0.0); 11716 return EvaluateFloat(E->getArg(0), Val, Info) && 11717 Success(Val.isFinite() ? 1 : 0, E); 11718 } 11719 11720 case Builtin::BI__builtin_isnan: { 11721 APFloat Val(0.0); 11722 return EvaluateFloat(E->getArg(0), Val, Info) && 11723 Success(Val.isNaN() ? 1 : 0, E); 11724 } 11725 11726 case Builtin::BI__builtin_isnormal: { 11727 APFloat Val(0.0); 11728 return EvaluateFloat(E->getArg(0), Val, Info) && 11729 Success(Val.isNormal() ? 1 : 0, E); 11730 } 11731 11732 case Builtin::BI__builtin_parity: 11733 case Builtin::BI__builtin_parityl: 11734 case Builtin::BI__builtin_parityll: { 11735 APSInt Val; 11736 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11737 return false; 11738 11739 return Success(Val.countPopulation() % 2, E); 11740 } 11741 11742 case Builtin::BI__builtin_popcount: 11743 case Builtin::BI__builtin_popcountl: 11744 case Builtin::BI__builtin_popcountll: { 11745 APSInt Val; 11746 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11747 return false; 11748 11749 return Success(Val.countPopulation(), E); 11750 } 11751 11752 case Builtin::BI__builtin_rotateleft8: 11753 case Builtin::BI__builtin_rotateleft16: 11754 case Builtin::BI__builtin_rotateleft32: 11755 case Builtin::BI__builtin_rotateleft64: 11756 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11757 case Builtin::BI_rotl16: 11758 case Builtin::BI_rotl: 11759 case Builtin::BI_lrotl: 11760 case Builtin::BI_rotl64: { 11761 APSInt Val, Amt; 11762 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11763 !EvaluateInteger(E->getArg(1), Amt, Info)) 11764 return false; 11765 11766 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11767 } 11768 11769 case Builtin::BI__builtin_rotateright8: 11770 case Builtin::BI__builtin_rotateright16: 11771 case Builtin::BI__builtin_rotateright32: 11772 case Builtin::BI__builtin_rotateright64: 11773 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11774 case Builtin::BI_rotr16: 11775 case Builtin::BI_rotr: 11776 case Builtin::BI_lrotr: 11777 case Builtin::BI_rotr64: { 11778 APSInt Val, Amt; 11779 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11780 !EvaluateInteger(E->getArg(1), Amt, Info)) 11781 return false; 11782 11783 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11784 } 11785 11786 case Builtin::BIstrlen: 11787 case Builtin::BIwcslen: 11788 // A call to strlen is not a constant expression. 11789 if (Info.getLangOpts().CPlusPlus11) 11790 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11791 << /*isConstexpr*/0 << /*isConstructor*/0 11792 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11793 else 11794 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11795 LLVM_FALLTHROUGH; 11796 case Builtin::BI__builtin_strlen: 11797 case Builtin::BI__builtin_wcslen: { 11798 // As an extension, we support __builtin_strlen() as a constant expression, 11799 // and support folding strlen() to a constant. 11800 LValue String; 11801 if (!EvaluatePointer(E->getArg(0), String, Info)) 11802 return false; 11803 11804 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11805 11806 // Fast path: if it's a string literal, search the string value. 11807 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11808 String.getLValueBase().dyn_cast<const Expr *>())) { 11809 // The string literal may have embedded null characters. Find the first 11810 // one and truncate there. 11811 StringRef Str = S->getBytes(); 11812 int64_t Off = String.Offset.getQuantity(); 11813 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11814 S->getCharByteWidth() == 1 && 11815 // FIXME: Add fast-path for wchar_t too. 11816 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11817 Str = Str.substr(Off); 11818 11819 StringRef::size_type Pos = Str.find(0); 11820 if (Pos != StringRef::npos) 11821 Str = Str.substr(0, Pos); 11822 11823 return Success(Str.size(), E); 11824 } 11825 11826 // Fall through to slow path to issue appropriate diagnostic. 11827 } 11828 11829 // Slow path: scan the bytes of the string looking for the terminating 0. 11830 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11831 APValue Char; 11832 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11833 !Char.isInt()) 11834 return false; 11835 if (!Char.getInt()) 11836 return Success(Strlen, E); 11837 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11838 return false; 11839 } 11840 } 11841 11842 case Builtin::BIstrcmp: 11843 case Builtin::BIwcscmp: 11844 case Builtin::BIstrncmp: 11845 case Builtin::BIwcsncmp: 11846 case Builtin::BImemcmp: 11847 case Builtin::BIbcmp: 11848 case Builtin::BIwmemcmp: 11849 // A call to strlen is not a constant expression. 11850 if (Info.getLangOpts().CPlusPlus11) 11851 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11852 << /*isConstexpr*/0 << /*isConstructor*/0 11853 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11854 else 11855 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11856 LLVM_FALLTHROUGH; 11857 case Builtin::BI__builtin_strcmp: 11858 case Builtin::BI__builtin_wcscmp: 11859 case Builtin::BI__builtin_strncmp: 11860 case Builtin::BI__builtin_wcsncmp: 11861 case Builtin::BI__builtin_memcmp: 11862 case Builtin::BI__builtin_bcmp: 11863 case Builtin::BI__builtin_wmemcmp: { 11864 LValue String1, String2; 11865 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11866 !EvaluatePointer(E->getArg(1), String2, Info)) 11867 return false; 11868 11869 uint64_t MaxLength = uint64_t(-1); 11870 if (BuiltinOp != Builtin::BIstrcmp && 11871 BuiltinOp != Builtin::BIwcscmp && 11872 BuiltinOp != Builtin::BI__builtin_strcmp && 11873 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11874 APSInt N; 11875 if (!EvaluateInteger(E->getArg(2), N, Info)) 11876 return false; 11877 MaxLength = N.getExtValue(); 11878 } 11879 11880 // Empty substrings compare equal by definition. 11881 if (MaxLength == 0u) 11882 return Success(0, E); 11883 11884 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11885 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11886 String1.Designator.Invalid || String2.Designator.Invalid) 11887 return false; 11888 11889 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11890 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11891 11892 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11893 BuiltinOp == Builtin::BIbcmp || 11894 BuiltinOp == Builtin::BI__builtin_memcmp || 11895 BuiltinOp == Builtin::BI__builtin_bcmp; 11896 11897 assert(IsRawByte || 11898 (Info.Ctx.hasSameUnqualifiedType( 11899 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11900 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11901 11902 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11903 // 'char8_t', but no other types. 11904 if (IsRawByte && 11905 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11906 // FIXME: Consider using our bit_cast implementation to support this. 11907 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11908 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11909 << CharTy1 << CharTy2; 11910 return false; 11911 } 11912 11913 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11914 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11915 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11916 Char1.isInt() && Char2.isInt(); 11917 }; 11918 const auto &AdvanceElems = [&] { 11919 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11920 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11921 }; 11922 11923 bool StopAtNull = 11924 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11925 BuiltinOp != Builtin::BIwmemcmp && 11926 BuiltinOp != Builtin::BI__builtin_memcmp && 11927 BuiltinOp != Builtin::BI__builtin_bcmp && 11928 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11929 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11930 BuiltinOp == Builtin::BIwcsncmp || 11931 BuiltinOp == Builtin::BIwmemcmp || 11932 BuiltinOp == Builtin::BI__builtin_wcscmp || 11933 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11934 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11935 11936 for (; MaxLength; --MaxLength) { 11937 APValue Char1, Char2; 11938 if (!ReadCurElems(Char1, Char2)) 11939 return false; 11940 if (Char1.getInt().ne(Char2.getInt())) { 11941 if (IsWide) // wmemcmp compares with wchar_t signedness. 11942 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11943 // memcmp always compares unsigned chars. 11944 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11945 } 11946 if (StopAtNull && !Char1.getInt()) 11947 return Success(0, E); 11948 assert(!(StopAtNull && !Char2.getInt())); 11949 if (!AdvanceElems()) 11950 return false; 11951 } 11952 // We hit the strncmp / memcmp limit. 11953 return Success(0, E); 11954 } 11955 11956 case Builtin::BI__atomic_always_lock_free: 11957 case Builtin::BI__atomic_is_lock_free: 11958 case Builtin::BI__c11_atomic_is_lock_free: { 11959 APSInt SizeVal; 11960 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11961 return false; 11962 11963 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11964 // of two less than or equal to the maximum inline atomic width, we know it 11965 // is lock-free. If the size isn't a power of two, or greater than the 11966 // maximum alignment where we promote atomics, we know it is not lock-free 11967 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11968 // the answer can only be determined at runtime; for example, 16-byte 11969 // atomics have lock-free implementations on some, but not all, 11970 // x86-64 processors. 11971 11972 // Check power-of-two. 11973 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11974 if (Size.isPowerOfTwo()) { 11975 // Check against inlining width. 11976 unsigned InlineWidthBits = 11977 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11978 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11979 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11980 Size == CharUnits::One() || 11981 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11982 Expr::NPC_NeverValueDependent)) 11983 // OK, we will inline appropriately-aligned operations of this size, 11984 // and _Atomic(T) is appropriately-aligned. 11985 return Success(1, E); 11986 11987 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11988 castAs<PointerType>()->getPointeeType(); 11989 if (!PointeeType->isIncompleteType() && 11990 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11991 // OK, we will inline operations on this object. 11992 return Success(1, E); 11993 } 11994 } 11995 } 11996 11997 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11998 Success(0, E) : Error(E); 11999 } 12000 case Builtin::BIomp_is_initial_device: 12001 // We can decide statically which value the runtime would return if called. 12002 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 12003 case Builtin::BI__builtin_add_overflow: 12004 case Builtin::BI__builtin_sub_overflow: 12005 case Builtin::BI__builtin_mul_overflow: 12006 case Builtin::BI__builtin_sadd_overflow: 12007 case Builtin::BI__builtin_uadd_overflow: 12008 case Builtin::BI__builtin_uaddl_overflow: 12009 case Builtin::BI__builtin_uaddll_overflow: 12010 case Builtin::BI__builtin_usub_overflow: 12011 case Builtin::BI__builtin_usubl_overflow: 12012 case Builtin::BI__builtin_usubll_overflow: 12013 case Builtin::BI__builtin_umul_overflow: 12014 case Builtin::BI__builtin_umull_overflow: 12015 case Builtin::BI__builtin_umulll_overflow: 12016 case Builtin::BI__builtin_saddl_overflow: 12017 case Builtin::BI__builtin_saddll_overflow: 12018 case Builtin::BI__builtin_ssub_overflow: 12019 case Builtin::BI__builtin_ssubl_overflow: 12020 case Builtin::BI__builtin_ssubll_overflow: 12021 case Builtin::BI__builtin_smul_overflow: 12022 case Builtin::BI__builtin_smull_overflow: 12023 case Builtin::BI__builtin_smulll_overflow: { 12024 LValue ResultLValue; 12025 APSInt LHS, RHS; 12026 12027 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12028 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12029 !EvaluateInteger(E->getArg(1), RHS, Info) || 12030 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12031 return false; 12032 12033 APSInt Result; 12034 bool DidOverflow = false; 12035 12036 // If the types don't have to match, enlarge all 3 to the largest of them. 12037 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12038 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12039 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12040 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12041 ResultType->isSignedIntegerOrEnumerationType(); 12042 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12043 ResultType->isSignedIntegerOrEnumerationType(); 12044 uint64_t LHSSize = LHS.getBitWidth(); 12045 uint64_t RHSSize = RHS.getBitWidth(); 12046 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12047 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12048 12049 // Add an additional bit if the signedness isn't uniformly agreed to. We 12050 // could do this ONLY if there is a signed and an unsigned that both have 12051 // MaxBits, but the code to check that is pretty nasty. The issue will be 12052 // caught in the shrink-to-result later anyway. 12053 if (IsSigned && !AllSigned) 12054 ++MaxBits; 12055 12056 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12057 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12058 Result = APSInt(MaxBits, !IsSigned); 12059 } 12060 12061 // Find largest int. 12062 switch (BuiltinOp) { 12063 default: 12064 llvm_unreachable("Invalid value for BuiltinOp"); 12065 case Builtin::BI__builtin_add_overflow: 12066 case Builtin::BI__builtin_sadd_overflow: 12067 case Builtin::BI__builtin_saddl_overflow: 12068 case Builtin::BI__builtin_saddll_overflow: 12069 case Builtin::BI__builtin_uadd_overflow: 12070 case Builtin::BI__builtin_uaddl_overflow: 12071 case Builtin::BI__builtin_uaddll_overflow: 12072 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12073 : LHS.uadd_ov(RHS, DidOverflow); 12074 break; 12075 case Builtin::BI__builtin_sub_overflow: 12076 case Builtin::BI__builtin_ssub_overflow: 12077 case Builtin::BI__builtin_ssubl_overflow: 12078 case Builtin::BI__builtin_ssubll_overflow: 12079 case Builtin::BI__builtin_usub_overflow: 12080 case Builtin::BI__builtin_usubl_overflow: 12081 case Builtin::BI__builtin_usubll_overflow: 12082 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12083 : LHS.usub_ov(RHS, DidOverflow); 12084 break; 12085 case Builtin::BI__builtin_mul_overflow: 12086 case Builtin::BI__builtin_smul_overflow: 12087 case Builtin::BI__builtin_smull_overflow: 12088 case Builtin::BI__builtin_smulll_overflow: 12089 case Builtin::BI__builtin_umul_overflow: 12090 case Builtin::BI__builtin_umull_overflow: 12091 case Builtin::BI__builtin_umulll_overflow: 12092 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12093 : LHS.umul_ov(RHS, DidOverflow); 12094 break; 12095 } 12096 12097 // In the case where multiple sizes are allowed, truncate and see if 12098 // the values are the same. 12099 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12100 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12101 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12102 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12103 // since it will give us the behavior of a TruncOrSelf in the case where 12104 // its parameter <= its size. We previously set Result to be at least the 12105 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12106 // will work exactly like TruncOrSelf. 12107 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12108 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12109 12110 if (!APSInt::isSameValue(Temp, Result)) 12111 DidOverflow = true; 12112 Result = Temp; 12113 } 12114 12115 APValue APV{Result}; 12116 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12117 return false; 12118 return Success(DidOverflow, E); 12119 } 12120 } 12121 } 12122 12123 /// Determine whether this is a pointer past the end of the complete 12124 /// object referred to by the lvalue. 12125 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12126 const LValue &LV) { 12127 // A null pointer can be viewed as being "past the end" but we don't 12128 // choose to look at it that way here. 12129 if (!LV.getLValueBase()) 12130 return false; 12131 12132 // If the designator is valid and refers to a subobject, we're not pointing 12133 // past the end. 12134 if (!LV.getLValueDesignator().Invalid && 12135 !LV.getLValueDesignator().isOnePastTheEnd()) 12136 return false; 12137 12138 // A pointer to an incomplete type might be past-the-end if the type's size is 12139 // zero. We cannot tell because the type is incomplete. 12140 QualType Ty = getType(LV.getLValueBase()); 12141 if (Ty->isIncompleteType()) 12142 return true; 12143 12144 // We're a past-the-end pointer if we point to the byte after the object, 12145 // no matter what our type or path is. 12146 auto Size = Ctx.getTypeSizeInChars(Ty); 12147 return LV.getLValueOffset() == Size; 12148 } 12149 12150 namespace { 12151 12152 /// Data recursive integer evaluator of certain binary operators. 12153 /// 12154 /// We use a data recursive algorithm for binary operators so that we are able 12155 /// to handle extreme cases of chained binary operators without causing stack 12156 /// overflow. 12157 class DataRecursiveIntBinOpEvaluator { 12158 struct EvalResult { 12159 APValue Val; 12160 bool Failed; 12161 12162 EvalResult() : Failed(false) { } 12163 12164 void swap(EvalResult &RHS) { 12165 Val.swap(RHS.Val); 12166 Failed = RHS.Failed; 12167 RHS.Failed = false; 12168 } 12169 }; 12170 12171 struct Job { 12172 const Expr *E; 12173 EvalResult LHSResult; // meaningful only for binary operator expression. 12174 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12175 12176 Job() = default; 12177 Job(Job &&) = default; 12178 12179 void startSpeculativeEval(EvalInfo &Info) { 12180 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12181 } 12182 12183 private: 12184 SpeculativeEvaluationRAII SpecEvalRAII; 12185 }; 12186 12187 SmallVector<Job, 16> Queue; 12188 12189 IntExprEvaluator &IntEval; 12190 EvalInfo &Info; 12191 APValue &FinalResult; 12192 12193 public: 12194 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12195 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12196 12197 /// True if \param E is a binary operator that we are going to handle 12198 /// data recursively. 12199 /// We handle binary operators that are comma, logical, or that have operands 12200 /// with integral or enumeration type. 12201 static bool shouldEnqueue(const BinaryOperator *E) { 12202 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12203 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12204 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12205 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12206 } 12207 12208 bool Traverse(const BinaryOperator *E) { 12209 enqueue(E); 12210 EvalResult PrevResult; 12211 while (!Queue.empty()) 12212 process(PrevResult); 12213 12214 if (PrevResult.Failed) return false; 12215 12216 FinalResult.swap(PrevResult.Val); 12217 return true; 12218 } 12219 12220 private: 12221 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12222 return IntEval.Success(Value, E, Result); 12223 } 12224 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12225 return IntEval.Success(Value, E, Result); 12226 } 12227 bool Error(const Expr *E) { 12228 return IntEval.Error(E); 12229 } 12230 bool Error(const Expr *E, diag::kind D) { 12231 return IntEval.Error(E, D); 12232 } 12233 12234 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12235 return Info.CCEDiag(E, D); 12236 } 12237 12238 // Returns true if visiting the RHS is necessary, false otherwise. 12239 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12240 bool &SuppressRHSDiags); 12241 12242 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12243 const BinaryOperator *E, APValue &Result); 12244 12245 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12246 Result.Failed = !Evaluate(Result.Val, Info, E); 12247 if (Result.Failed) 12248 Result.Val = APValue(); 12249 } 12250 12251 void process(EvalResult &Result); 12252 12253 void enqueue(const Expr *E) { 12254 E = E->IgnoreParens(); 12255 Queue.resize(Queue.size()+1); 12256 Queue.back().E = E; 12257 Queue.back().Kind = Job::AnyExprKind; 12258 } 12259 }; 12260 12261 } 12262 12263 bool DataRecursiveIntBinOpEvaluator:: 12264 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12265 bool &SuppressRHSDiags) { 12266 if (E->getOpcode() == BO_Comma) { 12267 // Ignore LHS but note if we could not evaluate it. 12268 if (LHSResult.Failed) 12269 return Info.noteSideEffect(); 12270 return true; 12271 } 12272 12273 if (E->isLogicalOp()) { 12274 bool LHSAsBool; 12275 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12276 // We were able to evaluate the LHS, see if we can get away with not 12277 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12278 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12279 Success(LHSAsBool, E, LHSResult.Val); 12280 return false; // Ignore RHS 12281 } 12282 } else { 12283 LHSResult.Failed = true; 12284 12285 // Since we weren't able to evaluate the left hand side, it 12286 // might have had side effects. 12287 if (!Info.noteSideEffect()) 12288 return false; 12289 12290 // We can't evaluate the LHS; however, sometimes the result 12291 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12292 // Don't ignore RHS and suppress diagnostics from this arm. 12293 SuppressRHSDiags = true; 12294 } 12295 12296 return true; 12297 } 12298 12299 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12300 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12301 12302 if (LHSResult.Failed && !Info.noteFailure()) 12303 return false; // Ignore RHS; 12304 12305 return true; 12306 } 12307 12308 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12309 bool IsSub) { 12310 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12311 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12312 // offsets. 12313 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12314 CharUnits &Offset = LVal.getLValueOffset(); 12315 uint64_t Offset64 = Offset.getQuantity(); 12316 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12317 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12318 : Offset64 + Index64); 12319 } 12320 12321 bool DataRecursiveIntBinOpEvaluator:: 12322 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12323 const BinaryOperator *E, APValue &Result) { 12324 if (E->getOpcode() == BO_Comma) { 12325 if (RHSResult.Failed) 12326 return false; 12327 Result = RHSResult.Val; 12328 return true; 12329 } 12330 12331 if (E->isLogicalOp()) { 12332 bool lhsResult, rhsResult; 12333 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12334 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12335 12336 if (LHSIsOK) { 12337 if (RHSIsOK) { 12338 if (E->getOpcode() == BO_LOr) 12339 return Success(lhsResult || rhsResult, E, Result); 12340 else 12341 return Success(lhsResult && rhsResult, E, Result); 12342 } 12343 } else { 12344 if (RHSIsOK) { 12345 // We can't evaluate the LHS; however, sometimes the result 12346 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12347 if (rhsResult == (E->getOpcode() == BO_LOr)) 12348 return Success(rhsResult, E, Result); 12349 } 12350 } 12351 12352 return false; 12353 } 12354 12355 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12356 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12357 12358 if (LHSResult.Failed || RHSResult.Failed) 12359 return false; 12360 12361 const APValue &LHSVal = LHSResult.Val; 12362 const APValue &RHSVal = RHSResult.Val; 12363 12364 // Handle cases like (unsigned long)&a + 4. 12365 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12366 Result = LHSVal; 12367 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12368 return true; 12369 } 12370 12371 // Handle cases like 4 + (unsigned long)&a 12372 if (E->getOpcode() == BO_Add && 12373 RHSVal.isLValue() && LHSVal.isInt()) { 12374 Result = RHSVal; 12375 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12376 return true; 12377 } 12378 12379 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12380 // Handle (intptr_t)&&A - (intptr_t)&&B. 12381 if (!LHSVal.getLValueOffset().isZero() || 12382 !RHSVal.getLValueOffset().isZero()) 12383 return false; 12384 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12385 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12386 if (!LHSExpr || !RHSExpr) 12387 return false; 12388 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12389 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12390 if (!LHSAddrExpr || !RHSAddrExpr) 12391 return false; 12392 // Make sure both labels come from the same function. 12393 if (LHSAddrExpr->getLabel()->getDeclContext() != 12394 RHSAddrExpr->getLabel()->getDeclContext()) 12395 return false; 12396 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12397 return true; 12398 } 12399 12400 // All the remaining cases expect both operands to be an integer 12401 if (!LHSVal.isInt() || !RHSVal.isInt()) 12402 return Error(E); 12403 12404 // Set up the width and signedness manually, in case it can't be deduced 12405 // from the operation we're performing. 12406 // FIXME: Don't do this in the cases where we can deduce it. 12407 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12408 E->getType()->isUnsignedIntegerOrEnumerationType()); 12409 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12410 RHSVal.getInt(), Value)) 12411 return false; 12412 return Success(Value, E, Result); 12413 } 12414 12415 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12416 Job &job = Queue.back(); 12417 12418 switch (job.Kind) { 12419 case Job::AnyExprKind: { 12420 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12421 if (shouldEnqueue(Bop)) { 12422 job.Kind = Job::BinOpKind; 12423 enqueue(Bop->getLHS()); 12424 return; 12425 } 12426 } 12427 12428 EvaluateExpr(job.E, Result); 12429 Queue.pop_back(); 12430 return; 12431 } 12432 12433 case Job::BinOpKind: { 12434 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12435 bool SuppressRHSDiags = false; 12436 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12437 Queue.pop_back(); 12438 return; 12439 } 12440 if (SuppressRHSDiags) 12441 job.startSpeculativeEval(Info); 12442 job.LHSResult.swap(Result); 12443 job.Kind = Job::BinOpVisitedLHSKind; 12444 enqueue(Bop->getRHS()); 12445 return; 12446 } 12447 12448 case Job::BinOpVisitedLHSKind: { 12449 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12450 EvalResult RHS; 12451 RHS.swap(Result); 12452 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12453 Queue.pop_back(); 12454 return; 12455 } 12456 } 12457 12458 llvm_unreachable("Invalid Job::Kind!"); 12459 } 12460 12461 namespace { 12462 /// Used when we determine that we should fail, but can keep evaluating prior to 12463 /// noting that we had a failure. 12464 class DelayedNoteFailureRAII { 12465 EvalInfo &Info; 12466 bool NoteFailure; 12467 12468 public: 12469 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12470 : Info(Info), NoteFailure(NoteFailure) {} 12471 ~DelayedNoteFailureRAII() { 12472 if (NoteFailure) { 12473 bool ContinueAfterFailure = Info.noteFailure(); 12474 (void)ContinueAfterFailure; 12475 assert(ContinueAfterFailure && 12476 "Shouldn't have kept evaluating on failure."); 12477 } 12478 } 12479 }; 12480 12481 enum class CmpResult { 12482 Unequal, 12483 Less, 12484 Equal, 12485 Greater, 12486 Unordered, 12487 }; 12488 } 12489 12490 template <class SuccessCB, class AfterCB> 12491 static bool 12492 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12493 SuccessCB &&Success, AfterCB &&DoAfter) { 12494 assert(!E->isValueDependent()); 12495 assert(E->isComparisonOp() && "expected comparison operator"); 12496 assert((E->getOpcode() == BO_Cmp || 12497 E->getType()->isIntegralOrEnumerationType()) && 12498 "unsupported binary expression evaluation"); 12499 auto Error = [&](const Expr *E) { 12500 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12501 return false; 12502 }; 12503 12504 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12505 bool IsEquality = E->isEqualityOp(); 12506 12507 QualType LHSTy = E->getLHS()->getType(); 12508 QualType RHSTy = E->getRHS()->getType(); 12509 12510 if (LHSTy->isIntegralOrEnumerationType() && 12511 RHSTy->isIntegralOrEnumerationType()) { 12512 APSInt LHS, RHS; 12513 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12514 if (!LHSOK && !Info.noteFailure()) 12515 return false; 12516 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12517 return false; 12518 if (LHS < RHS) 12519 return Success(CmpResult::Less, E); 12520 if (LHS > RHS) 12521 return Success(CmpResult::Greater, E); 12522 return Success(CmpResult::Equal, E); 12523 } 12524 12525 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12526 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12527 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12528 12529 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12530 if (!LHSOK && !Info.noteFailure()) 12531 return false; 12532 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12533 return false; 12534 if (LHSFX < RHSFX) 12535 return Success(CmpResult::Less, E); 12536 if (LHSFX > RHSFX) 12537 return Success(CmpResult::Greater, E); 12538 return Success(CmpResult::Equal, E); 12539 } 12540 12541 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12542 ComplexValue LHS, RHS; 12543 bool LHSOK; 12544 if (E->isAssignmentOp()) { 12545 LValue LV; 12546 EvaluateLValue(E->getLHS(), LV, Info); 12547 LHSOK = false; 12548 } else if (LHSTy->isRealFloatingType()) { 12549 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12550 if (LHSOK) { 12551 LHS.makeComplexFloat(); 12552 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12553 } 12554 } else { 12555 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12556 } 12557 if (!LHSOK && !Info.noteFailure()) 12558 return false; 12559 12560 if (E->getRHS()->getType()->isRealFloatingType()) { 12561 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12562 return false; 12563 RHS.makeComplexFloat(); 12564 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12565 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12566 return false; 12567 12568 if (LHS.isComplexFloat()) { 12569 APFloat::cmpResult CR_r = 12570 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12571 APFloat::cmpResult CR_i = 12572 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12573 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12574 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12575 } else { 12576 assert(IsEquality && "invalid complex comparison"); 12577 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12578 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12579 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12580 } 12581 } 12582 12583 if (LHSTy->isRealFloatingType() && 12584 RHSTy->isRealFloatingType()) { 12585 APFloat RHS(0.0), LHS(0.0); 12586 12587 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12588 if (!LHSOK && !Info.noteFailure()) 12589 return false; 12590 12591 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12592 return false; 12593 12594 assert(E->isComparisonOp() && "Invalid binary operator!"); 12595 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12596 if (!Info.InConstantContext && 12597 APFloatCmpResult == APFloat::cmpUnordered && 12598 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12599 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12600 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12601 return false; 12602 } 12603 auto GetCmpRes = [&]() { 12604 switch (APFloatCmpResult) { 12605 case APFloat::cmpEqual: 12606 return CmpResult::Equal; 12607 case APFloat::cmpLessThan: 12608 return CmpResult::Less; 12609 case APFloat::cmpGreaterThan: 12610 return CmpResult::Greater; 12611 case APFloat::cmpUnordered: 12612 return CmpResult::Unordered; 12613 } 12614 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12615 }; 12616 return Success(GetCmpRes(), E); 12617 } 12618 12619 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12620 LValue LHSValue, RHSValue; 12621 12622 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12623 if (!LHSOK && !Info.noteFailure()) 12624 return false; 12625 12626 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12627 return false; 12628 12629 // Reject differing bases from the normal codepath; we special-case 12630 // comparisons to null. 12631 if (!HasSameBase(LHSValue, RHSValue)) { 12632 // Inequalities and subtractions between unrelated pointers have 12633 // unspecified or undefined behavior. 12634 if (!IsEquality) { 12635 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12636 return false; 12637 } 12638 // A constant address may compare equal to the address of a symbol. 12639 // The one exception is that address of an object cannot compare equal 12640 // to a null pointer constant. 12641 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12642 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12643 return Error(E); 12644 // It's implementation-defined whether distinct literals will have 12645 // distinct addresses. In clang, the result of such a comparison is 12646 // unspecified, so it is not a constant expression. However, we do know 12647 // that the address of a literal will be non-null. 12648 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12649 LHSValue.Base && RHSValue.Base) 12650 return Error(E); 12651 // We can't tell whether weak symbols will end up pointing to the same 12652 // object. 12653 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12654 return Error(E); 12655 // We can't compare the address of the start of one object with the 12656 // past-the-end address of another object, per C++ DR1652. 12657 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12658 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12659 (RHSValue.Base && RHSValue.Offset.isZero() && 12660 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12661 return Error(E); 12662 // We can't tell whether an object is at the same address as another 12663 // zero sized object. 12664 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12665 (LHSValue.Base && isZeroSized(RHSValue))) 12666 return Error(E); 12667 return Success(CmpResult::Unequal, E); 12668 } 12669 12670 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12671 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12672 12673 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12674 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12675 12676 // C++11 [expr.rel]p3: 12677 // Pointers to void (after pointer conversions) can be compared, with a 12678 // result defined as follows: If both pointers represent the same 12679 // address or are both the null pointer value, the result is true if the 12680 // operator is <= or >= and false otherwise; otherwise the result is 12681 // unspecified. 12682 // We interpret this as applying to pointers to *cv* void. 12683 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12684 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12685 12686 // C++11 [expr.rel]p2: 12687 // - If two pointers point to non-static data members of the same object, 12688 // or to subobjects or array elements fo such members, recursively, the 12689 // pointer to the later declared member compares greater provided the 12690 // two members have the same access control and provided their class is 12691 // not a union. 12692 // [...] 12693 // - Otherwise pointer comparisons are unspecified. 12694 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12695 bool WasArrayIndex; 12696 unsigned Mismatch = FindDesignatorMismatch( 12697 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12698 // At the point where the designators diverge, the comparison has a 12699 // specified value if: 12700 // - we are comparing array indices 12701 // - we are comparing fields of a union, or fields with the same access 12702 // Otherwise, the result is unspecified and thus the comparison is not a 12703 // constant expression. 12704 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12705 Mismatch < RHSDesignator.Entries.size()) { 12706 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12707 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12708 if (!LF && !RF) 12709 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12710 else if (!LF) 12711 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12712 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12713 << RF->getParent() << RF; 12714 else if (!RF) 12715 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12716 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12717 << LF->getParent() << LF; 12718 else if (!LF->getParent()->isUnion() && 12719 LF->getAccess() != RF->getAccess()) 12720 Info.CCEDiag(E, 12721 diag::note_constexpr_pointer_comparison_differing_access) 12722 << LF << LF->getAccess() << RF << RF->getAccess() 12723 << LF->getParent(); 12724 } 12725 } 12726 12727 // The comparison here must be unsigned, and performed with the same 12728 // width as the pointer. 12729 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12730 uint64_t CompareLHS = LHSOffset.getQuantity(); 12731 uint64_t CompareRHS = RHSOffset.getQuantity(); 12732 assert(PtrSize <= 64 && "Unexpected pointer width"); 12733 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12734 CompareLHS &= Mask; 12735 CompareRHS &= Mask; 12736 12737 // If there is a base and this is a relational operator, we can only 12738 // compare pointers within the object in question; otherwise, the result 12739 // depends on where the object is located in memory. 12740 if (!LHSValue.Base.isNull() && IsRelational) { 12741 QualType BaseTy = getType(LHSValue.Base); 12742 if (BaseTy->isIncompleteType()) 12743 return Error(E); 12744 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12745 uint64_t OffsetLimit = Size.getQuantity(); 12746 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12747 return Error(E); 12748 } 12749 12750 if (CompareLHS < CompareRHS) 12751 return Success(CmpResult::Less, E); 12752 if (CompareLHS > CompareRHS) 12753 return Success(CmpResult::Greater, E); 12754 return Success(CmpResult::Equal, E); 12755 } 12756 12757 if (LHSTy->isMemberPointerType()) { 12758 assert(IsEquality && "unexpected member pointer operation"); 12759 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12760 12761 MemberPtr LHSValue, RHSValue; 12762 12763 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12764 if (!LHSOK && !Info.noteFailure()) 12765 return false; 12766 12767 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12768 return false; 12769 12770 // C++11 [expr.eq]p2: 12771 // If both operands are null, they compare equal. Otherwise if only one is 12772 // null, they compare unequal. 12773 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12774 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12775 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12776 } 12777 12778 // Otherwise if either is a pointer to a virtual member function, the 12779 // result is unspecified. 12780 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12781 if (MD->isVirtual()) 12782 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12783 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12784 if (MD->isVirtual()) 12785 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12786 12787 // Otherwise they compare equal if and only if they would refer to the 12788 // same member of the same most derived object or the same subobject if 12789 // they were dereferenced with a hypothetical object of the associated 12790 // class type. 12791 bool Equal = LHSValue == RHSValue; 12792 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12793 } 12794 12795 if (LHSTy->isNullPtrType()) { 12796 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12797 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12798 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12799 // are compared, the result is true of the operator is <=, >= or ==, and 12800 // false otherwise. 12801 return Success(CmpResult::Equal, E); 12802 } 12803 12804 return DoAfter(); 12805 } 12806 12807 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12808 if (!CheckLiteralType(Info, E)) 12809 return false; 12810 12811 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12812 ComparisonCategoryResult CCR; 12813 switch (CR) { 12814 case CmpResult::Unequal: 12815 llvm_unreachable("should never produce Unequal for three-way comparison"); 12816 case CmpResult::Less: 12817 CCR = ComparisonCategoryResult::Less; 12818 break; 12819 case CmpResult::Equal: 12820 CCR = ComparisonCategoryResult::Equal; 12821 break; 12822 case CmpResult::Greater: 12823 CCR = ComparisonCategoryResult::Greater; 12824 break; 12825 case CmpResult::Unordered: 12826 CCR = ComparisonCategoryResult::Unordered; 12827 break; 12828 } 12829 // Evaluation succeeded. Lookup the information for the comparison category 12830 // type and fetch the VarDecl for the result. 12831 const ComparisonCategoryInfo &CmpInfo = 12832 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12833 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12834 // Check and evaluate the result as a constant expression. 12835 LValue LV; 12836 LV.set(VD); 12837 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12838 return false; 12839 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12840 ConstantExprKind::Normal); 12841 }; 12842 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12843 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12844 }); 12845 } 12846 12847 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12848 // We don't call noteFailure immediately because the assignment happens after 12849 // we evaluate LHS and RHS. 12850 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12851 return Error(E); 12852 12853 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12854 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12855 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12856 12857 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12858 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12859 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12860 12861 if (E->isComparisonOp()) { 12862 // Evaluate builtin binary comparisons by evaluating them as three-way 12863 // comparisons and then translating the result. 12864 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12865 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12866 "should only produce Unequal for equality comparisons"); 12867 bool IsEqual = CR == CmpResult::Equal, 12868 IsLess = CR == CmpResult::Less, 12869 IsGreater = CR == CmpResult::Greater; 12870 auto Op = E->getOpcode(); 12871 switch (Op) { 12872 default: 12873 llvm_unreachable("unsupported binary operator"); 12874 case BO_EQ: 12875 case BO_NE: 12876 return Success(IsEqual == (Op == BO_EQ), E); 12877 case BO_LT: 12878 return Success(IsLess, E); 12879 case BO_GT: 12880 return Success(IsGreater, E); 12881 case BO_LE: 12882 return Success(IsEqual || IsLess, E); 12883 case BO_GE: 12884 return Success(IsEqual || IsGreater, E); 12885 } 12886 }; 12887 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12888 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12889 }); 12890 } 12891 12892 QualType LHSTy = E->getLHS()->getType(); 12893 QualType RHSTy = E->getRHS()->getType(); 12894 12895 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12896 E->getOpcode() == BO_Sub) { 12897 LValue LHSValue, RHSValue; 12898 12899 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12900 if (!LHSOK && !Info.noteFailure()) 12901 return false; 12902 12903 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12904 return false; 12905 12906 // Reject differing bases from the normal codepath; we special-case 12907 // comparisons to null. 12908 if (!HasSameBase(LHSValue, RHSValue)) { 12909 // Handle &&A - &&B. 12910 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12911 return Error(E); 12912 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12913 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12914 if (!LHSExpr || !RHSExpr) 12915 return Error(E); 12916 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12917 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12918 if (!LHSAddrExpr || !RHSAddrExpr) 12919 return Error(E); 12920 // Make sure both labels come from the same function. 12921 if (LHSAddrExpr->getLabel()->getDeclContext() != 12922 RHSAddrExpr->getLabel()->getDeclContext()) 12923 return Error(E); 12924 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12925 } 12926 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12927 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12928 12929 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12930 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12931 12932 // C++11 [expr.add]p6: 12933 // Unless both pointers point to elements of the same array object, or 12934 // one past the last element of the array object, the behavior is 12935 // undefined. 12936 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12937 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12938 RHSDesignator)) 12939 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12940 12941 QualType Type = E->getLHS()->getType(); 12942 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12943 12944 CharUnits ElementSize; 12945 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12946 return false; 12947 12948 // As an extension, a type may have zero size (empty struct or union in 12949 // C, array of zero length). Pointer subtraction in such cases has 12950 // undefined behavior, so is not constant. 12951 if (ElementSize.isZero()) { 12952 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12953 << ElementType; 12954 return false; 12955 } 12956 12957 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12958 // and produce incorrect results when it overflows. Such behavior 12959 // appears to be non-conforming, but is common, so perhaps we should 12960 // assume the standard intended for such cases to be undefined behavior 12961 // and check for them. 12962 12963 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12964 // overflow in the final conversion to ptrdiff_t. 12965 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12966 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12967 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12968 false); 12969 APSInt TrueResult = (LHS - RHS) / ElemSize; 12970 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12971 12972 if (Result.extend(65) != TrueResult && 12973 !HandleOverflow(Info, E, TrueResult, E->getType())) 12974 return false; 12975 return Success(Result, E); 12976 } 12977 12978 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12979 } 12980 12981 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12982 /// a result as the expression's type. 12983 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12984 const UnaryExprOrTypeTraitExpr *E) { 12985 switch(E->getKind()) { 12986 case UETT_PreferredAlignOf: 12987 case UETT_AlignOf: { 12988 if (E->isArgumentType()) 12989 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12990 E); 12991 else 12992 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12993 E); 12994 } 12995 12996 case UETT_VecStep: { 12997 QualType Ty = E->getTypeOfArgument(); 12998 12999 if (Ty->isVectorType()) { 13000 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13001 13002 // The vec_step built-in functions that take a 3-component 13003 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13004 if (n == 3) 13005 n = 4; 13006 13007 return Success(n, E); 13008 } else 13009 return Success(1, E); 13010 } 13011 13012 case UETT_SizeOf: { 13013 QualType SrcTy = E->getTypeOfArgument(); 13014 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13015 // the result is the size of the referenced type." 13016 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13017 SrcTy = Ref->getPointeeType(); 13018 13019 CharUnits Sizeof; 13020 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13021 return false; 13022 return Success(Sizeof, E); 13023 } 13024 case UETT_OpenMPRequiredSimdAlign: 13025 assert(E->isArgumentType()); 13026 return Success( 13027 Info.Ctx.toCharUnitsFromBits( 13028 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13029 .getQuantity(), 13030 E); 13031 } 13032 13033 llvm_unreachable("unknown expr/type trait"); 13034 } 13035 13036 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13037 CharUnits Result; 13038 unsigned n = OOE->getNumComponents(); 13039 if (n == 0) 13040 return Error(OOE); 13041 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13042 for (unsigned i = 0; i != n; ++i) { 13043 OffsetOfNode ON = OOE->getComponent(i); 13044 switch (ON.getKind()) { 13045 case OffsetOfNode::Array: { 13046 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13047 APSInt IdxResult; 13048 if (!EvaluateInteger(Idx, IdxResult, Info)) 13049 return false; 13050 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13051 if (!AT) 13052 return Error(OOE); 13053 CurrentType = AT->getElementType(); 13054 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13055 Result += IdxResult.getSExtValue() * ElementSize; 13056 break; 13057 } 13058 13059 case OffsetOfNode::Field: { 13060 FieldDecl *MemberDecl = ON.getField(); 13061 const RecordType *RT = CurrentType->getAs<RecordType>(); 13062 if (!RT) 13063 return Error(OOE); 13064 RecordDecl *RD = RT->getDecl(); 13065 if (RD->isInvalidDecl()) return false; 13066 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13067 unsigned i = MemberDecl->getFieldIndex(); 13068 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13069 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13070 CurrentType = MemberDecl->getType().getNonReferenceType(); 13071 break; 13072 } 13073 13074 case OffsetOfNode::Identifier: 13075 llvm_unreachable("dependent __builtin_offsetof"); 13076 13077 case OffsetOfNode::Base: { 13078 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13079 if (BaseSpec->isVirtual()) 13080 return Error(OOE); 13081 13082 // Find the layout of the class whose base we are looking into. 13083 const RecordType *RT = CurrentType->getAs<RecordType>(); 13084 if (!RT) 13085 return Error(OOE); 13086 RecordDecl *RD = RT->getDecl(); 13087 if (RD->isInvalidDecl()) return false; 13088 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13089 13090 // Find the base class itself. 13091 CurrentType = BaseSpec->getType(); 13092 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13093 if (!BaseRT) 13094 return Error(OOE); 13095 13096 // Add the offset to the base. 13097 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13098 break; 13099 } 13100 } 13101 } 13102 return Success(Result, OOE); 13103 } 13104 13105 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13106 switch (E->getOpcode()) { 13107 default: 13108 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13109 // See C99 6.6p3. 13110 return Error(E); 13111 case UO_Extension: 13112 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13113 // If so, we could clear the diagnostic ID. 13114 return Visit(E->getSubExpr()); 13115 case UO_Plus: 13116 // The result is just the value. 13117 return Visit(E->getSubExpr()); 13118 case UO_Minus: { 13119 if (!Visit(E->getSubExpr())) 13120 return false; 13121 if (!Result.isInt()) return Error(E); 13122 const APSInt &Value = Result.getInt(); 13123 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13124 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13125 E->getType())) 13126 return false; 13127 return Success(-Value, E); 13128 } 13129 case UO_Not: { 13130 if (!Visit(E->getSubExpr())) 13131 return false; 13132 if (!Result.isInt()) return Error(E); 13133 return Success(~Result.getInt(), E); 13134 } 13135 case UO_LNot: { 13136 bool bres; 13137 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13138 return false; 13139 return Success(!bres, E); 13140 } 13141 } 13142 } 13143 13144 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13145 /// result type is integer. 13146 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13147 const Expr *SubExpr = E->getSubExpr(); 13148 QualType DestType = E->getType(); 13149 QualType SrcType = SubExpr->getType(); 13150 13151 switch (E->getCastKind()) { 13152 case CK_BaseToDerived: 13153 case CK_DerivedToBase: 13154 case CK_UncheckedDerivedToBase: 13155 case CK_Dynamic: 13156 case CK_ToUnion: 13157 case CK_ArrayToPointerDecay: 13158 case CK_FunctionToPointerDecay: 13159 case CK_NullToPointer: 13160 case CK_NullToMemberPointer: 13161 case CK_BaseToDerivedMemberPointer: 13162 case CK_DerivedToBaseMemberPointer: 13163 case CK_ReinterpretMemberPointer: 13164 case CK_ConstructorConversion: 13165 case CK_IntegralToPointer: 13166 case CK_ToVoid: 13167 case CK_VectorSplat: 13168 case CK_IntegralToFloating: 13169 case CK_FloatingCast: 13170 case CK_CPointerToObjCPointerCast: 13171 case CK_BlockPointerToObjCPointerCast: 13172 case CK_AnyPointerToBlockPointerCast: 13173 case CK_ObjCObjectLValueCast: 13174 case CK_FloatingRealToComplex: 13175 case CK_FloatingComplexToReal: 13176 case CK_FloatingComplexCast: 13177 case CK_FloatingComplexToIntegralComplex: 13178 case CK_IntegralRealToComplex: 13179 case CK_IntegralComplexCast: 13180 case CK_IntegralComplexToFloatingComplex: 13181 case CK_BuiltinFnToFnPtr: 13182 case CK_ZeroToOCLOpaqueType: 13183 case CK_NonAtomicToAtomic: 13184 case CK_AddressSpaceConversion: 13185 case CK_IntToOCLSampler: 13186 case CK_FloatingToFixedPoint: 13187 case CK_FixedPointToFloating: 13188 case CK_FixedPointCast: 13189 case CK_IntegralToFixedPoint: 13190 llvm_unreachable("invalid cast kind for integral value"); 13191 13192 case CK_BitCast: 13193 case CK_Dependent: 13194 case CK_LValueBitCast: 13195 case CK_ARCProduceObject: 13196 case CK_ARCConsumeObject: 13197 case CK_ARCReclaimReturnedObject: 13198 case CK_ARCExtendBlockObject: 13199 case CK_CopyAndAutoreleaseBlockObject: 13200 return Error(E); 13201 13202 case CK_UserDefinedConversion: 13203 case CK_LValueToRValue: 13204 case CK_AtomicToNonAtomic: 13205 case CK_NoOp: 13206 case CK_LValueToRValueBitCast: 13207 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13208 13209 case CK_MemberPointerToBoolean: 13210 case CK_PointerToBoolean: 13211 case CK_IntegralToBoolean: 13212 case CK_FloatingToBoolean: 13213 case CK_BooleanToSignedIntegral: 13214 case CK_FloatingComplexToBoolean: 13215 case CK_IntegralComplexToBoolean: { 13216 bool BoolResult; 13217 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13218 return false; 13219 uint64_t IntResult = BoolResult; 13220 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13221 IntResult = (uint64_t)-1; 13222 return Success(IntResult, E); 13223 } 13224 13225 case CK_FixedPointToIntegral: { 13226 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13227 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13228 return false; 13229 bool Overflowed; 13230 llvm::APSInt Result = Src.convertToInt( 13231 Info.Ctx.getIntWidth(DestType), 13232 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13233 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13234 return false; 13235 return Success(Result, E); 13236 } 13237 13238 case CK_FixedPointToBoolean: { 13239 // Unsigned padding does not affect this. 13240 APValue Val; 13241 if (!Evaluate(Val, Info, SubExpr)) 13242 return false; 13243 return Success(Val.getFixedPoint().getBoolValue(), E); 13244 } 13245 13246 case CK_IntegralCast: { 13247 if (!Visit(SubExpr)) 13248 return false; 13249 13250 if (!Result.isInt()) { 13251 // Allow casts of address-of-label differences if they are no-ops 13252 // or narrowing. (The narrowing case isn't actually guaranteed to 13253 // be constant-evaluatable except in some narrow cases which are hard 13254 // to detect here. We let it through on the assumption the user knows 13255 // what they are doing.) 13256 if (Result.isAddrLabelDiff()) 13257 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13258 // Only allow casts of lvalues if they are lossless. 13259 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13260 } 13261 13262 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13263 Result.getInt()), E); 13264 } 13265 13266 case CK_PointerToIntegral: { 13267 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13268 13269 LValue LV; 13270 if (!EvaluatePointer(SubExpr, LV, Info)) 13271 return false; 13272 13273 if (LV.getLValueBase()) { 13274 // Only allow based lvalue casts if they are lossless. 13275 // FIXME: Allow a larger integer size than the pointer size, and allow 13276 // narrowing back down to pointer width in subsequent integral casts. 13277 // FIXME: Check integer type's active bits, not its type size. 13278 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13279 return Error(E); 13280 13281 LV.Designator.setInvalid(); 13282 LV.moveInto(Result); 13283 return true; 13284 } 13285 13286 APSInt AsInt; 13287 APValue V; 13288 LV.moveInto(V); 13289 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13290 llvm_unreachable("Can't cast this!"); 13291 13292 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13293 } 13294 13295 case CK_IntegralComplexToReal: { 13296 ComplexValue C; 13297 if (!EvaluateComplex(SubExpr, C, Info)) 13298 return false; 13299 return Success(C.getComplexIntReal(), E); 13300 } 13301 13302 case CK_FloatingToIntegral: { 13303 APFloat F(0.0); 13304 if (!EvaluateFloat(SubExpr, F, Info)) 13305 return false; 13306 13307 APSInt Value; 13308 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13309 return false; 13310 return Success(Value, E); 13311 } 13312 } 13313 13314 llvm_unreachable("unknown cast resulting in integral value"); 13315 } 13316 13317 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13318 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13319 ComplexValue LV; 13320 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13321 return false; 13322 if (!LV.isComplexInt()) 13323 return Error(E); 13324 return Success(LV.getComplexIntReal(), E); 13325 } 13326 13327 return Visit(E->getSubExpr()); 13328 } 13329 13330 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13331 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13332 ComplexValue LV; 13333 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13334 return false; 13335 if (!LV.isComplexInt()) 13336 return Error(E); 13337 return Success(LV.getComplexIntImag(), E); 13338 } 13339 13340 VisitIgnoredValue(E->getSubExpr()); 13341 return Success(0, E); 13342 } 13343 13344 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13345 return Success(E->getPackLength(), E); 13346 } 13347 13348 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13349 return Success(E->getValue(), E); 13350 } 13351 13352 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13353 const ConceptSpecializationExpr *E) { 13354 return Success(E->isSatisfied(), E); 13355 } 13356 13357 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13358 return Success(E->isSatisfied(), E); 13359 } 13360 13361 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13362 switch (E->getOpcode()) { 13363 default: 13364 // Invalid unary operators 13365 return Error(E); 13366 case UO_Plus: 13367 // The result is just the value. 13368 return Visit(E->getSubExpr()); 13369 case UO_Minus: { 13370 if (!Visit(E->getSubExpr())) return false; 13371 if (!Result.isFixedPoint()) 13372 return Error(E); 13373 bool Overflowed; 13374 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13375 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13376 return false; 13377 return Success(Negated, E); 13378 } 13379 case UO_LNot: { 13380 bool bres; 13381 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13382 return false; 13383 return Success(!bres, E); 13384 } 13385 } 13386 } 13387 13388 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13389 const Expr *SubExpr = E->getSubExpr(); 13390 QualType DestType = E->getType(); 13391 assert(DestType->isFixedPointType() && 13392 "Expected destination type to be a fixed point type"); 13393 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13394 13395 switch (E->getCastKind()) { 13396 case CK_FixedPointCast: { 13397 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13398 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13399 return false; 13400 bool Overflowed; 13401 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13402 if (Overflowed) { 13403 if (Info.checkingForUndefinedBehavior()) 13404 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13405 diag::warn_fixedpoint_constant_overflow) 13406 << Result.toString() << E->getType(); 13407 else if (!HandleOverflow(Info, E, Result, E->getType())) 13408 return false; 13409 } 13410 return Success(Result, E); 13411 } 13412 case CK_IntegralToFixedPoint: { 13413 APSInt Src; 13414 if (!EvaluateInteger(SubExpr, Src, Info)) 13415 return false; 13416 13417 bool Overflowed; 13418 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13419 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13420 13421 if (Overflowed) { 13422 if (Info.checkingForUndefinedBehavior()) 13423 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13424 diag::warn_fixedpoint_constant_overflow) 13425 << IntResult.toString() << E->getType(); 13426 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13427 return false; 13428 } 13429 13430 return Success(IntResult, E); 13431 } 13432 case CK_FloatingToFixedPoint: { 13433 APFloat Src(0.0); 13434 if (!EvaluateFloat(SubExpr, Src, Info)) 13435 return false; 13436 13437 bool Overflowed; 13438 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13439 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13440 13441 if (Overflowed) { 13442 if (Info.checkingForUndefinedBehavior()) 13443 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13444 diag::warn_fixedpoint_constant_overflow) 13445 << Result.toString() << E->getType(); 13446 else if (!HandleOverflow(Info, E, Result, E->getType())) 13447 return false; 13448 } 13449 13450 return Success(Result, E); 13451 } 13452 case CK_NoOp: 13453 case CK_LValueToRValue: 13454 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13455 default: 13456 return Error(E); 13457 } 13458 } 13459 13460 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13461 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13462 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13463 13464 const Expr *LHS = E->getLHS(); 13465 const Expr *RHS = E->getRHS(); 13466 FixedPointSemantics ResultFXSema = 13467 Info.Ctx.getFixedPointSemantics(E->getType()); 13468 13469 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13470 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13471 return false; 13472 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13473 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13474 return false; 13475 13476 bool OpOverflow = false, ConversionOverflow = false; 13477 APFixedPoint Result(LHSFX.getSemantics()); 13478 switch (E->getOpcode()) { 13479 case BO_Add: { 13480 Result = LHSFX.add(RHSFX, &OpOverflow) 13481 .convert(ResultFXSema, &ConversionOverflow); 13482 break; 13483 } 13484 case BO_Sub: { 13485 Result = LHSFX.sub(RHSFX, &OpOverflow) 13486 .convert(ResultFXSema, &ConversionOverflow); 13487 break; 13488 } 13489 case BO_Mul: { 13490 Result = LHSFX.mul(RHSFX, &OpOverflow) 13491 .convert(ResultFXSema, &ConversionOverflow); 13492 break; 13493 } 13494 case BO_Div: { 13495 if (RHSFX.getValue() == 0) { 13496 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13497 return false; 13498 } 13499 Result = LHSFX.div(RHSFX, &OpOverflow) 13500 .convert(ResultFXSema, &ConversionOverflow); 13501 break; 13502 } 13503 case BO_Shl: 13504 case BO_Shr: { 13505 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13506 llvm::APSInt RHSVal = RHSFX.getValue(); 13507 13508 unsigned ShiftBW = 13509 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13510 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13511 // Embedded-C 4.1.6.2.2: 13512 // The right operand must be nonnegative and less than the total number 13513 // of (nonpadding) bits of the fixed-point operand ... 13514 if (RHSVal.isNegative()) 13515 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13516 else if (Amt != RHSVal) 13517 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13518 << RHSVal << E->getType() << ShiftBW; 13519 13520 if (E->getOpcode() == BO_Shl) 13521 Result = LHSFX.shl(Amt, &OpOverflow); 13522 else 13523 Result = LHSFX.shr(Amt, &OpOverflow); 13524 break; 13525 } 13526 default: 13527 return false; 13528 } 13529 if (OpOverflow || ConversionOverflow) { 13530 if (Info.checkingForUndefinedBehavior()) 13531 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13532 diag::warn_fixedpoint_constant_overflow) 13533 << Result.toString() << E->getType(); 13534 else if (!HandleOverflow(Info, E, Result, E->getType())) 13535 return false; 13536 } 13537 return Success(Result, E); 13538 } 13539 13540 //===----------------------------------------------------------------------===// 13541 // Float Evaluation 13542 //===----------------------------------------------------------------------===// 13543 13544 namespace { 13545 class FloatExprEvaluator 13546 : public ExprEvaluatorBase<FloatExprEvaluator> { 13547 APFloat &Result; 13548 public: 13549 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13550 : ExprEvaluatorBaseTy(info), Result(result) {} 13551 13552 bool Success(const APValue &V, const Expr *e) { 13553 Result = V.getFloat(); 13554 return true; 13555 } 13556 13557 bool ZeroInitialization(const Expr *E) { 13558 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13559 return true; 13560 } 13561 13562 bool VisitCallExpr(const CallExpr *E); 13563 13564 bool VisitUnaryOperator(const UnaryOperator *E); 13565 bool VisitBinaryOperator(const BinaryOperator *E); 13566 bool VisitFloatingLiteral(const FloatingLiteral *E); 13567 bool VisitCastExpr(const CastExpr *E); 13568 13569 bool VisitUnaryReal(const UnaryOperator *E); 13570 bool VisitUnaryImag(const UnaryOperator *E); 13571 13572 // FIXME: Missing: array subscript of vector, member of vector 13573 }; 13574 } // end anonymous namespace 13575 13576 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13577 assert(!E->isValueDependent()); 13578 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13579 return FloatExprEvaluator(Info, Result).Visit(E); 13580 } 13581 13582 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13583 QualType ResultTy, 13584 const Expr *Arg, 13585 bool SNaN, 13586 llvm::APFloat &Result) { 13587 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13588 if (!S) return false; 13589 13590 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13591 13592 llvm::APInt fill; 13593 13594 // Treat empty strings as if they were zero. 13595 if (S->getString().empty()) 13596 fill = llvm::APInt(32, 0); 13597 else if (S->getString().getAsInteger(0, fill)) 13598 return false; 13599 13600 if (Context.getTargetInfo().isNan2008()) { 13601 if (SNaN) 13602 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13603 else 13604 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13605 } else { 13606 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13607 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13608 // a different encoding to what became a standard in 2008, and for pre- 13609 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13610 // sNaN. This is now known as "legacy NaN" encoding. 13611 if (SNaN) 13612 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13613 else 13614 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13615 } 13616 13617 return true; 13618 } 13619 13620 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13621 switch (E->getBuiltinCallee()) { 13622 default: 13623 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13624 13625 case Builtin::BI__builtin_huge_val: 13626 case Builtin::BI__builtin_huge_valf: 13627 case Builtin::BI__builtin_huge_vall: 13628 case Builtin::BI__builtin_huge_valf128: 13629 case Builtin::BI__builtin_inf: 13630 case Builtin::BI__builtin_inff: 13631 case Builtin::BI__builtin_infl: 13632 case Builtin::BI__builtin_inff128: { 13633 const llvm::fltSemantics &Sem = 13634 Info.Ctx.getFloatTypeSemantics(E->getType()); 13635 Result = llvm::APFloat::getInf(Sem); 13636 return true; 13637 } 13638 13639 case Builtin::BI__builtin_nans: 13640 case Builtin::BI__builtin_nansf: 13641 case Builtin::BI__builtin_nansl: 13642 case Builtin::BI__builtin_nansf128: 13643 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13644 true, Result)) 13645 return Error(E); 13646 return true; 13647 13648 case Builtin::BI__builtin_nan: 13649 case Builtin::BI__builtin_nanf: 13650 case Builtin::BI__builtin_nanl: 13651 case Builtin::BI__builtin_nanf128: 13652 // If this is __builtin_nan() turn this into a nan, otherwise we 13653 // can't constant fold it. 13654 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13655 false, Result)) 13656 return Error(E); 13657 return true; 13658 13659 case Builtin::BI__builtin_fabs: 13660 case Builtin::BI__builtin_fabsf: 13661 case Builtin::BI__builtin_fabsl: 13662 case Builtin::BI__builtin_fabsf128: 13663 // The C standard says "fabs raises no floating-point exceptions, 13664 // even if x is a signaling NaN. The returned value is independent of 13665 // the current rounding direction mode." Therefore constant folding can 13666 // proceed without regard to the floating point settings. 13667 // Reference, WG14 N2478 F.10.4.3 13668 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13669 return false; 13670 13671 if (Result.isNegative()) 13672 Result.changeSign(); 13673 return true; 13674 13675 // FIXME: Builtin::BI__builtin_powi 13676 // FIXME: Builtin::BI__builtin_powif 13677 // FIXME: Builtin::BI__builtin_powil 13678 13679 case Builtin::BI__builtin_copysign: 13680 case Builtin::BI__builtin_copysignf: 13681 case Builtin::BI__builtin_copysignl: 13682 case Builtin::BI__builtin_copysignf128: { 13683 APFloat RHS(0.); 13684 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13685 !EvaluateFloat(E->getArg(1), RHS, Info)) 13686 return false; 13687 Result.copySign(RHS); 13688 return true; 13689 } 13690 } 13691 } 13692 13693 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13694 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13695 ComplexValue CV; 13696 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13697 return false; 13698 Result = CV.FloatReal; 13699 return true; 13700 } 13701 13702 return Visit(E->getSubExpr()); 13703 } 13704 13705 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13706 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13707 ComplexValue CV; 13708 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13709 return false; 13710 Result = CV.FloatImag; 13711 return true; 13712 } 13713 13714 VisitIgnoredValue(E->getSubExpr()); 13715 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13716 Result = llvm::APFloat::getZero(Sem); 13717 return true; 13718 } 13719 13720 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13721 switch (E->getOpcode()) { 13722 default: return Error(E); 13723 case UO_Plus: 13724 return EvaluateFloat(E->getSubExpr(), Result, Info); 13725 case UO_Minus: 13726 // In C standard, WG14 N2478 F.3 p4 13727 // "the unary - raises no floating point exceptions, 13728 // even if the operand is signalling." 13729 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13730 return false; 13731 Result.changeSign(); 13732 return true; 13733 } 13734 } 13735 13736 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13737 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13738 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13739 13740 APFloat RHS(0.0); 13741 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13742 if (!LHSOK && !Info.noteFailure()) 13743 return false; 13744 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13745 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13746 } 13747 13748 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13749 Result = E->getValue(); 13750 return true; 13751 } 13752 13753 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13754 const Expr* SubExpr = E->getSubExpr(); 13755 13756 switch (E->getCastKind()) { 13757 default: 13758 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13759 13760 case CK_IntegralToFloating: { 13761 APSInt IntResult; 13762 const FPOptions FPO = E->getFPFeaturesInEffect( 13763 Info.Ctx.getLangOpts()); 13764 return EvaluateInteger(SubExpr, IntResult, Info) && 13765 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13766 IntResult, E->getType(), Result); 13767 } 13768 13769 case CK_FixedPointToFloating: { 13770 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13771 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13772 return false; 13773 Result = 13774 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13775 return true; 13776 } 13777 13778 case CK_FloatingCast: { 13779 if (!Visit(SubExpr)) 13780 return false; 13781 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13782 Result); 13783 } 13784 13785 case CK_FloatingComplexToReal: { 13786 ComplexValue V; 13787 if (!EvaluateComplex(SubExpr, V, Info)) 13788 return false; 13789 Result = V.getComplexFloatReal(); 13790 return true; 13791 } 13792 } 13793 } 13794 13795 //===----------------------------------------------------------------------===// 13796 // Complex Evaluation (for float and integer) 13797 //===----------------------------------------------------------------------===// 13798 13799 namespace { 13800 class ComplexExprEvaluator 13801 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13802 ComplexValue &Result; 13803 13804 public: 13805 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13806 : ExprEvaluatorBaseTy(info), Result(Result) {} 13807 13808 bool Success(const APValue &V, const Expr *e) { 13809 Result.setFrom(V); 13810 return true; 13811 } 13812 13813 bool ZeroInitialization(const Expr *E); 13814 13815 //===--------------------------------------------------------------------===// 13816 // Visitor Methods 13817 //===--------------------------------------------------------------------===// 13818 13819 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13820 bool VisitCastExpr(const CastExpr *E); 13821 bool VisitBinaryOperator(const BinaryOperator *E); 13822 bool VisitUnaryOperator(const UnaryOperator *E); 13823 bool VisitInitListExpr(const InitListExpr *E); 13824 bool VisitCallExpr(const CallExpr *E); 13825 }; 13826 } // end anonymous namespace 13827 13828 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13829 EvalInfo &Info) { 13830 assert(!E->isValueDependent()); 13831 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13832 return ComplexExprEvaluator(Info, Result).Visit(E); 13833 } 13834 13835 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13836 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13837 if (ElemTy->isRealFloatingType()) { 13838 Result.makeComplexFloat(); 13839 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13840 Result.FloatReal = Zero; 13841 Result.FloatImag = Zero; 13842 } else { 13843 Result.makeComplexInt(); 13844 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13845 Result.IntReal = Zero; 13846 Result.IntImag = Zero; 13847 } 13848 return true; 13849 } 13850 13851 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13852 const Expr* SubExpr = E->getSubExpr(); 13853 13854 if (SubExpr->getType()->isRealFloatingType()) { 13855 Result.makeComplexFloat(); 13856 APFloat &Imag = Result.FloatImag; 13857 if (!EvaluateFloat(SubExpr, Imag, Info)) 13858 return false; 13859 13860 Result.FloatReal = APFloat(Imag.getSemantics()); 13861 return true; 13862 } else { 13863 assert(SubExpr->getType()->isIntegerType() && 13864 "Unexpected imaginary literal."); 13865 13866 Result.makeComplexInt(); 13867 APSInt &Imag = Result.IntImag; 13868 if (!EvaluateInteger(SubExpr, Imag, Info)) 13869 return false; 13870 13871 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13872 return true; 13873 } 13874 } 13875 13876 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13877 13878 switch (E->getCastKind()) { 13879 case CK_BitCast: 13880 case CK_BaseToDerived: 13881 case CK_DerivedToBase: 13882 case CK_UncheckedDerivedToBase: 13883 case CK_Dynamic: 13884 case CK_ToUnion: 13885 case CK_ArrayToPointerDecay: 13886 case CK_FunctionToPointerDecay: 13887 case CK_NullToPointer: 13888 case CK_NullToMemberPointer: 13889 case CK_BaseToDerivedMemberPointer: 13890 case CK_DerivedToBaseMemberPointer: 13891 case CK_MemberPointerToBoolean: 13892 case CK_ReinterpretMemberPointer: 13893 case CK_ConstructorConversion: 13894 case CK_IntegralToPointer: 13895 case CK_PointerToIntegral: 13896 case CK_PointerToBoolean: 13897 case CK_ToVoid: 13898 case CK_VectorSplat: 13899 case CK_IntegralCast: 13900 case CK_BooleanToSignedIntegral: 13901 case CK_IntegralToBoolean: 13902 case CK_IntegralToFloating: 13903 case CK_FloatingToIntegral: 13904 case CK_FloatingToBoolean: 13905 case CK_FloatingCast: 13906 case CK_CPointerToObjCPointerCast: 13907 case CK_BlockPointerToObjCPointerCast: 13908 case CK_AnyPointerToBlockPointerCast: 13909 case CK_ObjCObjectLValueCast: 13910 case CK_FloatingComplexToReal: 13911 case CK_FloatingComplexToBoolean: 13912 case CK_IntegralComplexToReal: 13913 case CK_IntegralComplexToBoolean: 13914 case CK_ARCProduceObject: 13915 case CK_ARCConsumeObject: 13916 case CK_ARCReclaimReturnedObject: 13917 case CK_ARCExtendBlockObject: 13918 case CK_CopyAndAutoreleaseBlockObject: 13919 case CK_BuiltinFnToFnPtr: 13920 case CK_ZeroToOCLOpaqueType: 13921 case CK_NonAtomicToAtomic: 13922 case CK_AddressSpaceConversion: 13923 case CK_IntToOCLSampler: 13924 case CK_FloatingToFixedPoint: 13925 case CK_FixedPointToFloating: 13926 case CK_FixedPointCast: 13927 case CK_FixedPointToBoolean: 13928 case CK_FixedPointToIntegral: 13929 case CK_IntegralToFixedPoint: 13930 llvm_unreachable("invalid cast kind for complex value"); 13931 13932 case CK_LValueToRValue: 13933 case CK_AtomicToNonAtomic: 13934 case CK_NoOp: 13935 case CK_LValueToRValueBitCast: 13936 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13937 13938 case CK_Dependent: 13939 case CK_LValueBitCast: 13940 case CK_UserDefinedConversion: 13941 return Error(E); 13942 13943 case CK_FloatingRealToComplex: { 13944 APFloat &Real = Result.FloatReal; 13945 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13946 return false; 13947 13948 Result.makeComplexFloat(); 13949 Result.FloatImag = APFloat(Real.getSemantics()); 13950 return true; 13951 } 13952 13953 case CK_FloatingComplexCast: { 13954 if (!Visit(E->getSubExpr())) 13955 return false; 13956 13957 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13958 QualType From 13959 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13960 13961 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13962 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13963 } 13964 13965 case CK_FloatingComplexToIntegralComplex: { 13966 if (!Visit(E->getSubExpr())) 13967 return false; 13968 13969 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13970 QualType From 13971 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13972 Result.makeComplexInt(); 13973 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13974 To, Result.IntReal) && 13975 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13976 To, Result.IntImag); 13977 } 13978 13979 case CK_IntegralRealToComplex: { 13980 APSInt &Real = Result.IntReal; 13981 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13982 return false; 13983 13984 Result.makeComplexInt(); 13985 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13986 return true; 13987 } 13988 13989 case CK_IntegralComplexCast: { 13990 if (!Visit(E->getSubExpr())) 13991 return false; 13992 13993 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13994 QualType From 13995 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13996 13997 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13998 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13999 return true; 14000 } 14001 14002 case CK_IntegralComplexToFloatingComplex: { 14003 if (!Visit(E->getSubExpr())) 14004 return false; 14005 14006 const FPOptions FPO = E->getFPFeaturesInEffect( 14007 Info.Ctx.getLangOpts()); 14008 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14009 QualType From 14010 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14011 Result.makeComplexFloat(); 14012 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14013 To, Result.FloatReal) && 14014 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14015 To, Result.FloatImag); 14016 } 14017 } 14018 14019 llvm_unreachable("unknown cast resulting in complex value"); 14020 } 14021 14022 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14023 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14024 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14025 14026 // Track whether the LHS or RHS is real at the type system level. When this is 14027 // the case we can simplify our evaluation strategy. 14028 bool LHSReal = false, RHSReal = false; 14029 14030 bool LHSOK; 14031 if (E->getLHS()->getType()->isRealFloatingType()) { 14032 LHSReal = true; 14033 APFloat &Real = Result.FloatReal; 14034 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14035 if (LHSOK) { 14036 Result.makeComplexFloat(); 14037 Result.FloatImag = APFloat(Real.getSemantics()); 14038 } 14039 } else { 14040 LHSOK = Visit(E->getLHS()); 14041 } 14042 if (!LHSOK && !Info.noteFailure()) 14043 return false; 14044 14045 ComplexValue RHS; 14046 if (E->getRHS()->getType()->isRealFloatingType()) { 14047 RHSReal = true; 14048 APFloat &Real = RHS.FloatReal; 14049 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14050 return false; 14051 RHS.makeComplexFloat(); 14052 RHS.FloatImag = APFloat(Real.getSemantics()); 14053 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14054 return false; 14055 14056 assert(!(LHSReal && RHSReal) && 14057 "Cannot have both operands of a complex operation be real."); 14058 switch (E->getOpcode()) { 14059 default: return Error(E); 14060 case BO_Add: 14061 if (Result.isComplexFloat()) { 14062 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14063 APFloat::rmNearestTiesToEven); 14064 if (LHSReal) 14065 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14066 else if (!RHSReal) 14067 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14068 APFloat::rmNearestTiesToEven); 14069 } else { 14070 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14071 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14072 } 14073 break; 14074 case BO_Sub: 14075 if (Result.isComplexFloat()) { 14076 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14077 APFloat::rmNearestTiesToEven); 14078 if (LHSReal) { 14079 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14080 Result.getComplexFloatImag().changeSign(); 14081 } else if (!RHSReal) { 14082 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14083 APFloat::rmNearestTiesToEven); 14084 } 14085 } else { 14086 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14087 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14088 } 14089 break; 14090 case BO_Mul: 14091 if (Result.isComplexFloat()) { 14092 // This is an implementation of complex multiplication according to the 14093 // constraints laid out in C11 Annex G. The implementation uses the 14094 // following naming scheme: 14095 // (a + ib) * (c + id) 14096 ComplexValue LHS = Result; 14097 APFloat &A = LHS.getComplexFloatReal(); 14098 APFloat &B = LHS.getComplexFloatImag(); 14099 APFloat &C = RHS.getComplexFloatReal(); 14100 APFloat &D = RHS.getComplexFloatImag(); 14101 APFloat &ResR = Result.getComplexFloatReal(); 14102 APFloat &ResI = Result.getComplexFloatImag(); 14103 if (LHSReal) { 14104 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14105 ResR = A * C; 14106 ResI = A * D; 14107 } else if (RHSReal) { 14108 ResR = C * A; 14109 ResI = C * B; 14110 } else { 14111 // In the fully general case, we need to handle NaNs and infinities 14112 // robustly. 14113 APFloat AC = A * C; 14114 APFloat BD = B * D; 14115 APFloat AD = A * D; 14116 APFloat BC = B * C; 14117 ResR = AC - BD; 14118 ResI = AD + BC; 14119 if (ResR.isNaN() && ResI.isNaN()) { 14120 bool Recalc = false; 14121 if (A.isInfinity() || B.isInfinity()) { 14122 A = APFloat::copySign( 14123 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14124 B = APFloat::copySign( 14125 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14126 if (C.isNaN()) 14127 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14128 if (D.isNaN()) 14129 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14130 Recalc = true; 14131 } 14132 if (C.isInfinity() || D.isInfinity()) { 14133 C = APFloat::copySign( 14134 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14135 D = APFloat::copySign( 14136 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14137 if (A.isNaN()) 14138 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14139 if (B.isNaN()) 14140 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14141 Recalc = true; 14142 } 14143 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14144 AD.isInfinity() || BC.isInfinity())) { 14145 if (A.isNaN()) 14146 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14147 if (B.isNaN()) 14148 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14149 if (C.isNaN()) 14150 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14151 if (D.isNaN()) 14152 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14153 Recalc = true; 14154 } 14155 if (Recalc) { 14156 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14157 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14158 } 14159 } 14160 } 14161 } else { 14162 ComplexValue LHS = Result; 14163 Result.getComplexIntReal() = 14164 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14165 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14166 Result.getComplexIntImag() = 14167 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14168 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14169 } 14170 break; 14171 case BO_Div: 14172 if (Result.isComplexFloat()) { 14173 // This is an implementation of complex division according to the 14174 // constraints laid out in C11 Annex G. The implementation uses the 14175 // following naming scheme: 14176 // (a + ib) / (c + id) 14177 ComplexValue LHS = Result; 14178 APFloat &A = LHS.getComplexFloatReal(); 14179 APFloat &B = LHS.getComplexFloatImag(); 14180 APFloat &C = RHS.getComplexFloatReal(); 14181 APFloat &D = RHS.getComplexFloatImag(); 14182 APFloat &ResR = Result.getComplexFloatReal(); 14183 APFloat &ResI = Result.getComplexFloatImag(); 14184 if (RHSReal) { 14185 ResR = A / C; 14186 ResI = B / C; 14187 } else { 14188 if (LHSReal) { 14189 // No real optimizations we can do here, stub out with zero. 14190 B = APFloat::getZero(A.getSemantics()); 14191 } 14192 int DenomLogB = 0; 14193 APFloat MaxCD = maxnum(abs(C), abs(D)); 14194 if (MaxCD.isFinite()) { 14195 DenomLogB = ilogb(MaxCD); 14196 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14197 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14198 } 14199 APFloat Denom = C * C + D * D; 14200 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14201 APFloat::rmNearestTiesToEven); 14202 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14203 APFloat::rmNearestTiesToEven); 14204 if (ResR.isNaN() && ResI.isNaN()) { 14205 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14206 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14207 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14208 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14209 D.isFinite()) { 14210 A = APFloat::copySign( 14211 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14212 B = APFloat::copySign( 14213 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14214 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14215 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14216 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14217 C = APFloat::copySign( 14218 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14219 D = APFloat::copySign( 14220 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14221 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14222 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14223 } 14224 } 14225 } 14226 } else { 14227 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14228 return Error(E, diag::note_expr_divide_by_zero); 14229 14230 ComplexValue LHS = Result; 14231 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14232 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14233 Result.getComplexIntReal() = 14234 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14235 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14236 Result.getComplexIntImag() = 14237 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14238 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14239 } 14240 break; 14241 } 14242 14243 return true; 14244 } 14245 14246 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14247 // Get the operand value into 'Result'. 14248 if (!Visit(E->getSubExpr())) 14249 return false; 14250 14251 switch (E->getOpcode()) { 14252 default: 14253 return Error(E); 14254 case UO_Extension: 14255 return true; 14256 case UO_Plus: 14257 // The result is always just the subexpr. 14258 return true; 14259 case UO_Minus: 14260 if (Result.isComplexFloat()) { 14261 Result.getComplexFloatReal().changeSign(); 14262 Result.getComplexFloatImag().changeSign(); 14263 } 14264 else { 14265 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14266 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14267 } 14268 return true; 14269 case UO_Not: 14270 if (Result.isComplexFloat()) 14271 Result.getComplexFloatImag().changeSign(); 14272 else 14273 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14274 return true; 14275 } 14276 } 14277 14278 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14279 if (E->getNumInits() == 2) { 14280 if (E->getType()->isComplexType()) { 14281 Result.makeComplexFloat(); 14282 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14283 return false; 14284 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14285 return false; 14286 } else { 14287 Result.makeComplexInt(); 14288 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14289 return false; 14290 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14291 return false; 14292 } 14293 return true; 14294 } 14295 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14296 } 14297 14298 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14299 switch (E->getBuiltinCallee()) { 14300 case Builtin::BI__builtin_complex: 14301 Result.makeComplexFloat(); 14302 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14303 return false; 14304 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14305 return false; 14306 return true; 14307 14308 default: 14309 break; 14310 } 14311 14312 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14313 } 14314 14315 //===----------------------------------------------------------------------===// 14316 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14317 // implicit conversion. 14318 //===----------------------------------------------------------------------===// 14319 14320 namespace { 14321 class AtomicExprEvaluator : 14322 public ExprEvaluatorBase<AtomicExprEvaluator> { 14323 const LValue *This; 14324 APValue &Result; 14325 public: 14326 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14327 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14328 14329 bool Success(const APValue &V, const Expr *E) { 14330 Result = V; 14331 return true; 14332 } 14333 14334 bool ZeroInitialization(const Expr *E) { 14335 ImplicitValueInitExpr VIE( 14336 E->getType()->castAs<AtomicType>()->getValueType()); 14337 // For atomic-qualified class (and array) types in C++, initialize the 14338 // _Atomic-wrapped subobject directly, in-place. 14339 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14340 : Evaluate(Result, Info, &VIE); 14341 } 14342 14343 bool VisitCastExpr(const CastExpr *E) { 14344 switch (E->getCastKind()) { 14345 default: 14346 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14347 case CK_NonAtomicToAtomic: 14348 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14349 : Evaluate(Result, Info, E->getSubExpr()); 14350 } 14351 } 14352 }; 14353 } // end anonymous namespace 14354 14355 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14356 EvalInfo &Info) { 14357 assert(!E->isValueDependent()); 14358 assert(E->isRValue() && E->getType()->isAtomicType()); 14359 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14360 } 14361 14362 //===----------------------------------------------------------------------===// 14363 // Void expression evaluation, primarily for a cast to void on the LHS of a 14364 // comma operator 14365 //===----------------------------------------------------------------------===// 14366 14367 namespace { 14368 class VoidExprEvaluator 14369 : public ExprEvaluatorBase<VoidExprEvaluator> { 14370 public: 14371 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14372 14373 bool Success(const APValue &V, const Expr *e) { return true; } 14374 14375 bool ZeroInitialization(const Expr *E) { return true; } 14376 14377 bool VisitCastExpr(const CastExpr *E) { 14378 switch (E->getCastKind()) { 14379 default: 14380 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14381 case CK_ToVoid: 14382 VisitIgnoredValue(E->getSubExpr()); 14383 return true; 14384 } 14385 } 14386 14387 bool VisitCallExpr(const CallExpr *E) { 14388 switch (E->getBuiltinCallee()) { 14389 case Builtin::BI__assume: 14390 case Builtin::BI__builtin_assume: 14391 // The argument is not evaluated! 14392 return true; 14393 14394 case Builtin::BI__builtin_operator_delete: 14395 return HandleOperatorDeleteCall(Info, E); 14396 14397 default: 14398 break; 14399 } 14400 14401 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14402 } 14403 14404 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14405 }; 14406 } // end anonymous namespace 14407 14408 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14409 // We cannot speculatively evaluate a delete expression. 14410 if (Info.SpeculativeEvaluationDepth) 14411 return false; 14412 14413 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14414 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14415 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14416 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14417 return false; 14418 } 14419 14420 const Expr *Arg = E->getArgument(); 14421 14422 LValue Pointer; 14423 if (!EvaluatePointer(Arg, Pointer, Info)) 14424 return false; 14425 if (Pointer.Designator.Invalid) 14426 return false; 14427 14428 // Deleting a null pointer has no effect. 14429 if (Pointer.isNullPointer()) { 14430 // This is the only case where we need to produce an extension warning: 14431 // the only other way we can succeed is if we find a dynamic allocation, 14432 // and we will have warned when we allocated it in that case. 14433 if (!Info.getLangOpts().CPlusPlus20) 14434 Info.CCEDiag(E, diag::note_constexpr_new); 14435 return true; 14436 } 14437 14438 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14439 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14440 if (!Alloc) 14441 return false; 14442 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14443 14444 // For the non-array case, the designator must be empty if the static type 14445 // does not have a virtual destructor. 14446 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14447 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14448 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14449 << Arg->getType()->getPointeeType() << AllocType; 14450 return false; 14451 } 14452 14453 // For a class type with a virtual destructor, the selected operator delete 14454 // is the one looked up when building the destructor. 14455 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14456 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14457 if (VirtualDelete && 14458 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14459 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14460 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14461 return false; 14462 } 14463 } 14464 14465 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14466 (*Alloc)->Value, AllocType)) 14467 return false; 14468 14469 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14470 // The element was already erased. This means the destructor call also 14471 // deleted the object. 14472 // FIXME: This probably results in undefined behavior before we get this 14473 // far, and should be diagnosed elsewhere first. 14474 Info.FFDiag(E, diag::note_constexpr_double_delete); 14475 return false; 14476 } 14477 14478 return true; 14479 } 14480 14481 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14482 assert(!E->isValueDependent()); 14483 assert(E->isRValue() && E->getType()->isVoidType()); 14484 return VoidExprEvaluator(Info).Visit(E); 14485 } 14486 14487 //===----------------------------------------------------------------------===// 14488 // Top level Expr::EvaluateAsRValue method. 14489 //===----------------------------------------------------------------------===// 14490 14491 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14492 assert(!E->isValueDependent()); 14493 // In C, function designators are not lvalues, but we evaluate them as if they 14494 // are. 14495 QualType T = E->getType(); 14496 if (E->isGLValue() || T->isFunctionType()) { 14497 LValue LV; 14498 if (!EvaluateLValue(E, LV, Info)) 14499 return false; 14500 LV.moveInto(Result); 14501 } else if (T->isVectorType()) { 14502 if (!EvaluateVector(E, Result, Info)) 14503 return false; 14504 } else if (T->isIntegralOrEnumerationType()) { 14505 if (!IntExprEvaluator(Info, Result).Visit(E)) 14506 return false; 14507 } else if (T->hasPointerRepresentation()) { 14508 LValue LV; 14509 if (!EvaluatePointer(E, LV, Info)) 14510 return false; 14511 LV.moveInto(Result); 14512 } else if (T->isRealFloatingType()) { 14513 llvm::APFloat F(0.0); 14514 if (!EvaluateFloat(E, F, Info)) 14515 return false; 14516 Result = APValue(F); 14517 } else if (T->isAnyComplexType()) { 14518 ComplexValue C; 14519 if (!EvaluateComplex(E, C, Info)) 14520 return false; 14521 C.moveInto(Result); 14522 } else if (T->isFixedPointType()) { 14523 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14524 } else if (T->isMemberPointerType()) { 14525 MemberPtr P; 14526 if (!EvaluateMemberPointer(E, P, Info)) 14527 return false; 14528 P.moveInto(Result); 14529 return true; 14530 } else if (T->isArrayType()) { 14531 LValue LV; 14532 APValue &Value = 14533 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14534 if (!EvaluateArray(E, LV, Value, Info)) 14535 return false; 14536 Result = Value; 14537 } else if (T->isRecordType()) { 14538 LValue LV; 14539 APValue &Value = 14540 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14541 if (!EvaluateRecord(E, LV, Value, Info)) 14542 return false; 14543 Result = Value; 14544 } else if (T->isVoidType()) { 14545 if (!Info.getLangOpts().CPlusPlus11) 14546 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14547 << E->getType(); 14548 if (!EvaluateVoid(E, Info)) 14549 return false; 14550 } else if (T->isAtomicType()) { 14551 QualType Unqual = T.getAtomicUnqualifiedType(); 14552 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14553 LValue LV; 14554 APValue &Value = Info.CurrentCall->createTemporary( 14555 E, Unqual, ScopeKind::FullExpression, LV); 14556 if (!EvaluateAtomic(E, &LV, Value, Info)) 14557 return false; 14558 } else { 14559 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14560 return false; 14561 } 14562 } else if (Info.getLangOpts().CPlusPlus11) { 14563 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14564 return false; 14565 } else { 14566 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14567 return false; 14568 } 14569 14570 return true; 14571 } 14572 14573 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14574 /// cases, the in-place evaluation is essential, since later initializers for 14575 /// an object can indirectly refer to subobjects which were initialized earlier. 14576 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14577 const Expr *E, bool AllowNonLiteralTypes) { 14578 assert(!E->isValueDependent()); 14579 14580 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14581 return false; 14582 14583 if (E->isRValue()) { 14584 // Evaluate arrays and record types in-place, so that later initializers can 14585 // refer to earlier-initialized members of the object. 14586 QualType T = E->getType(); 14587 if (T->isArrayType()) 14588 return EvaluateArray(E, This, Result, Info); 14589 else if (T->isRecordType()) 14590 return EvaluateRecord(E, This, Result, Info); 14591 else if (T->isAtomicType()) { 14592 QualType Unqual = T.getAtomicUnqualifiedType(); 14593 if (Unqual->isArrayType() || Unqual->isRecordType()) 14594 return EvaluateAtomic(E, &This, Result, Info); 14595 } 14596 } 14597 14598 // For any other type, in-place evaluation is unimportant. 14599 return Evaluate(Result, Info, E); 14600 } 14601 14602 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14603 /// lvalue-to-rvalue cast if it is an lvalue. 14604 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14605 assert(!E->isValueDependent()); 14606 if (Info.EnableNewConstInterp) { 14607 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14608 return false; 14609 } else { 14610 if (E->getType().isNull()) 14611 return false; 14612 14613 if (!CheckLiteralType(Info, E)) 14614 return false; 14615 14616 if (!::Evaluate(Result, Info, E)) 14617 return false; 14618 14619 if (E->isGLValue()) { 14620 LValue LV; 14621 LV.setFrom(Info.Ctx, Result); 14622 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14623 return false; 14624 } 14625 } 14626 14627 // Check this core constant expression is a constant expression. 14628 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14629 ConstantExprKind::Normal) && 14630 CheckMemoryLeaks(Info); 14631 } 14632 14633 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14634 const ASTContext &Ctx, bool &IsConst) { 14635 // Fast-path evaluations of integer literals, since we sometimes see files 14636 // containing vast quantities of these. 14637 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14638 Result.Val = APValue(APSInt(L->getValue(), 14639 L->getType()->isUnsignedIntegerType())); 14640 IsConst = true; 14641 return true; 14642 } 14643 14644 // This case should be rare, but we need to check it before we check on 14645 // the type below. 14646 if (Exp->getType().isNull()) { 14647 IsConst = false; 14648 return true; 14649 } 14650 14651 // FIXME: Evaluating values of large array and record types can cause 14652 // performance problems. Only do so in C++11 for now. 14653 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14654 Exp->getType()->isRecordType()) && 14655 !Ctx.getLangOpts().CPlusPlus11) { 14656 IsConst = false; 14657 return true; 14658 } 14659 return false; 14660 } 14661 14662 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14663 Expr::SideEffectsKind SEK) { 14664 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14665 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14666 } 14667 14668 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14669 const ASTContext &Ctx, EvalInfo &Info) { 14670 assert(!E->isValueDependent()); 14671 bool IsConst; 14672 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14673 return IsConst; 14674 14675 return EvaluateAsRValue(Info, E, Result.Val); 14676 } 14677 14678 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14679 const ASTContext &Ctx, 14680 Expr::SideEffectsKind AllowSideEffects, 14681 EvalInfo &Info) { 14682 assert(!E->isValueDependent()); 14683 if (!E->getType()->isIntegralOrEnumerationType()) 14684 return false; 14685 14686 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14687 !ExprResult.Val.isInt() || 14688 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14689 return false; 14690 14691 return true; 14692 } 14693 14694 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14695 const ASTContext &Ctx, 14696 Expr::SideEffectsKind AllowSideEffects, 14697 EvalInfo &Info) { 14698 assert(!E->isValueDependent()); 14699 if (!E->getType()->isFixedPointType()) 14700 return false; 14701 14702 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14703 return false; 14704 14705 if (!ExprResult.Val.isFixedPoint() || 14706 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14707 return false; 14708 14709 return true; 14710 } 14711 14712 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14713 /// any crazy technique (that has nothing to do with language standards) that 14714 /// we want to. If this function returns true, it returns the folded constant 14715 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14716 /// will be applied to the result. 14717 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14718 bool InConstantContext) const { 14719 assert(!isValueDependent() && 14720 "Expression evaluator can't be called on a dependent expression."); 14721 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14722 Info.InConstantContext = InConstantContext; 14723 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14724 } 14725 14726 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14727 bool InConstantContext) const { 14728 assert(!isValueDependent() && 14729 "Expression evaluator can't be called on a dependent expression."); 14730 EvalResult Scratch; 14731 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14732 HandleConversionToBool(Scratch.Val, Result); 14733 } 14734 14735 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14736 SideEffectsKind AllowSideEffects, 14737 bool InConstantContext) const { 14738 assert(!isValueDependent() && 14739 "Expression evaluator can't be called on a dependent expression."); 14740 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14741 Info.InConstantContext = InConstantContext; 14742 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14743 } 14744 14745 bool Expr::EvaluateAsFixedPoint(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 ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14753 } 14754 14755 bool Expr::EvaluateAsFloat(APFloat &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 14761 if (!getType()->isRealFloatingType()) 14762 return false; 14763 14764 EvalResult ExprResult; 14765 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14766 !ExprResult.Val.isFloat() || 14767 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14768 return false; 14769 14770 Result = ExprResult.Val.getFloat(); 14771 return true; 14772 } 14773 14774 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14775 bool InConstantContext) const { 14776 assert(!isValueDependent() && 14777 "Expression evaluator can't be called on a dependent expression."); 14778 14779 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14780 Info.InConstantContext = InConstantContext; 14781 LValue LV; 14782 CheckedTemporaries CheckedTemps; 14783 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14784 Result.HasSideEffects || 14785 !CheckLValueConstantExpression(Info, getExprLoc(), 14786 Ctx.getLValueReferenceType(getType()), LV, 14787 ConstantExprKind::Normal, CheckedTemps)) 14788 return false; 14789 14790 LV.moveInto(Result.Val); 14791 return true; 14792 } 14793 14794 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14795 APValue DestroyedValue, QualType Type, 14796 SourceLocation Loc, Expr::EvalStatus &EStatus) { 14797 EvalInfo Info(Ctx, EStatus, EvalInfo::EM_ConstantExpression); 14798 Info.setEvaluatingDecl(Base, DestroyedValue, 14799 EvalInfo::EvaluatingDeclKind::Dtor); 14800 Info.InConstantContext = true; 14801 14802 LValue LVal; 14803 LVal.set(Base); 14804 14805 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14806 EStatus.HasSideEffects) 14807 return false; 14808 14809 if (!Info.discardCleanups()) 14810 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14811 14812 return true; 14813 } 14814 14815 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14816 ConstantExprKind Kind) const { 14817 assert(!isValueDependent() && 14818 "Expression evaluator can't be called on a dependent expression."); 14819 14820 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14821 EvalInfo Info(Ctx, Result, EM); 14822 Info.InConstantContext = true; 14823 14824 // The type of the object we're initializing is 'const T' for a class NTTP. 14825 QualType T = getType(); 14826 if (Kind == ConstantExprKind::ClassTemplateArgument) 14827 T.addConst(); 14828 14829 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14830 // represent the result of the evaluation. CheckConstantExpression ensures 14831 // this doesn't escape. 14832 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14833 APValue::LValueBase Base(&BaseMTE); 14834 14835 Info.setEvaluatingDecl(Base, Result.Val); 14836 LValue LVal; 14837 LVal.set(Base); 14838 14839 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14840 return false; 14841 14842 if (!Info.discardCleanups()) 14843 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14844 14845 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14846 Result.Val, Kind)) 14847 return false; 14848 if (!CheckMemoryLeaks(Info)) 14849 return false; 14850 14851 // If this is a class template argument, it's required to have constant 14852 // destruction too. 14853 if (Kind == ConstantExprKind::ClassTemplateArgument && 14854 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result) || 14855 Result.HasSideEffects)) { 14856 // FIXME: Prefix a note to indicate that the problem is lack of constant 14857 // destruction. 14858 return false; 14859 } 14860 14861 return true; 14862 } 14863 14864 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14865 const VarDecl *VD, 14866 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14867 bool IsConstantInitialization) const { 14868 assert(!isValueDependent() && 14869 "Expression evaluator can't be called on a dependent expression."); 14870 14871 // FIXME: Evaluating initializers for large array and record types can cause 14872 // performance problems. Only do so in C++11 for now. 14873 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14874 !Ctx.getLangOpts().CPlusPlus11) 14875 return false; 14876 14877 Expr::EvalStatus EStatus; 14878 EStatus.Diag = &Notes; 14879 14880 EvalInfo Info(Ctx, EStatus, 14881 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14882 ? EvalInfo::EM_ConstantExpression 14883 : EvalInfo::EM_ConstantFold); 14884 Info.setEvaluatingDecl(VD, Value); 14885 Info.InConstantContext = IsConstantInitialization; 14886 14887 SourceLocation DeclLoc = VD->getLocation(); 14888 QualType DeclTy = VD->getType(); 14889 14890 if (Info.EnableNewConstInterp) { 14891 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14892 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14893 return false; 14894 } else { 14895 LValue LVal; 14896 LVal.set(VD); 14897 14898 if (!EvaluateInPlace(Value, Info, LVal, this, 14899 /*AllowNonLiteralTypes=*/true) || 14900 EStatus.HasSideEffects) 14901 return false; 14902 14903 // At this point, any lifetime-extended temporaries are completely 14904 // initialized. 14905 Info.performLifetimeExtension(); 14906 14907 if (!Info.discardCleanups()) 14908 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14909 } 14910 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14911 ConstantExprKind::Normal) && 14912 CheckMemoryLeaks(Info); 14913 } 14914 14915 bool VarDecl::evaluateDestruction( 14916 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14917 Expr::EvalStatus EStatus; 14918 EStatus.Diag = &Notes; 14919 14920 // Make a copy of the value for the destructor to mutate, if we know it. 14921 // Otherwise, treat the value as default-initialized; if the destructor works 14922 // anyway, then the destruction is constant (and must be essentially empty). 14923 APValue DestroyedValue; 14924 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14925 DestroyedValue = *getEvaluatedValue(); 14926 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14927 return false; 14928 14929 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14930 getType(), getLocation(), EStatus) || 14931 EStatus.HasSideEffects) 14932 return false; 14933 14934 ensureEvaluatedStmt()->HasConstantDestruction = true; 14935 return true; 14936 } 14937 14938 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14939 /// constant folded, but discard the result. 14940 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14941 assert(!isValueDependent() && 14942 "Expression evaluator can't be called on a dependent expression."); 14943 14944 EvalResult Result; 14945 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14946 !hasUnacceptableSideEffect(Result, SEK); 14947 } 14948 14949 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14950 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14951 assert(!isValueDependent() && 14952 "Expression evaluator can't be called on a dependent expression."); 14953 14954 EvalResult EVResult; 14955 EVResult.Diag = Diag; 14956 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14957 Info.InConstantContext = true; 14958 14959 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14960 (void)Result; 14961 assert(Result && "Could not evaluate expression"); 14962 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14963 14964 return EVResult.Val.getInt(); 14965 } 14966 14967 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14968 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14969 assert(!isValueDependent() && 14970 "Expression evaluator can't be called on a dependent expression."); 14971 14972 EvalResult EVResult; 14973 EVResult.Diag = Diag; 14974 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14975 Info.InConstantContext = true; 14976 Info.CheckingForUndefinedBehavior = true; 14977 14978 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 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 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14987 assert(!isValueDependent() && 14988 "Expression evaluator can't be called on a dependent expression."); 14989 14990 bool IsConst; 14991 EvalResult EVResult; 14992 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14993 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14994 Info.CheckingForUndefinedBehavior = true; 14995 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14996 } 14997 } 14998 14999 bool Expr::EvalResult::isGlobalLValue() const { 15000 assert(Val.isLValue()); 15001 return IsGlobalLValue(Val.getLValueBase()); 15002 } 15003 15004 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15005 /// an integer constant expression. 15006 15007 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15008 /// comma, etc 15009 15010 // CheckICE - This function does the fundamental ICE checking: the returned 15011 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15012 // and a (possibly null) SourceLocation indicating the location of the problem. 15013 // 15014 // Note that to reduce code duplication, this helper does no evaluation 15015 // itself; the caller checks whether the expression is evaluatable, and 15016 // in the rare cases where CheckICE actually cares about the evaluated 15017 // value, it calls into Evaluate. 15018 15019 namespace { 15020 15021 enum ICEKind { 15022 /// This expression is an ICE. 15023 IK_ICE, 15024 /// This expression is not an ICE, but if it isn't evaluated, it's 15025 /// a legal subexpression for an ICE. This return value is used to handle 15026 /// the comma operator in C99 mode, and non-constant subexpressions. 15027 IK_ICEIfUnevaluated, 15028 /// This expression is not an ICE, and is not a legal subexpression for one. 15029 IK_NotICE 15030 }; 15031 15032 struct ICEDiag { 15033 ICEKind Kind; 15034 SourceLocation Loc; 15035 15036 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15037 }; 15038 15039 } 15040 15041 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15042 15043 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15044 15045 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15046 Expr::EvalResult EVResult; 15047 Expr::EvalStatus Status; 15048 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15049 15050 Info.InConstantContext = true; 15051 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15052 !EVResult.Val.isInt()) 15053 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15054 15055 return NoDiag(); 15056 } 15057 15058 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15059 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15060 if (!E->getType()->isIntegralOrEnumerationType()) 15061 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15062 15063 switch (E->getStmtClass()) { 15064 #define ABSTRACT_STMT(Node) 15065 #define STMT(Node, Base) case Expr::Node##Class: 15066 #define EXPR(Node, Base) 15067 #include "clang/AST/StmtNodes.inc" 15068 case Expr::PredefinedExprClass: 15069 case Expr::FloatingLiteralClass: 15070 case Expr::ImaginaryLiteralClass: 15071 case Expr::StringLiteralClass: 15072 case Expr::ArraySubscriptExprClass: 15073 case Expr::MatrixSubscriptExprClass: 15074 case Expr::OMPArraySectionExprClass: 15075 case Expr::OMPArrayShapingExprClass: 15076 case Expr::OMPIteratorExprClass: 15077 case Expr::MemberExprClass: 15078 case Expr::CompoundAssignOperatorClass: 15079 case Expr::CompoundLiteralExprClass: 15080 case Expr::ExtVectorElementExprClass: 15081 case Expr::DesignatedInitExprClass: 15082 case Expr::ArrayInitLoopExprClass: 15083 case Expr::ArrayInitIndexExprClass: 15084 case Expr::NoInitExprClass: 15085 case Expr::DesignatedInitUpdateExprClass: 15086 case Expr::ImplicitValueInitExprClass: 15087 case Expr::ParenListExprClass: 15088 case Expr::VAArgExprClass: 15089 case Expr::AddrLabelExprClass: 15090 case Expr::StmtExprClass: 15091 case Expr::CXXMemberCallExprClass: 15092 case Expr::CUDAKernelCallExprClass: 15093 case Expr::CXXAddrspaceCastExprClass: 15094 case Expr::CXXDynamicCastExprClass: 15095 case Expr::CXXTypeidExprClass: 15096 case Expr::CXXUuidofExprClass: 15097 case Expr::MSPropertyRefExprClass: 15098 case Expr::MSPropertySubscriptExprClass: 15099 case Expr::CXXNullPtrLiteralExprClass: 15100 case Expr::UserDefinedLiteralClass: 15101 case Expr::CXXThisExprClass: 15102 case Expr::CXXThrowExprClass: 15103 case Expr::CXXNewExprClass: 15104 case Expr::CXXDeleteExprClass: 15105 case Expr::CXXPseudoDestructorExprClass: 15106 case Expr::UnresolvedLookupExprClass: 15107 case Expr::TypoExprClass: 15108 case Expr::RecoveryExprClass: 15109 case Expr::DependentScopeDeclRefExprClass: 15110 case Expr::CXXConstructExprClass: 15111 case Expr::CXXInheritedCtorInitExprClass: 15112 case Expr::CXXStdInitializerListExprClass: 15113 case Expr::CXXBindTemporaryExprClass: 15114 case Expr::ExprWithCleanupsClass: 15115 case Expr::CXXTemporaryObjectExprClass: 15116 case Expr::CXXUnresolvedConstructExprClass: 15117 case Expr::CXXDependentScopeMemberExprClass: 15118 case Expr::UnresolvedMemberExprClass: 15119 case Expr::ObjCStringLiteralClass: 15120 case Expr::ObjCBoxedExprClass: 15121 case Expr::ObjCArrayLiteralClass: 15122 case Expr::ObjCDictionaryLiteralClass: 15123 case Expr::ObjCEncodeExprClass: 15124 case Expr::ObjCMessageExprClass: 15125 case Expr::ObjCSelectorExprClass: 15126 case Expr::ObjCProtocolExprClass: 15127 case Expr::ObjCIvarRefExprClass: 15128 case Expr::ObjCPropertyRefExprClass: 15129 case Expr::ObjCSubscriptRefExprClass: 15130 case Expr::ObjCIsaExprClass: 15131 case Expr::ObjCAvailabilityCheckExprClass: 15132 case Expr::ShuffleVectorExprClass: 15133 case Expr::ConvertVectorExprClass: 15134 case Expr::BlockExprClass: 15135 case Expr::NoStmtClass: 15136 case Expr::OpaqueValueExprClass: 15137 case Expr::PackExpansionExprClass: 15138 case Expr::SubstNonTypeTemplateParmPackExprClass: 15139 case Expr::FunctionParmPackExprClass: 15140 case Expr::AsTypeExprClass: 15141 case Expr::ObjCIndirectCopyRestoreExprClass: 15142 case Expr::MaterializeTemporaryExprClass: 15143 case Expr::PseudoObjectExprClass: 15144 case Expr::AtomicExprClass: 15145 case Expr::LambdaExprClass: 15146 case Expr::CXXFoldExprClass: 15147 case Expr::CoawaitExprClass: 15148 case Expr::DependentCoawaitExprClass: 15149 case Expr::CoyieldExprClass: 15150 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15151 15152 case Expr::InitListExprClass: { 15153 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15154 // form "T x = { a };" is equivalent to "T x = a;". 15155 // Unless we're initializing a reference, T is a scalar as it is known to be 15156 // of integral or enumeration type. 15157 if (E->isRValue()) 15158 if (cast<InitListExpr>(E)->getNumInits() == 1) 15159 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15160 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15161 } 15162 15163 case Expr::SizeOfPackExprClass: 15164 case Expr::GNUNullExprClass: 15165 case Expr::SourceLocExprClass: 15166 return NoDiag(); 15167 15168 case Expr::SubstNonTypeTemplateParmExprClass: 15169 return 15170 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15171 15172 case Expr::ConstantExprClass: 15173 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15174 15175 case Expr::ParenExprClass: 15176 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15177 case Expr::GenericSelectionExprClass: 15178 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15179 case Expr::IntegerLiteralClass: 15180 case Expr::FixedPointLiteralClass: 15181 case Expr::CharacterLiteralClass: 15182 case Expr::ObjCBoolLiteralExprClass: 15183 case Expr::CXXBoolLiteralExprClass: 15184 case Expr::CXXScalarValueInitExprClass: 15185 case Expr::TypeTraitExprClass: 15186 case Expr::ConceptSpecializationExprClass: 15187 case Expr::RequiresExprClass: 15188 case Expr::ArrayTypeTraitExprClass: 15189 case Expr::ExpressionTraitExprClass: 15190 case Expr::CXXNoexceptExprClass: 15191 return NoDiag(); 15192 case Expr::CallExprClass: 15193 case Expr::CXXOperatorCallExprClass: { 15194 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15195 // constant expressions, but they can never be ICEs because an ICE cannot 15196 // contain an operand of (pointer to) function type. 15197 const CallExpr *CE = cast<CallExpr>(E); 15198 if (CE->getBuiltinCallee()) 15199 return CheckEvalInICE(E, Ctx); 15200 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15201 } 15202 case Expr::CXXRewrittenBinaryOperatorClass: 15203 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15204 Ctx); 15205 case Expr::DeclRefExprClass: { 15206 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15207 if (isa<EnumConstantDecl>(D)) 15208 return NoDiag(); 15209 15210 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15211 // integer variables in constant expressions: 15212 // 15213 // C++ 7.1.5.1p2 15214 // A variable of non-volatile const-qualified integral or enumeration 15215 // type initialized by an ICE can be used in ICEs. 15216 // 15217 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15218 // that mode, use of reference variables should not be allowed. 15219 const VarDecl *VD = dyn_cast<VarDecl>(D); 15220 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15221 !VD->getType()->isReferenceType()) 15222 return NoDiag(); 15223 15224 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15225 } 15226 case Expr::UnaryOperatorClass: { 15227 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15228 switch (Exp->getOpcode()) { 15229 case UO_PostInc: 15230 case UO_PostDec: 15231 case UO_PreInc: 15232 case UO_PreDec: 15233 case UO_AddrOf: 15234 case UO_Deref: 15235 case UO_Coawait: 15236 // C99 6.6/3 allows increment and decrement within unevaluated 15237 // subexpressions of constant expressions, but they can never be ICEs 15238 // because an ICE cannot contain an lvalue operand. 15239 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15240 case UO_Extension: 15241 case UO_LNot: 15242 case UO_Plus: 15243 case UO_Minus: 15244 case UO_Not: 15245 case UO_Real: 15246 case UO_Imag: 15247 return CheckICE(Exp->getSubExpr(), Ctx); 15248 } 15249 llvm_unreachable("invalid unary operator class"); 15250 } 15251 case Expr::OffsetOfExprClass: { 15252 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15253 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15254 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15255 // compliance: we should warn earlier for offsetof expressions with 15256 // array subscripts that aren't ICEs, and if the array subscripts 15257 // are ICEs, the value of the offsetof must be an integer constant. 15258 return CheckEvalInICE(E, Ctx); 15259 } 15260 case Expr::UnaryExprOrTypeTraitExprClass: { 15261 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15262 if ((Exp->getKind() == UETT_SizeOf) && 15263 Exp->getTypeOfArgument()->isVariableArrayType()) 15264 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15265 return NoDiag(); 15266 } 15267 case Expr::BinaryOperatorClass: { 15268 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15269 switch (Exp->getOpcode()) { 15270 case BO_PtrMemD: 15271 case BO_PtrMemI: 15272 case BO_Assign: 15273 case BO_MulAssign: 15274 case BO_DivAssign: 15275 case BO_RemAssign: 15276 case BO_AddAssign: 15277 case BO_SubAssign: 15278 case BO_ShlAssign: 15279 case BO_ShrAssign: 15280 case BO_AndAssign: 15281 case BO_XorAssign: 15282 case BO_OrAssign: 15283 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15284 // constant expressions, but they can never be ICEs because an ICE cannot 15285 // contain an lvalue operand. 15286 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15287 15288 case BO_Mul: 15289 case BO_Div: 15290 case BO_Rem: 15291 case BO_Add: 15292 case BO_Sub: 15293 case BO_Shl: 15294 case BO_Shr: 15295 case BO_LT: 15296 case BO_GT: 15297 case BO_LE: 15298 case BO_GE: 15299 case BO_EQ: 15300 case BO_NE: 15301 case BO_And: 15302 case BO_Xor: 15303 case BO_Or: 15304 case BO_Comma: 15305 case BO_Cmp: { 15306 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15307 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15308 if (Exp->getOpcode() == BO_Div || 15309 Exp->getOpcode() == BO_Rem) { 15310 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15311 // we don't evaluate one. 15312 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15313 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15314 if (REval == 0) 15315 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15316 if (REval.isSigned() && REval.isAllOnesValue()) { 15317 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15318 if (LEval.isMinSignedValue()) 15319 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15320 } 15321 } 15322 } 15323 if (Exp->getOpcode() == BO_Comma) { 15324 if (Ctx.getLangOpts().C99) { 15325 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15326 // if it isn't evaluated. 15327 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15328 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15329 } else { 15330 // In both C89 and C++, commas in ICEs are illegal. 15331 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15332 } 15333 } 15334 return Worst(LHSResult, RHSResult); 15335 } 15336 case BO_LAnd: 15337 case BO_LOr: { 15338 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15339 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15340 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15341 // Rare case where the RHS has a comma "side-effect"; we need 15342 // to actually check the condition to see whether the side 15343 // with the comma is evaluated. 15344 if ((Exp->getOpcode() == BO_LAnd) != 15345 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15346 return RHSResult; 15347 return NoDiag(); 15348 } 15349 15350 return Worst(LHSResult, RHSResult); 15351 } 15352 } 15353 llvm_unreachable("invalid binary operator kind"); 15354 } 15355 case Expr::ImplicitCastExprClass: 15356 case Expr::CStyleCastExprClass: 15357 case Expr::CXXFunctionalCastExprClass: 15358 case Expr::CXXStaticCastExprClass: 15359 case Expr::CXXReinterpretCastExprClass: 15360 case Expr::CXXConstCastExprClass: 15361 case Expr::ObjCBridgedCastExprClass: { 15362 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15363 if (isa<ExplicitCastExpr>(E)) { 15364 if (const FloatingLiteral *FL 15365 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15366 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15367 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15368 APSInt IgnoredVal(DestWidth, !DestSigned); 15369 bool Ignored; 15370 // If the value does not fit in the destination type, the behavior is 15371 // undefined, so we are not required to treat it as a constant 15372 // expression. 15373 if (FL->getValue().convertToInteger(IgnoredVal, 15374 llvm::APFloat::rmTowardZero, 15375 &Ignored) & APFloat::opInvalidOp) 15376 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15377 return NoDiag(); 15378 } 15379 } 15380 switch (cast<CastExpr>(E)->getCastKind()) { 15381 case CK_LValueToRValue: 15382 case CK_AtomicToNonAtomic: 15383 case CK_NonAtomicToAtomic: 15384 case CK_NoOp: 15385 case CK_IntegralToBoolean: 15386 case CK_IntegralCast: 15387 return CheckICE(SubExpr, Ctx); 15388 default: 15389 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15390 } 15391 } 15392 case Expr::BinaryConditionalOperatorClass: { 15393 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15394 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15395 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15396 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15397 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15398 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15399 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15400 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15401 return FalseResult; 15402 } 15403 case Expr::ConditionalOperatorClass: { 15404 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15405 // If the condition (ignoring parens) is a __builtin_constant_p call, 15406 // then only the true side is actually considered in an integer constant 15407 // expression, and it is fully evaluated. This is an important GNU 15408 // extension. See GCC PR38377 for discussion. 15409 if (const CallExpr *CallCE 15410 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15411 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15412 return CheckEvalInICE(E, Ctx); 15413 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15414 if (CondResult.Kind == IK_NotICE) 15415 return CondResult; 15416 15417 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15418 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15419 15420 if (TrueResult.Kind == IK_NotICE) 15421 return TrueResult; 15422 if (FalseResult.Kind == IK_NotICE) 15423 return FalseResult; 15424 if (CondResult.Kind == IK_ICEIfUnevaluated) 15425 return CondResult; 15426 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15427 return NoDiag(); 15428 // Rare case where the diagnostics depend on which side is evaluated 15429 // Note that if we get here, CondResult is 0, and at least one of 15430 // TrueResult and FalseResult is non-zero. 15431 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15432 return FalseResult; 15433 return TrueResult; 15434 } 15435 case Expr::CXXDefaultArgExprClass: 15436 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15437 case Expr::CXXDefaultInitExprClass: 15438 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15439 case Expr::ChooseExprClass: { 15440 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15441 } 15442 case Expr::BuiltinBitCastExprClass: { 15443 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15444 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15445 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15446 } 15447 } 15448 15449 llvm_unreachable("Invalid StmtClass!"); 15450 } 15451 15452 /// Evaluate an expression as a C++11 integral constant expression. 15453 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15454 const Expr *E, 15455 llvm::APSInt *Value, 15456 SourceLocation *Loc) { 15457 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15458 if (Loc) *Loc = E->getExprLoc(); 15459 return false; 15460 } 15461 15462 APValue Result; 15463 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15464 return false; 15465 15466 if (!Result.isInt()) { 15467 if (Loc) *Loc = E->getExprLoc(); 15468 return false; 15469 } 15470 15471 if (Value) *Value = Result.getInt(); 15472 return true; 15473 } 15474 15475 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15476 SourceLocation *Loc) const { 15477 assert(!isValueDependent() && 15478 "Expression evaluator can't be called on a dependent expression."); 15479 15480 if (Ctx.getLangOpts().CPlusPlus11) 15481 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15482 15483 ICEDiag D = CheckICE(this, Ctx); 15484 if (D.Kind != IK_ICE) { 15485 if (Loc) *Loc = D.Loc; 15486 return false; 15487 } 15488 return true; 15489 } 15490 15491 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15492 SourceLocation *Loc, 15493 bool isEvaluated) const { 15494 assert(!isValueDependent() && 15495 "Expression evaluator can't be called on a dependent expression."); 15496 15497 APSInt Value; 15498 15499 if (Ctx.getLangOpts().CPlusPlus11) { 15500 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15501 return Value; 15502 return None; 15503 } 15504 15505 if (!isIntegerConstantExpr(Ctx, Loc)) 15506 return None; 15507 15508 // The only possible side-effects here are due to UB discovered in the 15509 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15510 // required to treat the expression as an ICE, so we produce the folded 15511 // value. 15512 EvalResult ExprResult; 15513 Expr::EvalStatus Status; 15514 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15515 Info.InConstantContext = true; 15516 15517 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15518 llvm_unreachable("ICE cannot be evaluated!"); 15519 15520 return ExprResult.Val.getInt(); 15521 } 15522 15523 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15524 assert(!isValueDependent() && 15525 "Expression evaluator can't be called on a dependent expression."); 15526 15527 return CheckICE(this, Ctx).Kind == IK_ICE; 15528 } 15529 15530 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15531 SourceLocation *Loc) const { 15532 assert(!isValueDependent() && 15533 "Expression evaluator can't be called on a dependent expression."); 15534 15535 // We support this checking in C++98 mode in order to diagnose compatibility 15536 // issues. 15537 assert(Ctx.getLangOpts().CPlusPlus); 15538 15539 // Build evaluation settings. 15540 Expr::EvalStatus Status; 15541 SmallVector<PartialDiagnosticAt, 8> Diags; 15542 Status.Diag = &Diags; 15543 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15544 15545 APValue Scratch; 15546 bool IsConstExpr = 15547 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15548 // FIXME: We don't produce a diagnostic for this, but the callers that 15549 // call us on arbitrary full-expressions should generally not care. 15550 Info.discardCleanups() && !Status.HasSideEffects; 15551 15552 if (!Diags.empty()) { 15553 IsConstExpr = false; 15554 if (Loc) *Loc = Diags[0].first; 15555 } else if (!IsConstExpr) { 15556 // FIXME: This shouldn't happen. 15557 if (Loc) *Loc = getExprLoc(); 15558 } 15559 15560 return IsConstExpr; 15561 } 15562 15563 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15564 const FunctionDecl *Callee, 15565 ArrayRef<const Expr*> Args, 15566 const Expr *This) const { 15567 assert(!isValueDependent() && 15568 "Expression evaluator can't be called on a dependent expression."); 15569 15570 Expr::EvalStatus Status; 15571 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15572 Info.InConstantContext = true; 15573 15574 LValue ThisVal; 15575 const LValue *ThisPtr = nullptr; 15576 if (This) { 15577 #ifndef NDEBUG 15578 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15579 assert(MD && "Don't provide `this` for non-methods."); 15580 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15581 #endif 15582 if (!This->isValueDependent() && 15583 EvaluateObjectArgument(Info, This, ThisVal) && 15584 !Info.EvalStatus.HasSideEffects) 15585 ThisPtr = &ThisVal; 15586 15587 // Ignore any side-effects from a failed evaluation. This is safe because 15588 // they can't interfere with any other argument evaluation. 15589 Info.EvalStatus.HasSideEffects = false; 15590 } 15591 15592 CallRef Call = Info.CurrentCall->createCall(Callee); 15593 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15594 I != E; ++I) { 15595 unsigned Idx = I - Args.begin(); 15596 if (Idx >= Callee->getNumParams()) 15597 break; 15598 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15599 if ((*I)->isValueDependent() || 15600 !EvaluateCallArg(PVD, *I, Call, Info) || 15601 Info.EvalStatus.HasSideEffects) { 15602 // If evaluation fails, throw away the argument entirely. 15603 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15604 *Slot = APValue(); 15605 } 15606 15607 // Ignore any side-effects from a failed evaluation. This is safe because 15608 // they can't interfere with any other argument evaluation. 15609 Info.EvalStatus.HasSideEffects = false; 15610 } 15611 15612 // Parameter cleanups happen in the caller and are not part of this 15613 // evaluation. 15614 Info.discardCleanups(); 15615 Info.EvalStatus.HasSideEffects = false; 15616 15617 // Build fake call to Callee. 15618 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15619 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15620 FullExpressionRAII Scope(Info); 15621 return Evaluate(Value, Info, this) && Scope.destroy() && 15622 !Info.EvalStatus.HasSideEffects; 15623 } 15624 15625 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15626 SmallVectorImpl< 15627 PartialDiagnosticAt> &Diags) { 15628 // FIXME: It would be useful to check constexpr function templates, but at the 15629 // moment the constant expression evaluator cannot cope with the non-rigorous 15630 // ASTs which we build for dependent expressions. 15631 if (FD->isDependentContext()) 15632 return true; 15633 15634 Expr::EvalStatus Status; 15635 Status.Diag = &Diags; 15636 15637 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15638 Info.InConstantContext = true; 15639 Info.CheckingPotentialConstantExpression = true; 15640 15641 // The constexpr VM attempts to compile all methods to bytecode here. 15642 if (Info.EnableNewConstInterp) { 15643 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15644 return Diags.empty(); 15645 } 15646 15647 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15648 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15649 15650 // Fabricate an arbitrary expression on the stack and pretend that it 15651 // is a temporary being used as the 'this' pointer. 15652 LValue This; 15653 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15654 This.set({&VIE, Info.CurrentCall->Index}); 15655 15656 ArrayRef<const Expr*> Args; 15657 15658 APValue Scratch; 15659 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15660 // Evaluate the call as a constant initializer, to allow the construction 15661 // of objects of non-literal types. 15662 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15663 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15664 } else { 15665 SourceLocation Loc = FD->getLocation(); 15666 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15667 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15668 } 15669 15670 return Diags.empty(); 15671 } 15672 15673 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15674 const FunctionDecl *FD, 15675 SmallVectorImpl< 15676 PartialDiagnosticAt> &Diags) { 15677 assert(!E->isValueDependent() && 15678 "Expression evaluator can't be called on a dependent expression."); 15679 15680 Expr::EvalStatus Status; 15681 Status.Diag = &Diags; 15682 15683 EvalInfo Info(FD->getASTContext(), Status, 15684 EvalInfo::EM_ConstantExpressionUnevaluated); 15685 Info.InConstantContext = true; 15686 Info.CheckingPotentialConstantExpression = true; 15687 15688 // Fabricate a call stack frame to give the arguments a plausible cover story. 15689 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15690 15691 APValue ResultScratch; 15692 Evaluate(ResultScratch, Info, E); 15693 return Diags.empty(); 15694 } 15695 15696 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15697 unsigned Type) const { 15698 if (!getType()->isPointerType()) 15699 return false; 15700 15701 Expr::EvalStatus Status; 15702 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15703 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15704 } 15705