1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isPRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 112 return DirectCallee->getAttr<AllocSizeAttr>(); 113 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 114 return IndirectCallee->getAttr<AllocSizeAttr>(); 115 return nullptr; 116 } 117 118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 119 /// This will look through a single cast. 120 /// 121 /// Returns null if we couldn't unwrap a function with alloc_size. 122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 123 if (!E->getType()->isPointerType()) 124 return nullptr; 125 126 E = E->IgnoreParens(); 127 // If we're doing a variable assignment from e.g. malloc(N), there will 128 // probably be a cast of some kind. In exotic cases, we might also see a 129 // top-level ExprWithCleanups. Ignore them either way. 130 if (const auto *FE = dyn_cast<FullExpr>(E)) 131 E = FE->getSubExpr()->IgnoreParens(); 132 133 if (const auto *Cast = dyn_cast<CastExpr>(E)) 134 E = Cast->getSubExpr()->IgnoreParens(); 135 136 if (const auto *CE = dyn_cast<CallExpr>(E)) 137 return getAllocSizeAttr(CE) ? CE : nullptr; 138 return nullptr; 139 } 140 141 /// Determines whether or not the given Base contains a call to a function 142 /// with the alloc_size attribute. 143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 144 const auto *E = Base.dyn_cast<const Expr *>(); 145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 146 } 147 148 /// Determines whether the given kind of constant expression is only ever 149 /// used for name mangling. If so, it's permitted to reference things that we 150 /// can't generate code for (in particular, dllimported functions). 151 static bool isForManglingOnly(ConstantExprKind Kind) { 152 switch (Kind) { 153 case ConstantExprKind::Normal: 154 case ConstantExprKind::ClassTemplateArgument: 155 case ConstantExprKind::ImmediateInvocation: 156 // Note that non-type template arguments of class type are emitted as 157 // template parameter objects. 158 return false; 159 160 case ConstantExprKind::NonClassTemplateArgument: 161 return true; 162 } 163 llvm_unreachable("unknown ConstantExprKind"); 164 } 165 166 static bool isTemplateArgument(ConstantExprKind Kind) { 167 switch (Kind) { 168 case ConstantExprKind::Normal: 169 case ConstantExprKind::ImmediateInvocation: 170 return false; 171 172 case ConstantExprKind::ClassTemplateArgument: 173 case ConstantExprKind::NonClassTemplateArgument: 174 return true; 175 } 176 llvm_unreachable("unknown ConstantExprKind"); 177 } 178 179 /// The bound to claim that an array of unknown bound has. 180 /// The value in MostDerivedArraySize is undefined in this case. So, set it 181 /// to an arbitrary value that's likely to loudly break things if it's used. 182 static const uint64_t AssumedSizeForUnsizedArray = 183 std::numeric_limits<uint64_t>::max() / 2; 184 185 /// Determines if an LValue with the given LValueBase will have an unsized 186 /// array in its designator. 187 /// Find the path length and type of the most-derived subobject in the given 188 /// path, and find the size of the containing array, if any. 189 static unsigned 190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 191 ArrayRef<APValue::LValuePathEntry> Path, 192 uint64_t &ArraySize, QualType &Type, bool &IsArray, 193 bool &FirstEntryIsUnsizedArray) { 194 // This only accepts LValueBases from APValues, and APValues don't support 195 // arrays that lack size info. 196 assert(!isBaseAnAllocSizeCall(Base) && 197 "Unsized arrays shouldn't appear here"); 198 unsigned MostDerivedLength = 0; 199 Type = getType(Base); 200 201 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 202 if (Type->isArrayType()) { 203 const ArrayType *AT = Ctx.getAsArrayType(Type); 204 Type = AT->getElementType(); 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 209 ArraySize = CAT->getSize().getZExtValue(); 210 } else { 211 assert(I == 0 && "unexpected unsized array designator"); 212 FirstEntryIsUnsizedArray = true; 213 ArraySize = AssumedSizeForUnsizedArray; 214 } 215 } else if (Type->isAnyComplexType()) { 216 const ComplexType *CT = Type->castAs<ComplexType>(); 217 Type = CT->getElementType(); 218 ArraySize = 2; 219 MostDerivedLength = I + 1; 220 IsArray = true; 221 } else if (const FieldDecl *FD = getAsField(Path[I])) { 222 Type = FD->getType(); 223 ArraySize = 0; 224 MostDerivedLength = I + 1; 225 IsArray = false; 226 } else { 227 // Path[I] describes a base class. 228 ArraySize = 0; 229 IsArray = false; 230 } 231 } 232 return MostDerivedLength; 233 } 234 235 /// A path from a glvalue to a subobject of that glvalue. 236 struct SubobjectDesignator { 237 /// True if the subobject was named in a manner not supported by C++11. Such 238 /// lvalues can still be folded, but they are not core constant expressions 239 /// and we cannot perform lvalue-to-rvalue conversions on them. 240 unsigned Invalid : 1; 241 242 /// Is this a pointer one past the end of an object? 243 unsigned IsOnePastTheEnd : 1; 244 245 /// Indicator of whether the first entry is an unsized array. 246 unsigned FirstEntryIsAnUnsizedArray : 1; 247 248 /// Indicator of whether the most-derived object is an array element. 249 unsigned MostDerivedIsArrayElement : 1; 250 251 /// The length of the path to the most-derived object of which this is a 252 /// subobject. 253 unsigned MostDerivedPathLength : 28; 254 255 /// The size of the array of which the most-derived object is an element. 256 /// This will always be 0 if the most-derived object is not an array 257 /// element. 0 is not an indicator of whether or not the most-derived object 258 /// is an array, however, because 0-length arrays are allowed. 259 /// 260 /// If the current array is an unsized array, the value of this is 261 /// undefined. 262 uint64_t MostDerivedArraySize; 263 264 /// The type of the most derived object referred to by this address. 265 QualType MostDerivedType; 266 267 typedef APValue::LValuePathEntry PathEntry; 268 269 /// The entries on the path from the glvalue to the designated subobject. 270 SmallVector<PathEntry, 8> Entries; 271 272 SubobjectDesignator() : Invalid(true) {} 273 274 explicit SubobjectDesignator(QualType T) 275 : Invalid(false), IsOnePastTheEnd(false), 276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 277 MostDerivedPathLength(0), MostDerivedArraySize(0), 278 MostDerivedType(T) {} 279 280 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 283 MostDerivedPathLength(0), MostDerivedArraySize(0) { 284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 285 if (!Invalid) { 286 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 287 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 289 if (V.getLValueBase()) { 290 bool IsArray = false; 291 bool FirstIsUnsizedArray = false; 292 MostDerivedPathLength = findMostDerivedSubobject( 293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 294 MostDerivedType, IsArray, FirstIsUnsizedArray); 295 MostDerivedIsArrayElement = IsArray; 296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 297 } 298 } 299 } 300 301 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 302 unsigned NewLength) { 303 if (Invalid) 304 return; 305 306 assert(Base && "cannot truncate path for null pointer"); 307 assert(NewLength <= Entries.size() && "not a truncation"); 308 309 if (NewLength == Entries.size()) 310 return; 311 Entries.resize(NewLength); 312 313 bool IsArray = false; 314 bool FirstIsUnsizedArray = false; 315 MostDerivedPathLength = findMostDerivedSubobject( 316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 317 FirstIsUnsizedArray); 318 MostDerivedIsArrayElement = IsArray; 319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 320 } 321 322 void setInvalid() { 323 Invalid = true; 324 Entries.clear(); 325 } 326 327 /// Determine whether the most derived subobject is an array without a 328 /// known bound. 329 bool isMostDerivedAnUnsizedArray() const { 330 assert(!Invalid && "Calling this makes no sense on invalid designators"); 331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 332 } 333 334 /// Determine what the most derived array's size is. Results in an assertion 335 /// failure if the most derived array lacks a size. 336 uint64_t getMostDerivedArraySize() const { 337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 338 return MostDerivedArraySize; 339 } 340 341 /// Determine whether this is a one-past-the-end pointer. 342 bool isOnePastTheEnd() const { 343 assert(!Invalid); 344 if (IsOnePastTheEnd) 345 return true; 346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 348 MostDerivedArraySize) 349 return true; 350 return false; 351 } 352 353 /// Get the range of valid index adjustments in the form 354 /// {maximum value that can be subtracted from this pointer, 355 /// maximum value that can be added to this pointer} 356 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 357 if (Invalid || isMostDerivedAnUnsizedArray()) 358 return {0, 0}; 359 360 // [expr.add]p4: For the purposes of these operators, a pointer to a 361 // nonarray object behaves the same as a pointer to the first element of 362 // an array of length one with the type of the object as its element type. 363 bool IsArray = MostDerivedPathLength == Entries.size() && 364 MostDerivedIsArrayElement; 365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 366 : (uint64_t)IsOnePastTheEnd; 367 uint64_t ArraySize = 368 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 369 return {ArrayIndex, ArraySize - ArrayIndex}; 370 } 371 372 /// Check that this refers to a valid subobject. 373 bool isValidSubobject() const { 374 if (Invalid) 375 return false; 376 return !isOnePastTheEnd(); 377 } 378 /// Check that this refers to a valid subobject, and if not, produce a 379 /// relevant diagnostic and set the designator as invalid. 380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 381 382 /// Get the type of the designated object. 383 QualType getType(ASTContext &Ctx) const { 384 assert(!Invalid && "invalid designator has no subobject type"); 385 return MostDerivedPathLength == Entries.size() 386 ? MostDerivedType 387 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 388 } 389 390 /// Update this designator to refer to the first element within this array. 391 void addArrayUnchecked(const ConstantArrayType *CAT) { 392 Entries.push_back(PathEntry::ArrayIndex(0)); 393 394 // This is a most-derived object. 395 MostDerivedType = CAT->getElementType(); 396 MostDerivedIsArrayElement = true; 397 MostDerivedArraySize = CAT->getSize().getZExtValue(); 398 MostDerivedPathLength = Entries.size(); 399 } 400 /// Update this designator to refer to the first element within the array of 401 /// elements of type T. This is an array of unknown size. 402 void addUnsizedArrayUnchecked(QualType ElemTy) { 403 Entries.push_back(PathEntry::ArrayIndex(0)); 404 405 MostDerivedType = ElemTy; 406 MostDerivedIsArrayElement = true; 407 // The value in MostDerivedArraySize is undefined in this case. So, set it 408 // to an arbitrary value that's likely to loudly break things if it's 409 // used. 410 MostDerivedArraySize = AssumedSizeForUnsizedArray; 411 MostDerivedPathLength = Entries.size(); 412 } 413 /// Update this designator to refer to the given base or member of this 414 /// object. 415 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 417 418 // If this isn't a base class, it's a new most-derived object. 419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 420 MostDerivedType = FD->getType(); 421 MostDerivedIsArrayElement = false; 422 MostDerivedArraySize = 0; 423 MostDerivedPathLength = Entries.size(); 424 } 425 } 426 /// Update this designator to refer to the given complex component. 427 void addComplexUnchecked(QualType EltTy, bool Imag) { 428 Entries.push_back(PathEntry::ArrayIndex(Imag)); 429 430 // This is technically a most-derived object, though in practice this 431 // is unlikely to matter. 432 MostDerivedType = EltTy; 433 MostDerivedIsArrayElement = true; 434 MostDerivedArraySize = 2; 435 MostDerivedPathLength = Entries.size(); 436 } 437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 439 const APSInt &N); 440 /// Add N to the address of this subobject. 441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 442 if (Invalid || !N) return; 443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 444 if (isMostDerivedAnUnsizedArray()) { 445 diagnoseUnsizedArrayPointerArithmetic(Info, E); 446 // Can't verify -- trust that the user is doing the right thing (or if 447 // not, trust that the caller will catch the bad behavior). 448 // FIXME: Should we reject if this overflows, at least? 449 Entries.back() = PathEntry::ArrayIndex( 450 Entries.back().getAsArrayIndex() + TruncatedN); 451 return; 452 } 453 454 // [expr.add]p4: For the purposes of these operators, a pointer to a 455 // nonarray object behaves the same as a pointer to the first element of 456 // an array of length one with the type of the object as its element type. 457 bool IsArray = MostDerivedPathLength == Entries.size() && 458 MostDerivedIsArrayElement; 459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 460 : (uint64_t)IsOnePastTheEnd; 461 uint64_t ArraySize = 462 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 463 464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 465 // Calculate the actual index in a wide enough type, so we can include 466 // it in the note. 467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 468 (llvm::APInt&)N += ArrayIndex; 469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 470 diagnosePointerArithmetic(Info, E, N); 471 setInvalid(); 472 return; 473 } 474 475 ArrayIndex += TruncatedN; 476 assert(ArrayIndex <= ArraySize && 477 "bounds check succeeded for out-of-bounds index"); 478 479 if (IsArray) 480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 481 else 482 IsOnePastTheEnd = (ArrayIndex != 0); 483 } 484 }; 485 486 /// A scope at the end of which an object can need to be destroyed. 487 enum class ScopeKind { 488 Block, 489 FullExpression, 490 Call 491 }; 492 493 /// A reference to a particular call and its arguments. 494 struct CallRef { 495 CallRef() : OrigCallee(), CallIndex(0), Version() {} 496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 498 499 explicit operator bool() const { return OrigCallee; } 500 501 /// Get the parameter that the caller initialized, corresponding to the 502 /// given parameter in the callee. 503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 505 : PVD; 506 } 507 508 /// The callee at the point where the arguments were evaluated. This might 509 /// be different from the actual callee (a different redeclaration, or a 510 /// virtual override), but this function's parameters are the ones that 511 /// appear in the parameter map. 512 const FunctionDecl *OrigCallee; 513 /// The call index of the frame that holds the argument values. 514 unsigned CallIndex; 515 /// The version of the parameters corresponding to this call. 516 unsigned Version; 517 }; 518 519 /// A stack frame in the constexpr call stack. 520 class CallStackFrame : public interp::Frame { 521 public: 522 EvalInfo &Info; 523 524 /// Parent - The caller of this stack frame. 525 CallStackFrame *Caller; 526 527 /// Callee - The function which was called. 528 const FunctionDecl *Callee; 529 530 /// This - The binding for the this pointer in this call, if any. 531 const LValue *This; 532 533 /// Information on how to find the arguments to this call. Our arguments 534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 535 /// key and this value as the version. 536 CallRef Arguments; 537 538 /// Source location information about the default argument or default 539 /// initializer expression we're evaluating, if any. 540 CurrentSourceLocExprScope CurSourceLocExprScope; 541 542 // Note that we intentionally use std::map here so that references to 543 // values are stable. 544 typedef std::pair<const void *, unsigned> MapKeyTy; 545 typedef std::map<MapKeyTy, APValue> MapTy; 546 /// Temporaries - Temporary lvalues materialized within this stack frame. 547 MapTy Temporaries; 548 549 /// CallLoc - The location of the call expression for this call. 550 SourceLocation CallLoc; 551 552 /// Index - The call index of this call. 553 unsigned Index; 554 555 /// The stack of integers for tracking version numbers for temporaries. 556 SmallVector<unsigned, 2> TempVersionStack = {1}; 557 unsigned CurTempVersion = TempVersionStack.back(); 558 559 unsigned getTempVersion() const { return TempVersionStack.back(); } 560 561 void pushTempVersion() { 562 TempVersionStack.push_back(++CurTempVersion); 563 } 564 565 void popTempVersion() { 566 TempVersionStack.pop_back(); 567 } 568 569 CallRef createCall(const FunctionDecl *Callee) { 570 return {Callee, Index, ++CurTempVersion}; 571 } 572 573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 574 // on the overall stack usage of deeply-recursing constexpr evaluations. 575 // (We should cache this map rather than recomputing it repeatedly.) 576 // But let's try this and see how it goes; we can look into caching the map 577 // as a later change. 578 579 /// LambdaCaptureFields - Mapping from captured variables/this to 580 /// corresponding data members in the closure class. 581 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 582 FieldDecl *LambdaThisCaptureField; 583 584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 585 const FunctionDecl *Callee, const LValue *This, 586 CallRef Arguments); 587 ~CallStackFrame(); 588 589 // Return the temporary for Key whose version number is Version. 590 APValue *getTemporary(const void *Key, unsigned Version) { 591 MapKeyTy KV(Key, Version); 592 auto LB = Temporaries.lower_bound(KV); 593 if (LB != Temporaries.end() && LB->first == KV) 594 return &LB->second; 595 // Pair (Key,Version) wasn't found in the map. Check that no elements 596 // in the map have 'Key' as their key. 597 assert((LB == Temporaries.end() || LB->first.first != Key) && 598 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 599 "Element with key 'Key' found in map"); 600 return nullptr; 601 } 602 603 // Return the current temporary for Key in the map. 604 APValue *getCurrentTemporary(const void *Key) { 605 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 606 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 607 return &std::prev(UB)->second; 608 return nullptr; 609 } 610 611 // Return the version number of the current temporary for Key. 612 unsigned getCurrentTemporaryVersion(const void *Key) const { 613 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 614 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 615 return std::prev(UB)->first.second; 616 return 0; 617 } 618 619 /// Allocate storage for an object of type T in this stack frame. 620 /// Populates LV with a handle to the created object. Key identifies 621 /// the temporary within the stack frame, and must not be reused without 622 /// bumping the temporary version number. 623 template<typename KeyT> 624 APValue &createTemporary(const KeyT *Key, QualType T, 625 ScopeKind Scope, LValue &LV); 626 627 /// Allocate storage for a parameter of a function call made in this frame. 628 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 629 630 void describe(llvm::raw_ostream &OS) override; 631 632 Frame *getCaller() const override { return Caller; } 633 SourceLocation getCallLocation() const override { return CallLoc; } 634 const FunctionDecl *getCallee() const override { return Callee; } 635 636 bool isStdFunction() const { 637 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 638 if (DC->isStdNamespace()) 639 return true; 640 return false; 641 } 642 643 private: 644 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 645 ScopeKind Scope); 646 }; 647 648 /// Temporarily override 'this'. 649 class ThisOverrideRAII { 650 public: 651 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 652 : Frame(Frame), OldThis(Frame.This) { 653 if (Enable) 654 Frame.This = NewThis; 655 } 656 ~ThisOverrideRAII() { 657 Frame.This = OldThis; 658 } 659 private: 660 CallStackFrame &Frame; 661 const LValue *OldThis; 662 }; 663 } 664 665 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 666 const LValue &This, QualType ThisType); 667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 668 APValue::LValueBase LVBase, APValue &Value, 669 QualType T); 670 671 namespace { 672 /// A cleanup, and a flag indicating whether it is lifetime-extended. 673 class Cleanup { 674 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 675 APValue::LValueBase Base; 676 QualType T; 677 678 public: 679 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 680 ScopeKind Scope) 681 : Value(Val, Scope), Base(Base), T(T) {} 682 683 /// Determine whether this cleanup should be performed at the end of the 684 /// given kind of scope. 685 bool isDestroyedAtEndOf(ScopeKind K) const { 686 return (int)Value.getInt() >= (int)K; 687 } 688 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 689 if (RunDestructors) { 690 SourceLocation Loc; 691 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 692 Loc = VD->getLocation(); 693 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 694 Loc = E->getExprLoc(); 695 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 696 } 697 *Value.getPointer() = APValue(); 698 return true; 699 } 700 701 bool hasSideEffect() { 702 return T.isDestructedType(); 703 } 704 }; 705 706 /// A reference to an object whose construction we are currently evaluating. 707 struct ObjectUnderConstruction { 708 APValue::LValueBase Base; 709 ArrayRef<APValue::LValuePathEntry> Path; 710 friend bool operator==(const ObjectUnderConstruction &LHS, 711 const ObjectUnderConstruction &RHS) { 712 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 713 } 714 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 715 return llvm::hash_combine(Obj.Base, Obj.Path); 716 } 717 }; 718 enum class ConstructionPhase { 719 None, 720 Bases, 721 AfterBases, 722 AfterFields, 723 Destroying, 724 DestroyingBases 725 }; 726 } 727 728 namespace llvm { 729 template<> struct DenseMapInfo<ObjectUnderConstruction> { 730 using Base = DenseMapInfo<APValue::LValueBase>; 731 static ObjectUnderConstruction getEmptyKey() { 732 return {Base::getEmptyKey(), {}}; } 733 static ObjectUnderConstruction getTombstoneKey() { 734 return {Base::getTombstoneKey(), {}}; 735 } 736 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 737 return hash_value(Object); 738 } 739 static bool isEqual(const ObjectUnderConstruction &LHS, 740 const ObjectUnderConstruction &RHS) { 741 return LHS == RHS; 742 } 743 }; 744 } 745 746 namespace { 747 /// A dynamically-allocated heap object. 748 struct DynAlloc { 749 /// The value of this heap-allocated object. 750 APValue Value; 751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 752 /// or a CallExpr (the latter is for direct calls to operator new inside 753 /// std::allocator<T>::allocate). 754 const Expr *AllocExpr = nullptr; 755 756 enum Kind { 757 New, 758 ArrayNew, 759 StdAllocator 760 }; 761 762 /// Get the kind of the allocation. This must match between allocation 763 /// and deallocation. 764 Kind getKind() const { 765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 766 return NE->isArray() ? ArrayNew : New; 767 assert(isa<CallExpr>(AllocExpr)); 768 return StdAllocator; 769 } 770 }; 771 772 struct DynAllocOrder { 773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 774 return L.getIndex() < R.getIndex(); 775 } 776 }; 777 778 /// EvalInfo - This is a private struct used by the evaluator to capture 779 /// information about a subexpression as it is folded. It retains information 780 /// about the AST context, but also maintains information about the folded 781 /// expression. 782 /// 783 /// If an expression could be evaluated, it is still possible it is not a C 784 /// "integer constant expression" or constant expression. If not, this struct 785 /// captures information about how and why not. 786 /// 787 /// One bit of information passed *into* the request for constant folding 788 /// indicates whether the subexpression is "evaluated" or not according to C 789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 790 /// evaluate the expression regardless of what the RHS is, but C only allows 791 /// certain things in certain situations. 792 class EvalInfo : public interp::State { 793 public: 794 ASTContext &Ctx; 795 796 /// EvalStatus - Contains information about the evaluation. 797 Expr::EvalStatus &EvalStatus; 798 799 /// CurrentCall - The top of the constexpr call stack. 800 CallStackFrame *CurrentCall; 801 802 /// CallStackDepth - The number of calls in the call stack right now. 803 unsigned CallStackDepth; 804 805 /// NextCallIndex - The next call index to assign. 806 unsigned NextCallIndex; 807 808 /// StepsLeft - The remaining number of evaluation steps we're permitted 809 /// to perform. This is essentially a limit for the number of statements 810 /// we will evaluate. 811 unsigned StepsLeft; 812 813 /// Enable the experimental new constant interpreter. If an expression is 814 /// not supported by the interpreter, an error is triggered. 815 bool EnableNewConstInterp; 816 817 /// BottomFrame - The frame in which evaluation started. This must be 818 /// initialized after CurrentCall and CallStackDepth. 819 CallStackFrame BottomFrame; 820 821 /// A stack of values whose lifetimes end at the end of some surrounding 822 /// evaluation frame. 823 llvm::SmallVector<Cleanup, 16> CleanupStack; 824 825 /// EvaluatingDecl - This is the declaration whose initializer is being 826 /// evaluated, if any. 827 APValue::LValueBase EvaluatingDecl; 828 829 enum class EvaluatingDeclKind { 830 None, 831 /// We're evaluating the construction of EvaluatingDecl. 832 Ctor, 833 /// We're evaluating the destruction of EvaluatingDecl. 834 Dtor, 835 }; 836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 837 838 /// EvaluatingDeclValue - This is the value being constructed for the 839 /// declaration whose initializer is being evaluated, if any. 840 APValue *EvaluatingDeclValue; 841 842 /// Set of objects that are currently being constructed. 843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 844 ObjectsUnderConstruction; 845 846 /// Current heap allocations, along with the location where each was 847 /// allocated. We use std::map here because we need stable addresses 848 /// for the stored APValues. 849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 850 851 /// The number of heap allocations performed so far in this evaluation. 852 unsigned NumHeapAllocs = 0; 853 854 struct EvaluatingConstructorRAII { 855 EvalInfo &EI; 856 ObjectUnderConstruction Object; 857 bool DidInsert; 858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 859 bool HasBases) 860 : EI(EI), Object(Object) { 861 DidInsert = 862 EI.ObjectsUnderConstruction 863 .insert({Object, HasBases ? ConstructionPhase::Bases 864 : ConstructionPhase::AfterBases}) 865 .second; 866 } 867 void finishedConstructingBases() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 869 } 870 void finishedConstructingFields() { 871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 872 } 873 ~EvaluatingConstructorRAII() { 874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 875 } 876 }; 877 878 struct EvaluatingDestructorRAII { 879 EvalInfo &EI; 880 ObjectUnderConstruction Object; 881 bool DidInsert; 882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 883 : EI(EI), Object(Object) { 884 DidInsert = EI.ObjectsUnderConstruction 885 .insert({Object, ConstructionPhase::Destroying}) 886 .second; 887 } 888 void startedDestroyingBases() { 889 EI.ObjectsUnderConstruction[Object] = 890 ConstructionPhase::DestroyingBases; 891 } 892 ~EvaluatingDestructorRAII() { 893 if (DidInsert) 894 EI.ObjectsUnderConstruction.erase(Object); 895 } 896 }; 897 898 ConstructionPhase 899 isEvaluatingCtorDtor(APValue::LValueBase Base, 900 ArrayRef<APValue::LValuePathEntry> Path) { 901 return ObjectsUnderConstruction.lookup({Base, Path}); 902 } 903 904 /// If we're currently speculatively evaluating, the outermost call stack 905 /// depth at which we can mutate state, otherwise 0. 906 unsigned SpeculativeEvaluationDepth = 0; 907 908 /// The current array initialization index, if we're performing array 909 /// initialization. 910 uint64_t ArrayInitIndex = -1; 911 912 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 913 /// notes attached to it will also be stored, otherwise they will not be. 914 bool HasActiveDiagnostic; 915 916 /// Have we emitted a diagnostic explaining why we couldn't constant 917 /// fold (not just why it's not strictly a constant expression)? 918 bool HasFoldFailureDiagnostic; 919 920 /// Whether or not we're in a context where the front end requires a 921 /// constant value. 922 bool InConstantContext; 923 924 /// Whether we're checking that an expression is a potential constant 925 /// expression. If so, do not fail on constructs that could become constant 926 /// later on (such as a use of an undefined global). 927 bool CheckingPotentialConstantExpression = false; 928 929 /// Whether we're checking for an expression that has undefined behavior. 930 /// If so, we will produce warnings if we encounter an operation that is 931 /// always undefined. 932 /// 933 /// Note that we still need to evaluate the expression normally when this 934 /// is set; this is used when evaluating ICEs in C. 935 bool CheckingForUndefinedBehavior = false; 936 937 enum EvaluationMode { 938 /// Evaluate as a constant expression. Stop if we find that the expression 939 /// is not a constant expression. 940 EM_ConstantExpression, 941 942 /// Evaluate as a constant expression. Stop if we find that the expression 943 /// is not a constant expression. Some expressions can be retried in the 944 /// optimizer if we don't constant fold them here, but in an unevaluated 945 /// context we try to fold them immediately since the optimizer never 946 /// gets a chance to look at it. 947 EM_ConstantExpressionUnevaluated, 948 949 /// Fold the expression to a constant. Stop if we hit a side-effect that 950 /// we can't model. 951 EM_ConstantFold, 952 953 /// Evaluate in any way we know how. Don't worry about side-effects that 954 /// can't be modeled. 955 EM_IgnoreSideEffects, 956 } EvalMode; 957 958 /// Are we checking whether the expression is a potential constant 959 /// expression? 960 bool checkingPotentialConstantExpression() const override { 961 return CheckingPotentialConstantExpression; 962 } 963 964 /// Are we checking an expression for overflow? 965 // FIXME: We should check for any kind of undefined or suspicious behavior 966 // in such constructs, not just overflow. 967 bool checkingForUndefinedBehavior() const override { 968 return CheckingForUndefinedBehavior; 969 } 970 971 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 972 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 973 CallStackDepth(0), NextCallIndex(1), 974 StepsLeft(C.getLangOpts().ConstexprStepLimit), 975 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 976 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 977 EvaluatingDecl((const ValueDecl *)nullptr), 978 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 979 HasFoldFailureDiagnostic(false), InConstantContext(false), 980 EvalMode(Mode) {} 981 982 ~EvalInfo() { 983 discardCleanups(); 984 } 985 986 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 987 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 988 EvaluatingDecl = Base; 989 IsEvaluatingDecl = EDK; 990 EvaluatingDeclValue = &Value; 991 } 992 993 bool CheckCallLimit(SourceLocation Loc) { 994 // Don't perform any constexpr calls (other than the call we're checking) 995 // when checking a potential constant expression. 996 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 997 return false; 998 if (NextCallIndex == 0) { 999 // NextCallIndex has wrapped around. 1000 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1001 return false; 1002 } 1003 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1004 return true; 1005 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1006 << getLangOpts().ConstexprCallDepth; 1007 return false; 1008 } 1009 1010 std::pair<CallStackFrame *, unsigned> 1011 getCallFrameAndDepth(unsigned CallIndex) { 1012 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1013 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1014 // be null in this loop. 1015 unsigned Depth = CallStackDepth; 1016 CallStackFrame *Frame = CurrentCall; 1017 while (Frame->Index > CallIndex) { 1018 Frame = Frame->Caller; 1019 --Depth; 1020 } 1021 if (Frame->Index == CallIndex) 1022 return {Frame, Depth}; 1023 return {nullptr, 0}; 1024 } 1025 1026 bool nextStep(const Stmt *S) { 1027 if (!StepsLeft) { 1028 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1029 return false; 1030 } 1031 --StepsLeft; 1032 return true; 1033 } 1034 1035 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1036 1037 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1038 Optional<DynAlloc*> Result; 1039 auto It = HeapAllocs.find(DA); 1040 if (It != HeapAllocs.end()) 1041 Result = &It->second; 1042 return Result; 1043 } 1044 1045 /// Get the allocated storage for the given parameter of the given call. 1046 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1047 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1048 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1049 : nullptr; 1050 } 1051 1052 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1053 struct StdAllocatorCaller { 1054 unsigned FrameIndex; 1055 QualType ElemType; 1056 explicit operator bool() const { return FrameIndex != 0; }; 1057 }; 1058 1059 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1060 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1061 Call = Call->Caller) { 1062 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1063 if (!MD) 1064 continue; 1065 const IdentifierInfo *FnII = MD->getIdentifier(); 1066 if (!FnII || !FnII->isStr(FnName)) 1067 continue; 1068 1069 const auto *CTSD = 1070 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1071 if (!CTSD) 1072 continue; 1073 1074 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1075 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1076 if (CTSD->isInStdNamespace() && ClassII && 1077 ClassII->isStr("allocator") && TAL.size() >= 1 && 1078 TAL[0].getKind() == TemplateArgument::Type) 1079 return {Call->Index, TAL[0].getAsType()}; 1080 } 1081 1082 return {}; 1083 } 1084 1085 void performLifetimeExtension() { 1086 // Disable the cleanups for lifetime-extended temporaries. 1087 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1088 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1089 }); 1090 } 1091 1092 /// Throw away any remaining cleanups at the end of evaluation. If any 1093 /// cleanups would have had a side-effect, note that as an unmodeled 1094 /// side-effect and return false. Otherwise, return true. 1095 bool discardCleanups() { 1096 for (Cleanup &C : CleanupStack) { 1097 if (C.hasSideEffect() && !noteSideEffect()) { 1098 CleanupStack.clear(); 1099 return false; 1100 } 1101 } 1102 CleanupStack.clear(); 1103 return true; 1104 } 1105 1106 private: 1107 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1108 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1109 1110 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1111 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1112 1113 void setFoldFailureDiagnostic(bool Flag) override { 1114 HasFoldFailureDiagnostic = Flag; 1115 } 1116 1117 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1118 1119 ASTContext &getCtx() const override { return Ctx; } 1120 1121 // If we have a prior diagnostic, it will be noting that the expression 1122 // isn't a constant expression. This diagnostic is more important, 1123 // unless we require this evaluation to produce a constant expression. 1124 // 1125 // FIXME: We might want to show both diagnostics to the user in 1126 // EM_ConstantFold mode. 1127 bool hasPriorDiagnostic() override { 1128 if (!EvalStatus.Diag->empty()) { 1129 switch (EvalMode) { 1130 case EM_ConstantFold: 1131 case EM_IgnoreSideEffects: 1132 if (!HasFoldFailureDiagnostic) 1133 break; 1134 // We've already failed to fold something. Keep that diagnostic. 1135 LLVM_FALLTHROUGH; 1136 case EM_ConstantExpression: 1137 case EM_ConstantExpressionUnevaluated: 1138 setActiveDiagnostic(false); 1139 return true; 1140 } 1141 } 1142 return false; 1143 } 1144 1145 unsigned getCallStackDepth() override { return CallStackDepth; } 1146 1147 public: 1148 /// Should we continue evaluation after encountering a side-effect that we 1149 /// couldn't model? 1150 bool keepEvaluatingAfterSideEffect() { 1151 switch (EvalMode) { 1152 case EM_IgnoreSideEffects: 1153 return true; 1154 1155 case EM_ConstantExpression: 1156 case EM_ConstantExpressionUnevaluated: 1157 case EM_ConstantFold: 1158 // By default, assume any side effect might be valid in some other 1159 // evaluation of this expression from a different context. 1160 return checkingPotentialConstantExpression() || 1161 checkingForUndefinedBehavior(); 1162 } 1163 llvm_unreachable("Missed EvalMode case"); 1164 } 1165 1166 /// Note that we have had a side-effect, and determine whether we should 1167 /// keep evaluating. 1168 bool noteSideEffect() { 1169 EvalStatus.HasSideEffects = true; 1170 return keepEvaluatingAfterSideEffect(); 1171 } 1172 1173 /// Should we continue evaluation after encountering undefined behavior? 1174 bool keepEvaluatingAfterUndefinedBehavior() { 1175 switch (EvalMode) { 1176 case EM_IgnoreSideEffects: 1177 case EM_ConstantFold: 1178 return true; 1179 1180 case EM_ConstantExpression: 1181 case EM_ConstantExpressionUnevaluated: 1182 return checkingForUndefinedBehavior(); 1183 } 1184 llvm_unreachable("Missed EvalMode case"); 1185 } 1186 1187 /// Note that we hit something that was technically undefined behavior, but 1188 /// that we can evaluate past it (such as signed overflow or floating-point 1189 /// division by zero.) 1190 bool noteUndefinedBehavior() override { 1191 EvalStatus.HasUndefinedBehavior = true; 1192 return keepEvaluatingAfterUndefinedBehavior(); 1193 } 1194 1195 /// Should we continue evaluation as much as possible after encountering a 1196 /// construct which can't be reduced to a value? 1197 bool keepEvaluatingAfterFailure() const override { 1198 if (!StepsLeft) 1199 return false; 1200 1201 switch (EvalMode) { 1202 case EM_ConstantExpression: 1203 case EM_ConstantExpressionUnevaluated: 1204 case EM_ConstantFold: 1205 case EM_IgnoreSideEffects: 1206 return checkingPotentialConstantExpression() || 1207 checkingForUndefinedBehavior(); 1208 } 1209 llvm_unreachable("Missed EvalMode case"); 1210 } 1211 1212 /// Notes that we failed to evaluate an expression that other expressions 1213 /// directly depend on, and determine if we should keep evaluating. This 1214 /// should only be called if we actually intend to keep evaluating. 1215 /// 1216 /// Call noteSideEffect() instead if we may be able to ignore the value that 1217 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1218 /// 1219 /// (Foo(), 1) // use noteSideEffect 1220 /// (Foo() || true) // use noteSideEffect 1221 /// Foo() + 1 // use noteFailure 1222 LLVM_NODISCARD bool noteFailure() { 1223 // Failure when evaluating some expression often means there is some 1224 // subexpression whose evaluation was skipped. Therefore, (because we 1225 // don't track whether we skipped an expression when unwinding after an 1226 // evaluation failure) every evaluation failure that bubbles up from a 1227 // subexpression implies that a side-effect has potentially happened. We 1228 // skip setting the HasSideEffects flag to true until we decide to 1229 // continue evaluating after that point, which happens here. 1230 bool KeepGoing = keepEvaluatingAfterFailure(); 1231 EvalStatus.HasSideEffects |= KeepGoing; 1232 return KeepGoing; 1233 } 1234 1235 class ArrayInitLoopIndex { 1236 EvalInfo &Info; 1237 uint64_t OuterIndex; 1238 1239 public: 1240 ArrayInitLoopIndex(EvalInfo &Info) 1241 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1242 Info.ArrayInitIndex = 0; 1243 } 1244 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1245 1246 operator uint64_t&() { return Info.ArrayInitIndex; } 1247 }; 1248 }; 1249 1250 /// Object used to treat all foldable expressions as constant expressions. 1251 struct FoldConstant { 1252 EvalInfo &Info; 1253 bool Enabled; 1254 bool HadNoPriorDiags; 1255 EvalInfo::EvaluationMode OldMode; 1256 1257 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1258 : Info(Info), 1259 Enabled(Enabled), 1260 HadNoPriorDiags(Info.EvalStatus.Diag && 1261 Info.EvalStatus.Diag->empty() && 1262 !Info.EvalStatus.HasSideEffects), 1263 OldMode(Info.EvalMode) { 1264 if (Enabled) 1265 Info.EvalMode = EvalInfo::EM_ConstantFold; 1266 } 1267 void keepDiagnostics() { Enabled = false; } 1268 ~FoldConstant() { 1269 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1270 !Info.EvalStatus.HasSideEffects) 1271 Info.EvalStatus.Diag->clear(); 1272 Info.EvalMode = OldMode; 1273 } 1274 }; 1275 1276 /// RAII object used to set the current evaluation mode to ignore 1277 /// side-effects. 1278 struct IgnoreSideEffectsRAII { 1279 EvalInfo &Info; 1280 EvalInfo::EvaluationMode OldMode; 1281 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1282 : Info(Info), OldMode(Info.EvalMode) { 1283 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1284 } 1285 1286 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1287 }; 1288 1289 /// RAII object used to optionally suppress diagnostics and side-effects from 1290 /// a speculative evaluation. 1291 class SpeculativeEvaluationRAII { 1292 EvalInfo *Info = nullptr; 1293 Expr::EvalStatus OldStatus; 1294 unsigned OldSpeculativeEvaluationDepth; 1295 1296 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1297 Info = Other.Info; 1298 OldStatus = Other.OldStatus; 1299 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1300 Other.Info = nullptr; 1301 } 1302 1303 void maybeRestoreState() { 1304 if (!Info) 1305 return; 1306 1307 Info->EvalStatus = OldStatus; 1308 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1309 } 1310 1311 public: 1312 SpeculativeEvaluationRAII() = default; 1313 1314 SpeculativeEvaluationRAII( 1315 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1316 : Info(&Info), OldStatus(Info.EvalStatus), 1317 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1318 Info.EvalStatus.Diag = NewDiag; 1319 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1320 } 1321 1322 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1323 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1324 moveFromAndCancel(std::move(Other)); 1325 } 1326 1327 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1328 maybeRestoreState(); 1329 moveFromAndCancel(std::move(Other)); 1330 return *this; 1331 } 1332 1333 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1334 }; 1335 1336 /// RAII object wrapping a full-expression or block scope, and handling 1337 /// the ending of the lifetime of temporaries created within it. 1338 template<ScopeKind Kind> 1339 class ScopeRAII { 1340 EvalInfo &Info; 1341 unsigned OldStackSize; 1342 public: 1343 ScopeRAII(EvalInfo &Info) 1344 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1345 // Push a new temporary version. This is needed to distinguish between 1346 // temporaries created in different iterations of a loop. 1347 Info.CurrentCall->pushTempVersion(); 1348 } 1349 bool destroy(bool RunDestructors = true) { 1350 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1351 OldStackSize = -1U; 1352 return OK; 1353 } 1354 ~ScopeRAII() { 1355 if (OldStackSize != -1U) 1356 destroy(false); 1357 // Body moved to a static method to encourage the compiler to inline away 1358 // instances of this class. 1359 Info.CurrentCall->popTempVersion(); 1360 } 1361 private: 1362 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1363 unsigned OldStackSize) { 1364 assert(OldStackSize <= Info.CleanupStack.size() && 1365 "running cleanups out of order?"); 1366 1367 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1368 // for a full-expression scope. 1369 bool Success = true; 1370 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1371 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1372 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1373 Success = false; 1374 break; 1375 } 1376 } 1377 } 1378 1379 // Compact any retained cleanups. 1380 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1381 if (Kind != ScopeKind::Block) 1382 NewEnd = 1383 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1384 return C.isDestroyedAtEndOf(Kind); 1385 }); 1386 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1387 return Success; 1388 } 1389 }; 1390 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1391 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1392 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1393 } 1394 1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1396 CheckSubobjectKind CSK) { 1397 if (Invalid) 1398 return false; 1399 if (isOnePastTheEnd()) { 1400 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1401 << CSK; 1402 setInvalid(); 1403 return false; 1404 } 1405 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1406 // must actually be at least one array element; even a VLA cannot have a 1407 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1408 return true; 1409 } 1410 1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1412 const Expr *E) { 1413 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1414 // Do not set the designator as invalid: we can represent this situation, 1415 // and correct handling of __builtin_object_size requires us to do so. 1416 } 1417 1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1419 const Expr *E, 1420 const APSInt &N) { 1421 // If we're complaining, we must be able to statically determine the size of 1422 // the most derived array. 1423 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1424 Info.CCEDiag(E, diag::note_constexpr_array_index) 1425 << N << /*array*/ 0 1426 << static_cast<unsigned>(getMostDerivedArraySize()); 1427 else 1428 Info.CCEDiag(E, diag::note_constexpr_array_index) 1429 << N << /*non-array*/ 1; 1430 setInvalid(); 1431 } 1432 1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1434 const FunctionDecl *Callee, const LValue *This, 1435 CallRef Call) 1436 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1437 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1438 Info.CurrentCall = this; 1439 ++Info.CallStackDepth; 1440 } 1441 1442 CallStackFrame::~CallStackFrame() { 1443 assert(Info.CurrentCall == this && "calls retired out of order"); 1444 --Info.CallStackDepth; 1445 Info.CurrentCall = Caller; 1446 } 1447 1448 static bool isRead(AccessKinds AK) { 1449 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1450 } 1451 1452 static bool isModification(AccessKinds AK) { 1453 switch (AK) { 1454 case AK_Read: 1455 case AK_ReadObjectRepresentation: 1456 case AK_MemberCall: 1457 case AK_DynamicCast: 1458 case AK_TypeId: 1459 return false; 1460 case AK_Assign: 1461 case AK_Increment: 1462 case AK_Decrement: 1463 case AK_Construct: 1464 case AK_Destroy: 1465 return true; 1466 } 1467 llvm_unreachable("unknown access kind"); 1468 } 1469 1470 static bool isAnyAccess(AccessKinds AK) { 1471 return isRead(AK) || isModification(AK); 1472 } 1473 1474 /// Is this an access per the C++ definition? 1475 static bool isFormalAccess(AccessKinds AK) { 1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1477 } 1478 1479 /// Is this kind of axcess valid on an indeterminate object value? 1480 static bool isValidIndeterminateAccess(AccessKinds AK) { 1481 switch (AK) { 1482 case AK_Read: 1483 case AK_Increment: 1484 case AK_Decrement: 1485 // These need the object's value. 1486 return false; 1487 1488 case AK_ReadObjectRepresentation: 1489 case AK_Assign: 1490 case AK_Construct: 1491 case AK_Destroy: 1492 // Construction and destruction don't need the value. 1493 return true; 1494 1495 case AK_MemberCall: 1496 case AK_DynamicCast: 1497 case AK_TypeId: 1498 // These aren't really meaningful on scalars. 1499 return true; 1500 } 1501 llvm_unreachable("unknown access kind"); 1502 } 1503 1504 namespace { 1505 struct ComplexValue { 1506 private: 1507 bool IsInt; 1508 1509 public: 1510 APSInt IntReal, IntImag; 1511 APFloat FloatReal, FloatImag; 1512 1513 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1514 1515 void makeComplexFloat() { IsInt = false; } 1516 bool isComplexFloat() const { return !IsInt; } 1517 APFloat &getComplexFloatReal() { return FloatReal; } 1518 APFloat &getComplexFloatImag() { return FloatImag; } 1519 1520 void makeComplexInt() { IsInt = true; } 1521 bool isComplexInt() const { return IsInt; } 1522 APSInt &getComplexIntReal() { return IntReal; } 1523 APSInt &getComplexIntImag() { return IntImag; } 1524 1525 void moveInto(APValue &v) const { 1526 if (isComplexFloat()) 1527 v = APValue(FloatReal, FloatImag); 1528 else 1529 v = APValue(IntReal, IntImag); 1530 } 1531 void setFrom(const APValue &v) { 1532 assert(v.isComplexFloat() || v.isComplexInt()); 1533 if (v.isComplexFloat()) { 1534 makeComplexFloat(); 1535 FloatReal = v.getComplexFloatReal(); 1536 FloatImag = v.getComplexFloatImag(); 1537 } else { 1538 makeComplexInt(); 1539 IntReal = v.getComplexIntReal(); 1540 IntImag = v.getComplexIntImag(); 1541 } 1542 } 1543 }; 1544 1545 struct LValue { 1546 APValue::LValueBase Base; 1547 CharUnits Offset; 1548 SubobjectDesignator Designator; 1549 bool IsNullPtr : 1; 1550 bool InvalidBase : 1; 1551 1552 const APValue::LValueBase getLValueBase() const { return Base; } 1553 CharUnits &getLValueOffset() { return Offset; } 1554 const CharUnits &getLValueOffset() const { return Offset; } 1555 SubobjectDesignator &getLValueDesignator() { return Designator; } 1556 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1557 bool isNullPointer() const { return IsNullPtr;} 1558 1559 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1560 unsigned getLValueVersion() const { return Base.getVersion(); } 1561 1562 void moveInto(APValue &V) const { 1563 if (Designator.Invalid) 1564 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1565 else { 1566 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1567 V = APValue(Base, Offset, Designator.Entries, 1568 Designator.IsOnePastTheEnd, IsNullPtr); 1569 } 1570 } 1571 void setFrom(ASTContext &Ctx, const APValue &V) { 1572 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1573 Base = V.getLValueBase(); 1574 Offset = V.getLValueOffset(); 1575 InvalidBase = false; 1576 Designator = SubobjectDesignator(Ctx, V); 1577 IsNullPtr = V.isNullPointer(); 1578 } 1579 1580 void set(APValue::LValueBase B, bool BInvalid = false) { 1581 #ifndef NDEBUG 1582 // We only allow a few types of invalid bases. Enforce that here. 1583 if (BInvalid) { 1584 const auto *E = B.get<const Expr *>(); 1585 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1586 "Unexpected type of invalid base"); 1587 } 1588 #endif 1589 1590 Base = B; 1591 Offset = CharUnits::fromQuantity(0); 1592 InvalidBase = BInvalid; 1593 Designator = SubobjectDesignator(getType(B)); 1594 IsNullPtr = false; 1595 } 1596 1597 void setNull(ASTContext &Ctx, QualType PointerTy) { 1598 Base = (const ValueDecl *)nullptr; 1599 Offset = 1600 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1601 InvalidBase = false; 1602 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1603 IsNullPtr = true; 1604 } 1605 1606 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1607 set(B, true); 1608 } 1609 1610 std::string toString(ASTContext &Ctx, QualType T) const { 1611 APValue Printable; 1612 moveInto(Printable); 1613 return Printable.getAsString(Ctx, T); 1614 } 1615 1616 private: 1617 // Check that this LValue is not based on a null pointer. If it is, produce 1618 // a diagnostic and mark the designator as invalid. 1619 template <typename GenDiagType> 1620 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1621 if (Designator.Invalid) 1622 return false; 1623 if (IsNullPtr) { 1624 GenDiag(); 1625 Designator.setInvalid(); 1626 return false; 1627 } 1628 return true; 1629 } 1630 1631 public: 1632 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1633 CheckSubobjectKind CSK) { 1634 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1635 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1636 }); 1637 } 1638 1639 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1640 AccessKinds AK) { 1641 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1642 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1643 }); 1644 } 1645 1646 // Check this LValue refers to an object. If not, set the designator to be 1647 // invalid and emit a diagnostic. 1648 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1649 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1650 Designator.checkSubobject(Info, E, CSK); 1651 } 1652 1653 void addDecl(EvalInfo &Info, const Expr *E, 1654 const Decl *D, bool Virtual = false) { 1655 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1656 Designator.addDeclUnchecked(D, Virtual); 1657 } 1658 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1659 if (!Designator.Entries.empty()) { 1660 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1661 Designator.setInvalid(); 1662 return; 1663 } 1664 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1665 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1666 Designator.FirstEntryIsAnUnsizedArray = true; 1667 Designator.addUnsizedArrayUnchecked(ElemTy); 1668 } 1669 } 1670 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1671 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1672 Designator.addArrayUnchecked(CAT); 1673 } 1674 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1675 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1676 Designator.addComplexUnchecked(EltTy, Imag); 1677 } 1678 void clearIsNullPointer() { 1679 IsNullPtr = false; 1680 } 1681 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1682 const APSInt &Index, CharUnits ElementSize) { 1683 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1684 // but we're not required to diagnose it and it's valid in C++.) 1685 if (!Index) 1686 return; 1687 1688 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1689 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1690 // offsets. 1691 uint64_t Offset64 = Offset.getQuantity(); 1692 uint64_t ElemSize64 = ElementSize.getQuantity(); 1693 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1694 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1695 1696 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1697 Designator.adjustIndex(Info, E, Index); 1698 clearIsNullPointer(); 1699 } 1700 void adjustOffset(CharUnits N) { 1701 Offset += N; 1702 if (N.getQuantity()) 1703 clearIsNullPointer(); 1704 } 1705 }; 1706 1707 struct MemberPtr { 1708 MemberPtr() {} 1709 explicit MemberPtr(const ValueDecl *Decl) : 1710 DeclAndIsDerivedMember(Decl, false), Path() {} 1711 1712 /// The member or (direct or indirect) field referred to by this member 1713 /// pointer, or 0 if this is a null member pointer. 1714 const ValueDecl *getDecl() const { 1715 return DeclAndIsDerivedMember.getPointer(); 1716 } 1717 /// Is this actually a member of some type derived from the relevant class? 1718 bool isDerivedMember() const { 1719 return DeclAndIsDerivedMember.getInt(); 1720 } 1721 /// Get the class which the declaration actually lives in. 1722 const CXXRecordDecl *getContainingRecord() const { 1723 return cast<CXXRecordDecl>( 1724 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1725 } 1726 1727 void moveInto(APValue &V) const { 1728 V = APValue(getDecl(), isDerivedMember(), Path); 1729 } 1730 void setFrom(const APValue &V) { 1731 assert(V.isMemberPointer()); 1732 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1733 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1734 Path.clear(); 1735 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1736 Path.insert(Path.end(), P.begin(), P.end()); 1737 } 1738 1739 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1740 /// whether the member is a member of some class derived from the class type 1741 /// of the member pointer. 1742 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1743 /// Path - The path of base/derived classes from the member declaration's 1744 /// class (exclusive) to the class type of the member pointer (inclusive). 1745 SmallVector<const CXXRecordDecl*, 4> Path; 1746 1747 /// Perform a cast towards the class of the Decl (either up or down the 1748 /// hierarchy). 1749 bool castBack(const CXXRecordDecl *Class) { 1750 assert(!Path.empty()); 1751 const CXXRecordDecl *Expected; 1752 if (Path.size() >= 2) 1753 Expected = Path[Path.size() - 2]; 1754 else 1755 Expected = getContainingRecord(); 1756 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1757 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1758 // if B does not contain the original member and is not a base or 1759 // derived class of the class containing the original member, the result 1760 // of the cast is undefined. 1761 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1762 // (D::*). We consider that to be a language defect. 1763 return false; 1764 } 1765 Path.pop_back(); 1766 return true; 1767 } 1768 /// Perform a base-to-derived member pointer cast. 1769 bool castToDerived(const CXXRecordDecl *Derived) { 1770 if (!getDecl()) 1771 return true; 1772 if (!isDerivedMember()) { 1773 Path.push_back(Derived); 1774 return true; 1775 } 1776 if (!castBack(Derived)) 1777 return false; 1778 if (Path.empty()) 1779 DeclAndIsDerivedMember.setInt(false); 1780 return true; 1781 } 1782 /// Perform a derived-to-base member pointer cast. 1783 bool castToBase(const CXXRecordDecl *Base) { 1784 if (!getDecl()) 1785 return true; 1786 if (Path.empty()) 1787 DeclAndIsDerivedMember.setInt(true); 1788 if (isDerivedMember()) { 1789 Path.push_back(Base); 1790 return true; 1791 } 1792 return castBack(Base); 1793 } 1794 }; 1795 1796 /// Compare two member pointers, which are assumed to be of the same type. 1797 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1798 if (!LHS.getDecl() || !RHS.getDecl()) 1799 return !LHS.getDecl() && !RHS.getDecl(); 1800 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1801 return false; 1802 return LHS.Path == RHS.Path; 1803 } 1804 } 1805 1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1808 const LValue &This, const Expr *E, 1809 bool AllowNonLiteralTypes = false); 1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1811 bool InvalidBaseOK = false); 1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1813 bool InvalidBaseOK = false); 1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1815 EvalInfo &Info); 1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1819 EvalInfo &Info); 1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 1826 EvalInfo &Info); 1827 1828 /// Evaluate an integer or fixed point expression into an APResult. 1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1830 EvalInfo &Info); 1831 1832 /// Evaluate only a fixed point expression into an APResult. 1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1834 EvalInfo &Info); 1835 1836 //===----------------------------------------------------------------------===// 1837 // Misc utilities 1838 //===----------------------------------------------------------------------===// 1839 1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1841 /// preserving its value (by extending by up to one bit as needed). 1842 static void negateAsSigned(APSInt &Int) { 1843 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1844 Int = Int.extend(Int.getBitWidth() + 1); 1845 Int.setIsSigned(true); 1846 } 1847 Int = -Int; 1848 } 1849 1850 template<typename KeyT> 1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1852 ScopeKind Scope, LValue &LV) { 1853 unsigned Version = getTempVersion(); 1854 APValue::LValueBase Base(Key, Index, Version); 1855 LV.set(Base); 1856 return createLocal(Base, Key, T, Scope); 1857 } 1858 1859 /// Allocate storage for a parameter of a function call made in this frame. 1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1861 LValue &LV) { 1862 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1863 APValue::LValueBase Base(PVD, Index, Args.Version); 1864 LV.set(Base); 1865 // We always destroy parameters at the end of the call, even if we'd allow 1866 // them to live to the end of the full-expression at runtime, in order to 1867 // give portable results and match other compilers. 1868 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1869 } 1870 1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1872 QualType T, ScopeKind Scope) { 1873 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1874 unsigned Version = Base.getVersion(); 1875 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1876 assert(Result.isAbsent() && "local created multiple times"); 1877 1878 // If we're creating a local immediately in the operand of a speculative 1879 // evaluation, don't register a cleanup to be run outside the speculative 1880 // evaluation context, since we won't actually be able to initialize this 1881 // object. 1882 if (Index <= Info.SpeculativeEvaluationDepth) { 1883 if (T.isDestructedType()) 1884 Info.noteSideEffect(); 1885 } else { 1886 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1887 } 1888 return Result; 1889 } 1890 1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1892 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1893 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1894 return nullptr; 1895 } 1896 1897 DynamicAllocLValue DA(NumHeapAllocs++); 1898 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1899 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1900 std::forward_as_tuple(DA), std::tuple<>()); 1901 assert(Result.second && "reused a heap alloc index?"); 1902 Result.first->second.AllocExpr = E; 1903 return &Result.first->second.Value; 1904 } 1905 1906 /// Produce a string describing the given constexpr call. 1907 void CallStackFrame::describe(raw_ostream &Out) { 1908 unsigned ArgIndex = 0; 1909 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1910 !isa<CXXConstructorDecl>(Callee) && 1911 cast<CXXMethodDecl>(Callee)->isInstance(); 1912 1913 if (!IsMemberCall) 1914 Out << *Callee << '('; 1915 1916 if (This && IsMemberCall) { 1917 APValue Val; 1918 This->moveInto(Val); 1919 Val.printPretty(Out, Info.Ctx, 1920 This->Designator.MostDerivedType); 1921 // FIXME: Add parens around Val if needed. 1922 Out << "->" << *Callee << '('; 1923 IsMemberCall = false; 1924 } 1925 1926 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1927 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1928 if (ArgIndex > (unsigned)IsMemberCall) 1929 Out << ", "; 1930 1931 const ParmVarDecl *Param = *I; 1932 APValue *V = Info.getParamSlot(Arguments, Param); 1933 if (V) 1934 V->printPretty(Out, Info.Ctx, Param->getType()); 1935 else 1936 Out << "<...>"; 1937 1938 if (ArgIndex == 0 && IsMemberCall) 1939 Out << "->" << *Callee << '('; 1940 } 1941 1942 Out << ')'; 1943 } 1944 1945 /// Evaluate an expression to see if it had side-effects, and discard its 1946 /// result. 1947 /// \return \c true if the caller should keep evaluating. 1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1949 assert(!E->isValueDependent()); 1950 APValue Scratch; 1951 if (!Evaluate(Scratch, Info, E)) 1952 // We don't need the value, but we might have skipped a side effect here. 1953 return Info.noteSideEffect(); 1954 return true; 1955 } 1956 1957 /// Should this call expression be treated as a constant? 1958 static bool IsConstantCall(const CallExpr *E) { 1959 unsigned Builtin = E->getBuiltinCallee(); 1960 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1961 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 1962 Builtin == Builtin::BI__builtin_function_start); 1963 } 1964 1965 static bool IsGlobalLValue(APValue::LValueBase B) { 1966 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1967 // constant expression of pointer type that evaluates to... 1968 1969 // ... a null pointer value, or a prvalue core constant expression of type 1970 // std::nullptr_t. 1971 if (!B) return true; 1972 1973 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1974 // ... the address of an object with static storage duration, 1975 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1976 return VD->hasGlobalStorage(); 1977 if (isa<TemplateParamObjectDecl>(D)) 1978 return true; 1979 // ... the address of a function, 1980 // ... the address of a GUID [MS extension], 1981 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1982 } 1983 1984 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1985 return true; 1986 1987 const Expr *E = B.get<const Expr*>(); 1988 switch (E->getStmtClass()) { 1989 default: 1990 return false; 1991 case Expr::CompoundLiteralExprClass: { 1992 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1993 return CLE->isFileScope() && CLE->isLValue(); 1994 } 1995 case Expr::MaterializeTemporaryExprClass: 1996 // A materialized temporary might have been lifetime-extended to static 1997 // storage duration. 1998 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1999 // A string literal has static storage duration. 2000 case Expr::StringLiteralClass: 2001 case Expr::PredefinedExprClass: 2002 case Expr::ObjCStringLiteralClass: 2003 case Expr::ObjCEncodeExprClass: 2004 return true; 2005 case Expr::ObjCBoxedExprClass: 2006 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2007 case Expr::CallExprClass: 2008 return IsConstantCall(cast<CallExpr>(E)); 2009 // For GCC compatibility, &&label has static storage duration. 2010 case Expr::AddrLabelExprClass: 2011 return true; 2012 // A Block literal expression may be used as the initialization value for 2013 // Block variables at global or local static scope. 2014 case Expr::BlockExprClass: 2015 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2016 case Expr::ImplicitValueInitExprClass: 2017 // FIXME: 2018 // We can never form an lvalue with an implicit value initialization as its 2019 // base through expression evaluation, so these only appear in one case: the 2020 // implicit variable declaration we invent when checking whether a constexpr 2021 // constructor can produce a constant expression. We must assume that such 2022 // an expression might be a global lvalue. 2023 return true; 2024 } 2025 } 2026 2027 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2028 return LVal.Base.dyn_cast<const ValueDecl*>(); 2029 } 2030 2031 static bool IsLiteralLValue(const LValue &Value) { 2032 if (Value.getLValueCallIndex()) 2033 return false; 2034 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2035 return E && !isa<MaterializeTemporaryExpr>(E); 2036 } 2037 2038 static bool IsWeakLValue(const LValue &Value) { 2039 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2040 return Decl && Decl->isWeak(); 2041 } 2042 2043 static bool isZeroSized(const LValue &Value) { 2044 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2045 if (Decl && isa<VarDecl>(Decl)) { 2046 QualType Ty = Decl->getType(); 2047 if (Ty->isArrayType()) 2048 return Ty->isIncompleteType() || 2049 Decl->getASTContext().getTypeSize(Ty) == 0; 2050 } 2051 return false; 2052 } 2053 2054 static bool HasSameBase(const LValue &A, const LValue &B) { 2055 if (!A.getLValueBase()) 2056 return !B.getLValueBase(); 2057 if (!B.getLValueBase()) 2058 return false; 2059 2060 if (A.getLValueBase().getOpaqueValue() != 2061 B.getLValueBase().getOpaqueValue()) 2062 return false; 2063 2064 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2065 A.getLValueVersion() == B.getLValueVersion(); 2066 } 2067 2068 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2069 assert(Base && "no location for a null lvalue"); 2070 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2071 2072 // For a parameter, find the corresponding call stack frame (if it still 2073 // exists), and point at the parameter of the function definition we actually 2074 // invoked. 2075 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2076 unsigned Idx = PVD->getFunctionScopeIndex(); 2077 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2078 if (F->Arguments.CallIndex == Base.getCallIndex() && 2079 F->Arguments.Version == Base.getVersion() && F->Callee && 2080 Idx < F->Callee->getNumParams()) { 2081 VD = F->Callee->getParamDecl(Idx); 2082 break; 2083 } 2084 } 2085 } 2086 2087 if (VD) 2088 Info.Note(VD->getLocation(), diag::note_declared_at); 2089 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2090 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2091 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2092 // FIXME: Produce a note for dangling pointers too. 2093 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2094 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2095 diag::note_constexpr_dynamic_alloc_here); 2096 } 2097 // We have no information to show for a typeid(T) object. 2098 } 2099 2100 enum class CheckEvaluationResultKind { 2101 ConstantExpression, 2102 FullyInitialized, 2103 }; 2104 2105 /// Materialized temporaries that we've already checked to determine if they're 2106 /// initializsed by a constant expression. 2107 using CheckedTemporaries = 2108 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2109 2110 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2111 EvalInfo &Info, SourceLocation DiagLoc, 2112 QualType Type, const APValue &Value, 2113 ConstantExprKind Kind, 2114 SourceLocation SubobjectLoc, 2115 CheckedTemporaries &CheckedTemps); 2116 2117 /// Check that this reference or pointer core constant expression is a valid 2118 /// value for an address or reference constant expression. Return true if we 2119 /// can fold this expression, whether or not it's a constant expression. 2120 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2121 QualType Type, const LValue &LVal, 2122 ConstantExprKind Kind, 2123 CheckedTemporaries &CheckedTemps) { 2124 bool IsReferenceType = Type->isReferenceType(); 2125 2126 APValue::LValueBase Base = LVal.getLValueBase(); 2127 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2128 2129 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2130 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2131 2132 // Additional restrictions apply in a template argument. We only enforce the 2133 // C++20 restrictions here; additional syntactic and semantic restrictions 2134 // are applied elsewhere. 2135 if (isTemplateArgument(Kind)) { 2136 int InvalidBaseKind = -1; 2137 StringRef Ident; 2138 if (Base.is<TypeInfoLValue>()) 2139 InvalidBaseKind = 0; 2140 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2141 InvalidBaseKind = 1; 2142 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2143 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2144 InvalidBaseKind = 2; 2145 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2146 InvalidBaseKind = 3; 2147 Ident = PE->getIdentKindName(); 2148 } 2149 2150 if (InvalidBaseKind != -1) { 2151 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2152 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2153 << Ident; 2154 return false; 2155 } 2156 } 2157 2158 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2159 if (FD->isConsteval()) { 2160 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2161 << !Type->isAnyPointerType(); 2162 Info.Note(FD->getLocation(), diag::note_declared_at); 2163 return false; 2164 } 2165 } 2166 2167 // Check that the object is a global. Note that the fake 'this' object we 2168 // manufacture when checking potential constant expressions is conservatively 2169 // assumed to be global here. 2170 if (!IsGlobalLValue(Base)) { 2171 if (Info.getLangOpts().CPlusPlus11) { 2172 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2173 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2174 << IsReferenceType << !Designator.Entries.empty() 2175 << !!VD << VD; 2176 2177 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2178 if (VarD && VarD->isConstexpr()) { 2179 // Non-static local constexpr variables have unintuitive semantics: 2180 // constexpr int a = 1; 2181 // constexpr const int *p = &a; 2182 // ... is invalid because the address of 'a' is not constant. Suggest 2183 // adding a 'static' in this case. 2184 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2185 << VarD 2186 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2187 } else { 2188 NoteLValueLocation(Info, Base); 2189 } 2190 } else { 2191 Info.FFDiag(Loc); 2192 } 2193 // Don't allow references to temporaries to escape. 2194 return false; 2195 } 2196 assert((Info.checkingPotentialConstantExpression() || 2197 LVal.getLValueCallIndex() == 0) && 2198 "have call index for global lvalue"); 2199 2200 if (Base.is<DynamicAllocLValue>()) { 2201 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2202 << IsReferenceType << !Designator.Entries.empty(); 2203 NoteLValueLocation(Info, Base); 2204 return false; 2205 } 2206 2207 if (BaseVD) { 2208 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2209 // Check if this is a thread-local variable. 2210 if (Var->getTLSKind()) 2211 // FIXME: Diagnostic! 2212 return false; 2213 2214 // A dllimport variable never acts like a constant, unless we're 2215 // evaluating a value for use only in name mangling. 2216 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2217 // FIXME: Diagnostic! 2218 return false; 2219 } 2220 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2221 // __declspec(dllimport) must be handled very carefully: 2222 // We must never initialize an expression with the thunk in C++. 2223 // Doing otherwise would allow the same id-expression to yield 2224 // different addresses for the same function in different translation 2225 // units. However, this means that we must dynamically initialize the 2226 // expression with the contents of the import address table at runtime. 2227 // 2228 // The C language has no notion of ODR; furthermore, it has no notion of 2229 // dynamic initialization. This means that we are permitted to 2230 // perform initialization with the address of the thunk. 2231 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2232 FD->hasAttr<DLLImportAttr>()) 2233 // FIXME: Diagnostic! 2234 return false; 2235 } 2236 } else if (const auto *MTE = 2237 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2238 if (CheckedTemps.insert(MTE).second) { 2239 QualType TempType = getType(Base); 2240 if (TempType.isDestructedType()) { 2241 Info.FFDiag(MTE->getExprLoc(), 2242 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2243 << TempType; 2244 return false; 2245 } 2246 2247 APValue *V = MTE->getOrCreateValue(false); 2248 assert(V && "evasluation result refers to uninitialised temporary"); 2249 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2250 Info, MTE->getExprLoc(), TempType, *V, 2251 Kind, SourceLocation(), CheckedTemps)) 2252 return false; 2253 } 2254 } 2255 2256 // Allow address constant expressions to be past-the-end pointers. This is 2257 // an extension: the standard requires them to point to an object. 2258 if (!IsReferenceType) 2259 return true; 2260 2261 // A reference constant expression must refer to an object. 2262 if (!Base) { 2263 // FIXME: diagnostic 2264 Info.CCEDiag(Loc); 2265 return true; 2266 } 2267 2268 // Does this refer one past the end of some object? 2269 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2270 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2271 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2272 NoteLValueLocation(Info, Base); 2273 } 2274 2275 return true; 2276 } 2277 2278 /// Member pointers are constant expressions unless they point to a 2279 /// non-virtual dllimport member function. 2280 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2281 SourceLocation Loc, 2282 QualType Type, 2283 const APValue &Value, 2284 ConstantExprKind Kind) { 2285 const ValueDecl *Member = Value.getMemberPointerDecl(); 2286 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2287 if (!FD) 2288 return true; 2289 if (FD->isConsteval()) { 2290 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2291 Info.Note(FD->getLocation(), diag::note_declared_at); 2292 return false; 2293 } 2294 return isForManglingOnly(Kind) || FD->isVirtual() || 2295 !FD->hasAttr<DLLImportAttr>(); 2296 } 2297 2298 /// Check that this core constant expression is of literal type, and if not, 2299 /// produce an appropriate diagnostic. 2300 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2301 const LValue *This = nullptr) { 2302 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2303 return true; 2304 2305 // C++1y: A constant initializer for an object o [...] may also invoke 2306 // constexpr constructors for o and its subobjects even if those objects 2307 // are of non-literal class types. 2308 // 2309 // C++11 missed this detail for aggregates, so classes like this: 2310 // struct foo_t { union { int i; volatile int j; } u; }; 2311 // are not (obviously) initializable like so: 2312 // __attribute__((__require_constant_initialization__)) 2313 // static const foo_t x = {{0}}; 2314 // because "i" is a subobject with non-literal initialization (due to the 2315 // volatile member of the union). See: 2316 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2317 // Therefore, we use the C++1y behavior. 2318 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2319 return true; 2320 2321 // Prvalue constant expressions must be of literal types. 2322 if (Info.getLangOpts().CPlusPlus11) 2323 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2324 << E->getType(); 2325 else 2326 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2327 return false; 2328 } 2329 2330 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2331 EvalInfo &Info, SourceLocation DiagLoc, 2332 QualType Type, const APValue &Value, 2333 ConstantExprKind Kind, 2334 SourceLocation SubobjectLoc, 2335 CheckedTemporaries &CheckedTemps) { 2336 if (!Value.hasValue()) { 2337 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2338 << true << Type; 2339 if (SubobjectLoc.isValid()) 2340 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2341 return false; 2342 } 2343 2344 // We allow _Atomic(T) to be initialized from anything that T can be 2345 // initialized from. 2346 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2347 Type = AT->getValueType(); 2348 2349 // Core issue 1454: For a literal constant expression of array or class type, 2350 // each subobject of its value shall have been initialized by a constant 2351 // expression. 2352 if (Value.isArray()) { 2353 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2354 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2355 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2356 Value.getArrayInitializedElt(I), Kind, 2357 SubobjectLoc, CheckedTemps)) 2358 return false; 2359 } 2360 if (!Value.hasArrayFiller()) 2361 return true; 2362 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2363 Value.getArrayFiller(), Kind, SubobjectLoc, 2364 CheckedTemps); 2365 } 2366 if (Value.isUnion() && Value.getUnionField()) { 2367 return CheckEvaluationResult( 2368 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2369 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2370 CheckedTemps); 2371 } 2372 if (Value.isStruct()) { 2373 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2374 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2375 unsigned BaseIndex = 0; 2376 for (const CXXBaseSpecifier &BS : CD->bases()) { 2377 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2378 Value.getStructBase(BaseIndex), Kind, 2379 BS.getBeginLoc(), CheckedTemps)) 2380 return false; 2381 ++BaseIndex; 2382 } 2383 } 2384 for (const auto *I : RD->fields()) { 2385 if (I->isUnnamedBitfield()) 2386 continue; 2387 2388 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2389 Value.getStructField(I->getFieldIndex()), 2390 Kind, I->getLocation(), CheckedTemps)) 2391 return false; 2392 } 2393 } 2394 2395 if (Value.isLValue() && 2396 CERK == CheckEvaluationResultKind::ConstantExpression) { 2397 LValue LVal; 2398 LVal.setFrom(Info.Ctx, Value); 2399 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2400 CheckedTemps); 2401 } 2402 2403 if (Value.isMemberPointer() && 2404 CERK == CheckEvaluationResultKind::ConstantExpression) 2405 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2406 2407 // Everything else is fine. 2408 return true; 2409 } 2410 2411 /// Check that this core constant expression value is a valid value for a 2412 /// constant expression. If not, report an appropriate diagnostic. Does not 2413 /// check that the expression is of literal type. 2414 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2415 QualType Type, const APValue &Value, 2416 ConstantExprKind Kind) { 2417 // Nothing to check for a constant expression of type 'cv void'. 2418 if (Type->isVoidType()) 2419 return true; 2420 2421 CheckedTemporaries CheckedTemps; 2422 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2423 Info, DiagLoc, Type, Value, Kind, 2424 SourceLocation(), CheckedTemps); 2425 } 2426 2427 /// Check that this evaluated value is fully-initialized and can be loaded by 2428 /// an lvalue-to-rvalue conversion. 2429 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2430 QualType Type, const APValue &Value) { 2431 CheckedTemporaries CheckedTemps; 2432 return CheckEvaluationResult( 2433 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2434 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2435 } 2436 2437 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2438 /// "the allocated storage is deallocated within the evaluation". 2439 static bool CheckMemoryLeaks(EvalInfo &Info) { 2440 if (!Info.HeapAllocs.empty()) { 2441 // We can still fold to a constant despite a compile-time memory leak, 2442 // so long as the heap allocation isn't referenced in the result (we check 2443 // that in CheckConstantExpression). 2444 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2445 diag::note_constexpr_memory_leak) 2446 << unsigned(Info.HeapAllocs.size() - 1); 2447 } 2448 return true; 2449 } 2450 2451 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2452 // A null base expression indicates a null pointer. These are always 2453 // evaluatable, and they are false unless the offset is zero. 2454 if (!Value.getLValueBase()) { 2455 Result = !Value.getLValueOffset().isZero(); 2456 return true; 2457 } 2458 2459 // We have a non-null base. These are generally known to be true, but if it's 2460 // a weak declaration it can be null at runtime. 2461 Result = true; 2462 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2463 return !Decl || !Decl->isWeak(); 2464 } 2465 2466 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2467 switch (Val.getKind()) { 2468 case APValue::None: 2469 case APValue::Indeterminate: 2470 return false; 2471 case APValue::Int: 2472 Result = Val.getInt().getBoolValue(); 2473 return true; 2474 case APValue::FixedPoint: 2475 Result = Val.getFixedPoint().getBoolValue(); 2476 return true; 2477 case APValue::Float: 2478 Result = !Val.getFloat().isZero(); 2479 return true; 2480 case APValue::ComplexInt: 2481 Result = Val.getComplexIntReal().getBoolValue() || 2482 Val.getComplexIntImag().getBoolValue(); 2483 return true; 2484 case APValue::ComplexFloat: 2485 Result = !Val.getComplexFloatReal().isZero() || 2486 !Val.getComplexFloatImag().isZero(); 2487 return true; 2488 case APValue::LValue: 2489 return EvalPointerValueAsBool(Val, Result); 2490 case APValue::MemberPointer: 2491 Result = Val.getMemberPointerDecl(); 2492 return true; 2493 case APValue::Vector: 2494 case APValue::Array: 2495 case APValue::Struct: 2496 case APValue::Union: 2497 case APValue::AddrLabelDiff: 2498 return false; 2499 } 2500 2501 llvm_unreachable("unknown APValue kind"); 2502 } 2503 2504 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2505 EvalInfo &Info) { 2506 assert(!E->isValueDependent()); 2507 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2508 APValue Val; 2509 if (!Evaluate(Val, Info, E)) 2510 return false; 2511 return HandleConversionToBool(Val, Result); 2512 } 2513 2514 template<typename T> 2515 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2516 const T &SrcValue, QualType DestType) { 2517 Info.CCEDiag(E, diag::note_constexpr_overflow) 2518 << SrcValue << DestType; 2519 return Info.noteUndefinedBehavior(); 2520 } 2521 2522 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2523 QualType SrcType, const APFloat &Value, 2524 QualType DestType, APSInt &Result) { 2525 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2526 // Determine whether we are converting to unsigned or signed. 2527 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2528 2529 Result = APSInt(DestWidth, !DestSigned); 2530 bool ignored; 2531 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2532 & APFloat::opInvalidOp) 2533 return HandleOverflow(Info, E, Value, DestType); 2534 return true; 2535 } 2536 2537 /// Get rounding mode used for evaluation of the specified expression. 2538 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2539 /// dynamic. 2540 /// If rounding mode is unknown at compile time, still try to evaluate the 2541 /// expression. If the result is exact, it does not depend on rounding mode. 2542 /// So return "tonearest" mode instead of "dynamic". 2543 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2544 bool &DynamicRM) { 2545 llvm::RoundingMode RM = 2546 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2547 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2548 if (DynamicRM) 2549 RM = llvm::RoundingMode::NearestTiesToEven; 2550 return RM; 2551 } 2552 2553 /// Check if the given evaluation result is allowed for constant evaluation. 2554 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2555 APFloat::opStatus St) { 2556 // In a constant context, assume that any dynamic rounding mode or FP 2557 // exception state matches the default floating-point environment. 2558 if (Info.InConstantContext) 2559 return true; 2560 2561 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2562 if ((St & APFloat::opInexact) && 2563 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2564 // Inexact result means that it depends on rounding mode. If the requested 2565 // mode is dynamic, the evaluation cannot be made in compile time. 2566 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2567 return false; 2568 } 2569 2570 if ((St != APFloat::opOK) && 2571 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2572 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2573 FPO.getAllowFEnvAccess())) { 2574 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2575 return false; 2576 } 2577 2578 if ((St & APFloat::opStatus::opInvalidOp) && 2579 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2580 // There is no usefully definable result. 2581 Info.FFDiag(E); 2582 return false; 2583 } 2584 2585 // FIXME: if: 2586 // - evaluation triggered other FP exception, and 2587 // - exception mode is not "ignore", and 2588 // - the expression being evaluated is not a part of global variable 2589 // initializer, 2590 // the evaluation probably need to be rejected. 2591 return true; 2592 } 2593 2594 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2595 QualType SrcType, QualType DestType, 2596 APFloat &Result) { 2597 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2598 bool DynamicRM; 2599 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2600 APFloat::opStatus St; 2601 APFloat Value = Result; 2602 bool ignored; 2603 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2604 return checkFloatingPointResult(Info, E, St); 2605 } 2606 2607 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2608 QualType DestType, QualType SrcType, 2609 const APSInt &Value) { 2610 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2611 // Figure out if this is a truncate, extend or noop cast. 2612 // If the input is signed, do a sign extend, noop, or truncate. 2613 APSInt Result = Value.extOrTrunc(DestWidth); 2614 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2615 if (DestType->isBooleanType()) 2616 Result = Value.getBoolValue(); 2617 return Result; 2618 } 2619 2620 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2621 const FPOptions FPO, 2622 QualType SrcType, const APSInt &Value, 2623 QualType DestType, APFloat &Result) { 2624 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2625 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2626 APFloat::rmNearestTiesToEven); 2627 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2628 FPO.isFPConstrained()) { 2629 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2630 return false; 2631 } 2632 return true; 2633 } 2634 2635 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2636 APValue &Value, const FieldDecl *FD) { 2637 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2638 2639 if (!Value.isInt()) { 2640 // Trying to store a pointer-cast-to-integer into a bitfield. 2641 // FIXME: In this case, we should provide the diagnostic for casting 2642 // a pointer to an integer. 2643 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2644 Info.FFDiag(E); 2645 return false; 2646 } 2647 2648 APSInt &Int = Value.getInt(); 2649 unsigned OldBitWidth = Int.getBitWidth(); 2650 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2651 if (NewBitWidth < OldBitWidth) 2652 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2653 return true; 2654 } 2655 2656 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2657 llvm::APInt &Res) { 2658 APValue SVal; 2659 if (!Evaluate(SVal, Info, E)) 2660 return false; 2661 if (SVal.isInt()) { 2662 Res = SVal.getInt(); 2663 return true; 2664 } 2665 if (SVal.isFloat()) { 2666 Res = SVal.getFloat().bitcastToAPInt(); 2667 return true; 2668 } 2669 if (SVal.isVector()) { 2670 QualType VecTy = E->getType(); 2671 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2672 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2673 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2674 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2675 Res = llvm::APInt::getZero(VecSize); 2676 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2677 APValue &Elt = SVal.getVectorElt(i); 2678 llvm::APInt EltAsInt; 2679 if (Elt.isInt()) { 2680 EltAsInt = Elt.getInt(); 2681 } else if (Elt.isFloat()) { 2682 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2683 } else { 2684 // Don't try to handle vectors of anything other than int or float 2685 // (not sure if it's possible to hit this case). 2686 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2687 return false; 2688 } 2689 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2690 if (BigEndian) 2691 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2692 else 2693 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2694 } 2695 return true; 2696 } 2697 // Give up if the input isn't an int, float, or vector. For example, we 2698 // reject "(v4i16)(intptr_t)&a". 2699 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2700 return false; 2701 } 2702 2703 /// Perform the given integer operation, which is known to need at most BitWidth 2704 /// bits, and check for overflow in the original type (if that type was not an 2705 /// unsigned type). 2706 template<typename Operation> 2707 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2708 const APSInt &LHS, const APSInt &RHS, 2709 unsigned BitWidth, Operation Op, 2710 APSInt &Result) { 2711 if (LHS.isUnsigned()) { 2712 Result = Op(LHS, RHS); 2713 return true; 2714 } 2715 2716 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2717 Result = Value.trunc(LHS.getBitWidth()); 2718 if (Result.extend(BitWidth) != Value) { 2719 if (Info.checkingForUndefinedBehavior()) 2720 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2721 diag::warn_integer_constant_overflow) 2722 << toString(Result, 10) << E->getType(); 2723 return HandleOverflow(Info, E, Value, E->getType()); 2724 } 2725 return true; 2726 } 2727 2728 /// Perform the given binary integer operation. 2729 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2730 BinaryOperatorKind Opcode, APSInt RHS, 2731 APSInt &Result) { 2732 switch (Opcode) { 2733 default: 2734 Info.FFDiag(E); 2735 return false; 2736 case BO_Mul: 2737 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2738 std::multiplies<APSInt>(), Result); 2739 case BO_Add: 2740 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2741 std::plus<APSInt>(), Result); 2742 case BO_Sub: 2743 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2744 std::minus<APSInt>(), Result); 2745 case BO_And: Result = LHS & RHS; return true; 2746 case BO_Xor: Result = LHS ^ RHS; return true; 2747 case BO_Or: Result = LHS | RHS; return true; 2748 case BO_Div: 2749 case BO_Rem: 2750 if (RHS == 0) { 2751 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2752 return false; 2753 } 2754 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2755 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2756 // this operation and gives the two's complement result. 2757 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2758 LHS.isMinSignedValue()) 2759 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2760 E->getType()); 2761 return true; 2762 case BO_Shl: { 2763 if (Info.getLangOpts().OpenCL) 2764 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2765 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2766 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2767 RHS.isUnsigned()); 2768 else if (RHS.isSigned() && RHS.isNegative()) { 2769 // During constant-folding, a negative shift is an opposite shift. Such 2770 // a shift is not a constant expression. 2771 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2772 RHS = -RHS; 2773 goto shift_right; 2774 } 2775 shift_left: 2776 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2777 // the shifted type. 2778 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2779 if (SA != RHS) { 2780 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2781 << RHS << E->getType() << LHS.getBitWidth(); 2782 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2783 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2784 // operand, and must not overflow the corresponding unsigned type. 2785 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2786 // E1 x 2^E2 module 2^N. 2787 if (LHS.isNegative()) 2788 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2789 else if (LHS.countLeadingZeros() < SA) 2790 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2791 } 2792 Result = LHS << SA; 2793 return true; 2794 } 2795 case BO_Shr: { 2796 if (Info.getLangOpts().OpenCL) 2797 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2798 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2799 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2800 RHS.isUnsigned()); 2801 else if (RHS.isSigned() && RHS.isNegative()) { 2802 // During constant-folding, a negative shift is an opposite shift. Such a 2803 // shift is not a constant expression. 2804 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2805 RHS = -RHS; 2806 goto shift_left; 2807 } 2808 shift_right: 2809 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2810 // shifted type. 2811 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2812 if (SA != RHS) 2813 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2814 << RHS << E->getType() << LHS.getBitWidth(); 2815 Result = LHS >> SA; 2816 return true; 2817 } 2818 2819 case BO_LT: Result = LHS < RHS; return true; 2820 case BO_GT: Result = LHS > RHS; return true; 2821 case BO_LE: Result = LHS <= RHS; return true; 2822 case BO_GE: Result = LHS >= RHS; return true; 2823 case BO_EQ: Result = LHS == RHS; return true; 2824 case BO_NE: Result = LHS != RHS; return true; 2825 case BO_Cmp: 2826 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2827 } 2828 } 2829 2830 /// Perform the given binary floating-point operation, in-place, on LHS. 2831 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2832 APFloat &LHS, BinaryOperatorKind Opcode, 2833 const APFloat &RHS) { 2834 bool DynamicRM; 2835 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2836 APFloat::opStatus St; 2837 switch (Opcode) { 2838 default: 2839 Info.FFDiag(E); 2840 return false; 2841 case BO_Mul: 2842 St = LHS.multiply(RHS, RM); 2843 break; 2844 case BO_Add: 2845 St = LHS.add(RHS, RM); 2846 break; 2847 case BO_Sub: 2848 St = LHS.subtract(RHS, RM); 2849 break; 2850 case BO_Div: 2851 // [expr.mul]p4: 2852 // If the second operand of / or % is zero the behavior is undefined. 2853 if (RHS.isZero()) 2854 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2855 St = LHS.divide(RHS, RM); 2856 break; 2857 } 2858 2859 // [expr.pre]p4: 2860 // If during the evaluation of an expression, the result is not 2861 // mathematically defined [...], the behavior is undefined. 2862 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2863 if (LHS.isNaN()) { 2864 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2865 return Info.noteUndefinedBehavior(); 2866 } 2867 2868 return checkFloatingPointResult(Info, E, St); 2869 } 2870 2871 static bool handleLogicalOpForVector(const APInt &LHSValue, 2872 BinaryOperatorKind Opcode, 2873 const APInt &RHSValue, APInt &Result) { 2874 bool LHS = (LHSValue != 0); 2875 bool RHS = (RHSValue != 0); 2876 2877 if (Opcode == BO_LAnd) 2878 Result = LHS && RHS; 2879 else 2880 Result = LHS || RHS; 2881 return true; 2882 } 2883 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2884 BinaryOperatorKind Opcode, 2885 const APFloat &RHSValue, APInt &Result) { 2886 bool LHS = !LHSValue.isZero(); 2887 bool RHS = !RHSValue.isZero(); 2888 2889 if (Opcode == BO_LAnd) 2890 Result = LHS && RHS; 2891 else 2892 Result = LHS || RHS; 2893 return true; 2894 } 2895 2896 static bool handleLogicalOpForVector(const APValue &LHSValue, 2897 BinaryOperatorKind Opcode, 2898 const APValue &RHSValue, APInt &Result) { 2899 // The result is always an int type, however operands match the first. 2900 if (LHSValue.getKind() == APValue::Int) 2901 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2902 RHSValue.getInt(), Result); 2903 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2904 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2905 RHSValue.getFloat(), Result); 2906 } 2907 2908 template <typename APTy> 2909 static bool 2910 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2911 const APTy &RHSValue, APInt &Result) { 2912 switch (Opcode) { 2913 default: 2914 llvm_unreachable("unsupported binary operator"); 2915 case BO_EQ: 2916 Result = (LHSValue == RHSValue); 2917 break; 2918 case BO_NE: 2919 Result = (LHSValue != RHSValue); 2920 break; 2921 case BO_LT: 2922 Result = (LHSValue < RHSValue); 2923 break; 2924 case BO_GT: 2925 Result = (LHSValue > RHSValue); 2926 break; 2927 case BO_LE: 2928 Result = (LHSValue <= RHSValue); 2929 break; 2930 case BO_GE: 2931 Result = (LHSValue >= RHSValue); 2932 break; 2933 } 2934 2935 // The boolean operations on these vector types use an instruction that 2936 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2937 // to -1 to make sure that we produce the correct value. 2938 Result.negate(); 2939 2940 return true; 2941 } 2942 2943 static bool handleCompareOpForVector(const APValue &LHSValue, 2944 BinaryOperatorKind Opcode, 2945 const APValue &RHSValue, APInt &Result) { 2946 // The result is always an int type, however operands match the first. 2947 if (LHSValue.getKind() == APValue::Int) 2948 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2949 RHSValue.getInt(), Result); 2950 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2951 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2952 RHSValue.getFloat(), Result); 2953 } 2954 2955 // Perform binary operations for vector types, in place on the LHS. 2956 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2957 BinaryOperatorKind Opcode, 2958 APValue &LHSValue, 2959 const APValue &RHSValue) { 2960 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2961 "Operation not supported on vector types"); 2962 2963 const auto *VT = E->getType()->castAs<VectorType>(); 2964 unsigned NumElements = VT->getNumElements(); 2965 QualType EltTy = VT->getElementType(); 2966 2967 // In the cases (typically C as I've observed) where we aren't evaluating 2968 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2969 // just give up. 2970 if (!LHSValue.isVector()) { 2971 assert(LHSValue.isLValue() && 2972 "A vector result that isn't a vector OR uncalculated LValue"); 2973 Info.FFDiag(E); 2974 return false; 2975 } 2976 2977 assert(LHSValue.getVectorLength() == NumElements && 2978 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2979 2980 SmallVector<APValue, 4> ResultElements; 2981 2982 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2983 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2984 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2985 2986 if (EltTy->isIntegerType()) { 2987 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2988 EltTy->isUnsignedIntegerType()}; 2989 bool Success = true; 2990 2991 if (BinaryOperator::isLogicalOp(Opcode)) 2992 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2993 else if (BinaryOperator::isComparisonOp(Opcode)) 2994 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2995 else 2996 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2997 RHSElt.getInt(), EltResult); 2998 2999 if (!Success) { 3000 Info.FFDiag(E); 3001 return false; 3002 } 3003 ResultElements.emplace_back(EltResult); 3004 3005 } else if (EltTy->isFloatingType()) { 3006 assert(LHSElt.getKind() == APValue::Float && 3007 RHSElt.getKind() == APValue::Float && 3008 "Mismatched LHS/RHS/Result Type"); 3009 APFloat LHSFloat = LHSElt.getFloat(); 3010 3011 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3012 RHSElt.getFloat())) { 3013 Info.FFDiag(E); 3014 return false; 3015 } 3016 3017 ResultElements.emplace_back(LHSFloat); 3018 } 3019 } 3020 3021 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3022 return true; 3023 } 3024 3025 /// Cast an lvalue referring to a base subobject to a derived class, by 3026 /// truncating the lvalue's path to the given length. 3027 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3028 const RecordDecl *TruncatedType, 3029 unsigned TruncatedElements) { 3030 SubobjectDesignator &D = Result.Designator; 3031 3032 // Check we actually point to a derived class object. 3033 if (TruncatedElements == D.Entries.size()) 3034 return true; 3035 assert(TruncatedElements >= D.MostDerivedPathLength && 3036 "not casting to a derived class"); 3037 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3038 return false; 3039 3040 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3041 const RecordDecl *RD = TruncatedType; 3042 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3043 if (RD->isInvalidDecl()) return false; 3044 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3045 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3046 if (isVirtualBaseClass(D.Entries[I])) 3047 Result.Offset -= Layout.getVBaseClassOffset(Base); 3048 else 3049 Result.Offset -= Layout.getBaseClassOffset(Base); 3050 RD = Base; 3051 } 3052 D.Entries.resize(TruncatedElements); 3053 return true; 3054 } 3055 3056 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3057 const CXXRecordDecl *Derived, 3058 const CXXRecordDecl *Base, 3059 const ASTRecordLayout *RL = nullptr) { 3060 if (!RL) { 3061 if (Derived->isInvalidDecl()) return false; 3062 RL = &Info.Ctx.getASTRecordLayout(Derived); 3063 } 3064 3065 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3066 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3067 return true; 3068 } 3069 3070 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3071 const CXXRecordDecl *DerivedDecl, 3072 const CXXBaseSpecifier *Base) { 3073 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3074 3075 if (!Base->isVirtual()) 3076 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3077 3078 SubobjectDesignator &D = Obj.Designator; 3079 if (D.Invalid) 3080 return false; 3081 3082 // Extract most-derived object and corresponding type. 3083 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3084 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3085 return false; 3086 3087 // Find the virtual base class. 3088 if (DerivedDecl->isInvalidDecl()) return false; 3089 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3090 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3091 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3092 return true; 3093 } 3094 3095 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3096 QualType Type, LValue &Result) { 3097 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3098 PathE = E->path_end(); 3099 PathI != PathE; ++PathI) { 3100 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3101 *PathI)) 3102 return false; 3103 Type = (*PathI)->getType(); 3104 } 3105 return true; 3106 } 3107 3108 /// Cast an lvalue referring to a derived class to a known base subobject. 3109 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3110 const CXXRecordDecl *DerivedRD, 3111 const CXXRecordDecl *BaseRD) { 3112 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3113 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3114 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3115 llvm_unreachable("Class must be derived from the passed in base class!"); 3116 3117 for (CXXBasePathElement &Elem : Paths.front()) 3118 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3119 return false; 3120 return true; 3121 } 3122 3123 /// Update LVal to refer to the given field, which must be a member of the type 3124 /// currently described by LVal. 3125 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3126 const FieldDecl *FD, 3127 const ASTRecordLayout *RL = nullptr) { 3128 if (!RL) { 3129 if (FD->getParent()->isInvalidDecl()) return false; 3130 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3131 } 3132 3133 unsigned I = FD->getFieldIndex(); 3134 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3135 LVal.addDecl(Info, E, FD); 3136 return true; 3137 } 3138 3139 /// Update LVal to refer to the given indirect field. 3140 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3141 LValue &LVal, 3142 const IndirectFieldDecl *IFD) { 3143 for (const auto *C : IFD->chain()) 3144 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3145 return false; 3146 return true; 3147 } 3148 3149 /// Get the size of the given type in char units. 3150 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3151 QualType Type, CharUnits &Size) { 3152 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3153 // extension. 3154 if (Type->isVoidType() || Type->isFunctionType()) { 3155 Size = CharUnits::One(); 3156 return true; 3157 } 3158 3159 if (Type->isDependentType()) { 3160 Info.FFDiag(Loc); 3161 return false; 3162 } 3163 3164 if (!Type->isConstantSizeType()) { 3165 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3166 // FIXME: Better diagnostic. 3167 Info.FFDiag(Loc); 3168 return false; 3169 } 3170 3171 Size = Info.Ctx.getTypeSizeInChars(Type); 3172 return true; 3173 } 3174 3175 /// Update a pointer value to model pointer arithmetic. 3176 /// \param Info - Information about the ongoing evaluation. 3177 /// \param E - The expression being evaluated, for diagnostic purposes. 3178 /// \param LVal - The pointer value to be updated. 3179 /// \param EltTy - The pointee type represented by LVal. 3180 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3181 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3182 LValue &LVal, QualType EltTy, 3183 APSInt Adjustment) { 3184 CharUnits SizeOfPointee; 3185 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3186 return false; 3187 3188 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3189 return true; 3190 } 3191 3192 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3193 LValue &LVal, QualType EltTy, 3194 int64_t Adjustment) { 3195 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3196 APSInt::get(Adjustment)); 3197 } 3198 3199 /// Update an lvalue to refer to a component of a complex number. 3200 /// \param Info - Information about the ongoing evaluation. 3201 /// \param LVal - The lvalue to be updated. 3202 /// \param EltTy - The complex number's component type. 3203 /// \param Imag - False for the real component, true for the imaginary. 3204 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3205 LValue &LVal, QualType EltTy, 3206 bool Imag) { 3207 if (Imag) { 3208 CharUnits SizeOfComponent; 3209 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3210 return false; 3211 LVal.Offset += SizeOfComponent; 3212 } 3213 LVal.addComplex(Info, E, EltTy, Imag); 3214 return true; 3215 } 3216 3217 /// Try to evaluate the initializer for a variable declaration. 3218 /// 3219 /// \param Info Information about the ongoing evaluation. 3220 /// \param E An expression to be used when printing diagnostics. 3221 /// \param VD The variable whose initializer should be obtained. 3222 /// \param Version The version of the variable within the frame. 3223 /// \param Frame The frame in which the variable was created. Must be null 3224 /// if this variable is not local to the evaluation. 3225 /// \param Result Filled in with a pointer to the value of the variable. 3226 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3227 const VarDecl *VD, CallStackFrame *Frame, 3228 unsigned Version, APValue *&Result) { 3229 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3230 3231 // If this is a local variable, dig out its value. 3232 if (Frame) { 3233 Result = Frame->getTemporary(VD, Version); 3234 if (Result) 3235 return true; 3236 3237 if (!isa<ParmVarDecl>(VD)) { 3238 // Assume variables referenced within a lambda's call operator that were 3239 // not declared within the call operator are captures and during checking 3240 // of a potential constant expression, assume they are unknown constant 3241 // expressions. 3242 assert(isLambdaCallOperator(Frame->Callee) && 3243 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3244 "missing value for local variable"); 3245 if (Info.checkingPotentialConstantExpression()) 3246 return false; 3247 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3248 // still reachable at all? 3249 Info.FFDiag(E->getBeginLoc(), 3250 diag::note_unimplemented_constexpr_lambda_feature_ast) 3251 << "captures not currently allowed"; 3252 return false; 3253 } 3254 } 3255 3256 // If we're currently evaluating the initializer of this declaration, use that 3257 // in-flight value. 3258 if (Info.EvaluatingDecl == Base) { 3259 Result = Info.EvaluatingDeclValue; 3260 return true; 3261 } 3262 3263 if (isa<ParmVarDecl>(VD)) { 3264 // Assume parameters of a potential constant expression are usable in 3265 // constant expressions. 3266 if (!Info.checkingPotentialConstantExpression() || 3267 !Info.CurrentCall->Callee || 3268 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3269 if (Info.getLangOpts().CPlusPlus11) { 3270 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3271 << VD; 3272 NoteLValueLocation(Info, Base); 3273 } else { 3274 Info.FFDiag(E); 3275 } 3276 } 3277 return false; 3278 } 3279 3280 // Dig out the initializer, and use the declaration which it's attached to. 3281 // FIXME: We should eventually check whether the variable has a reachable 3282 // initializing declaration. 3283 const Expr *Init = VD->getAnyInitializer(VD); 3284 if (!Init) { 3285 // Don't diagnose during potential constant expression checking; an 3286 // initializer might be added later. 3287 if (!Info.checkingPotentialConstantExpression()) { 3288 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3289 << VD; 3290 NoteLValueLocation(Info, Base); 3291 } 3292 return false; 3293 } 3294 3295 if (Init->isValueDependent()) { 3296 // The DeclRefExpr is not value-dependent, but the variable it refers to 3297 // has a value-dependent initializer. This should only happen in 3298 // constant-folding cases, where the variable is not actually of a suitable 3299 // type for use in a constant expression (otherwise the DeclRefExpr would 3300 // have been value-dependent too), so diagnose that. 3301 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3302 if (!Info.checkingPotentialConstantExpression()) { 3303 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3304 ? diag::note_constexpr_ltor_non_constexpr 3305 : diag::note_constexpr_ltor_non_integral, 1) 3306 << VD << VD->getType(); 3307 NoteLValueLocation(Info, Base); 3308 } 3309 return false; 3310 } 3311 3312 // Check that we can fold the initializer. In C++, we will have already done 3313 // this in the cases where it matters for conformance. 3314 SmallVector<PartialDiagnosticAt, 8> Notes; 3315 if (!VD->evaluateValue(Notes)) { 3316 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3317 Notes.size() + 1) << VD; 3318 NoteLValueLocation(Info, Base); 3319 Info.addNotes(Notes); 3320 return false; 3321 } 3322 3323 // Check that the variable is actually usable in constant expressions. For a 3324 // const integral variable or a reference, we might have a non-constant 3325 // initializer that we can nonetheless evaluate the initializer for. Such 3326 // variables are not usable in constant expressions. In C++98, the 3327 // initializer also syntactically needs to be an ICE. 3328 // 3329 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3330 // expressions here; doing so would regress diagnostics for things like 3331 // reading from a volatile constexpr variable. 3332 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3333 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3334 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3335 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3336 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3337 NoteLValueLocation(Info, Base); 3338 } 3339 3340 // Never use the initializer of a weak variable, not even for constant 3341 // folding. We can't be sure that this is the definition that will be used. 3342 if (VD->isWeak()) { 3343 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3344 NoteLValueLocation(Info, Base); 3345 return false; 3346 } 3347 3348 Result = VD->getEvaluatedValue(); 3349 return true; 3350 } 3351 3352 /// Get the base index of the given base class within an APValue representing 3353 /// the given derived class. 3354 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3355 const CXXRecordDecl *Base) { 3356 Base = Base->getCanonicalDecl(); 3357 unsigned Index = 0; 3358 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3359 E = Derived->bases_end(); I != E; ++I, ++Index) { 3360 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3361 return Index; 3362 } 3363 3364 llvm_unreachable("base class missing from derived class's bases list"); 3365 } 3366 3367 /// Extract the value of a character from a string literal. 3368 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3369 uint64_t Index) { 3370 assert(!isa<SourceLocExpr>(Lit) && 3371 "SourceLocExpr should have already been converted to a StringLiteral"); 3372 3373 // FIXME: Support MakeStringConstant 3374 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3375 std::string Str; 3376 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3377 assert(Index <= Str.size() && "Index too large"); 3378 return APSInt::getUnsigned(Str.c_str()[Index]); 3379 } 3380 3381 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3382 Lit = PE->getFunctionName(); 3383 const StringLiteral *S = cast<StringLiteral>(Lit); 3384 const ConstantArrayType *CAT = 3385 Info.Ctx.getAsConstantArrayType(S->getType()); 3386 assert(CAT && "string literal isn't an array"); 3387 QualType CharType = CAT->getElementType(); 3388 assert(CharType->isIntegerType() && "unexpected character type"); 3389 3390 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3391 CharType->isUnsignedIntegerType()); 3392 if (Index < S->getLength()) 3393 Value = S->getCodeUnit(Index); 3394 return Value; 3395 } 3396 3397 // Expand a string literal into an array of characters. 3398 // 3399 // FIXME: This is inefficient; we should probably introduce something similar 3400 // to the LLVM ConstantDataArray to make this cheaper. 3401 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3402 APValue &Result, 3403 QualType AllocType = QualType()) { 3404 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3405 AllocType.isNull() ? S->getType() : AllocType); 3406 assert(CAT && "string literal isn't an array"); 3407 QualType CharType = CAT->getElementType(); 3408 assert(CharType->isIntegerType() && "unexpected character type"); 3409 3410 unsigned Elts = CAT->getSize().getZExtValue(); 3411 Result = APValue(APValue::UninitArray(), 3412 std::min(S->getLength(), Elts), Elts); 3413 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3414 CharType->isUnsignedIntegerType()); 3415 if (Result.hasArrayFiller()) 3416 Result.getArrayFiller() = APValue(Value); 3417 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3418 Value = S->getCodeUnit(I); 3419 Result.getArrayInitializedElt(I) = APValue(Value); 3420 } 3421 } 3422 3423 // Expand an array so that it has more than Index filled elements. 3424 static void expandArray(APValue &Array, unsigned Index) { 3425 unsigned Size = Array.getArraySize(); 3426 assert(Index < Size); 3427 3428 // Always at least double the number of elements for which we store a value. 3429 unsigned OldElts = Array.getArrayInitializedElts(); 3430 unsigned NewElts = std::max(Index+1, OldElts * 2); 3431 NewElts = std::min(Size, std::max(NewElts, 8u)); 3432 3433 // Copy the data across. 3434 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3435 for (unsigned I = 0; I != OldElts; ++I) 3436 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3437 for (unsigned I = OldElts; I != NewElts; ++I) 3438 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3439 if (NewValue.hasArrayFiller()) 3440 NewValue.getArrayFiller() = Array.getArrayFiller(); 3441 Array.swap(NewValue); 3442 } 3443 3444 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3445 /// conversion. If it's of class type, we may assume that the copy operation 3446 /// is trivial. Note that this is never true for a union type with fields 3447 /// (because the copy always "reads" the active member) and always true for 3448 /// a non-class type. 3449 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3450 static bool isReadByLvalueToRvalueConversion(QualType T) { 3451 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3452 return !RD || isReadByLvalueToRvalueConversion(RD); 3453 } 3454 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3455 // FIXME: A trivial copy of a union copies the object representation, even if 3456 // the union is empty. 3457 if (RD->isUnion()) 3458 return !RD->field_empty(); 3459 if (RD->isEmpty()) 3460 return false; 3461 3462 for (auto *Field : RD->fields()) 3463 if (!Field->isUnnamedBitfield() && 3464 isReadByLvalueToRvalueConversion(Field->getType())) 3465 return true; 3466 3467 for (auto &BaseSpec : RD->bases()) 3468 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3469 return true; 3470 3471 return false; 3472 } 3473 3474 /// Diagnose an attempt to read from any unreadable field within the specified 3475 /// type, which might be a class type. 3476 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3477 QualType T) { 3478 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3479 if (!RD) 3480 return false; 3481 3482 if (!RD->hasMutableFields()) 3483 return false; 3484 3485 for (auto *Field : RD->fields()) { 3486 // If we're actually going to read this field in some way, then it can't 3487 // be mutable. If we're in a union, then assigning to a mutable field 3488 // (even an empty one) can change the active member, so that's not OK. 3489 // FIXME: Add core issue number for the union case. 3490 if (Field->isMutable() && 3491 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3492 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3493 Info.Note(Field->getLocation(), diag::note_declared_at); 3494 return true; 3495 } 3496 3497 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3498 return true; 3499 } 3500 3501 for (auto &BaseSpec : RD->bases()) 3502 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3503 return true; 3504 3505 // All mutable fields were empty, and thus not actually read. 3506 return false; 3507 } 3508 3509 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3510 APValue::LValueBase Base, 3511 bool MutableSubobject = false) { 3512 // A temporary or transient heap allocation we created. 3513 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3514 return true; 3515 3516 switch (Info.IsEvaluatingDecl) { 3517 case EvalInfo::EvaluatingDeclKind::None: 3518 return false; 3519 3520 case EvalInfo::EvaluatingDeclKind::Ctor: 3521 // The variable whose initializer we're evaluating. 3522 if (Info.EvaluatingDecl == Base) 3523 return true; 3524 3525 // A temporary lifetime-extended by the variable whose initializer we're 3526 // evaluating. 3527 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3528 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3529 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3530 return false; 3531 3532 case EvalInfo::EvaluatingDeclKind::Dtor: 3533 // C++2a [expr.const]p6: 3534 // [during constant destruction] the lifetime of a and its non-mutable 3535 // subobjects (but not its mutable subobjects) [are] considered to start 3536 // within e. 3537 if (MutableSubobject || Base != Info.EvaluatingDecl) 3538 return false; 3539 // FIXME: We can meaningfully extend this to cover non-const objects, but 3540 // we will need special handling: we should be able to access only 3541 // subobjects of such objects that are themselves declared const. 3542 QualType T = getType(Base); 3543 return T.isConstQualified() || T->isReferenceType(); 3544 } 3545 3546 llvm_unreachable("unknown evaluating decl kind"); 3547 } 3548 3549 namespace { 3550 /// A handle to a complete object (an object that is not a subobject of 3551 /// another object). 3552 struct CompleteObject { 3553 /// The identity of the object. 3554 APValue::LValueBase Base; 3555 /// The value of the complete object. 3556 APValue *Value; 3557 /// The type of the complete object. 3558 QualType Type; 3559 3560 CompleteObject() : Value(nullptr) {} 3561 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3562 : Base(Base), Value(Value), Type(Type) {} 3563 3564 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3565 // If this isn't a "real" access (eg, if it's just accessing the type 3566 // info), allow it. We assume the type doesn't change dynamically for 3567 // subobjects of constexpr objects (even though we'd hit UB here if it 3568 // did). FIXME: Is this right? 3569 if (!isAnyAccess(AK)) 3570 return true; 3571 3572 // In C++14 onwards, it is permitted to read a mutable member whose 3573 // lifetime began within the evaluation. 3574 // FIXME: Should we also allow this in C++11? 3575 if (!Info.getLangOpts().CPlusPlus14) 3576 return false; 3577 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3578 } 3579 3580 explicit operator bool() const { return !Type.isNull(); } 3581 }; 3582 } // end anonymous namespace 3583 3584 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3585 bool IsMutable = false) { 3586 // C++ [basic.type.qualifier]p1: 3587 // - A const object is an object of type const T or a non-mutable subobject 3588 // of a const object. 3589 if (ObjType.isConstQualified() && !IsMutable) 3590 SubobjType.addConst(); 3591 // - A volatile object is an object of type const T or a subobject of a 3592 // volatile object. 3593 if (ObjType.isVolatileQualified()) 3594 SubobjType.addVolatile(); 3595 return SubobjType; 3596 } 3597 3598 /// Find the designated sub-object of an rvalue. 3599 template<typename SubobjectHandler> 3600 typename SubobjectHandler::result_type 3601 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3602 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3603 if (Sub.Invalid) 3604 // A diagnostic will have already been produced. 3605 return handler.failed(); 3606 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3607 if (Info.getLangOpts().CPlusPlus11) 3608 Info.FFDiag(E, Sub.isOnePastTheEnd() 3609 ? diag::note_constexpr_access_past_end 3610 : diag::note_constexpr_access_unsized_array) 3611 << handler.AccessKind; 3612 else 3613 Info.FFDiag(E); 3614 return handler.failed(); 3615 } 3616 3617 APValue *O = Obj.Value; 3618 QualType ObjType = Obj.Type; 3619 const FieldDecl *LastField = nullptr; 3620 const FieldDecl *VolatileField = nullptr; 3621 3622 // Walk the designator's path to find the subobject. 3623 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3624 // Reading an indeterminate value is undefined, but assigning over one is OK. 3625 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3626 (O->isIndeterminate() && 3627 !isValidIndeterminateAccess(handler.AccessKind))) { 3628 if (!Info.checkingPotentialConstantExpression()) 3629 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3630 << handler.AccessKind << O->isIndeterminate(); 3631 return handler.failed(); 3632 } 3633 3634 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3635 // const and volatile semantics are not applied on an object under 3636 // {con,de}struction. 3637 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3638 ObjType->isRecordType() && 3639 Info.isEvaluatingCtorDtor( 3640 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3641 Sub.Entries.begin() + I)) != 3642 ConstructionPhase::None) { 3643 ObjType = Info.Ctx.getCanonicalType(ObjType); 3644 ObjType.removeLocalConst(); 3645 ObjType.removeLocalVolatile(); 3646 } 3647 3648 // If this is our last pass, check that the final object type is OK. 3649 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3650 // Accesses to volatile objects are prohibited. 3651 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3652 if (Info.getLangOpts().CPlusPlus) { 3653 int DiagKind; 3654 SourceLocation Loc; 3655 const NamedDecl *Decl = nullptr; 3656 if (VolatileField) { 3657 DiagKind = 2; 3658 Loc = VolatileField->getLocation(); 3659 Decl = VolatileField; 3660 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3661 DiagKind = 1; 3662 Loc = VD->getLocation(); 3663 Decl = VD; 3664 } else { 3665 DiagKind = 0; 3666 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3667 Loc = E->getExprLoc(); 3668 } 3669 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3670 << handler.AccessKind << DiagKind << Decl; 3671 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3672 } else { 3673 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3674 } 3675 return handler.failed(); 3676 } 3677 3678 // If we are reading an object of class type, there may still be more 3679 // things we need to check: if there are any mutable subobjects, we 3680 // cannot perform this read. (This only happens when performing a trivial 3681 // copy or assignment.) 3682 if (ObjType->isRecordType() && 3683 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3684 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3685 return handler.failed(); 3686 } 3687 3688 if (I == N) { 3689 if (!handler.found(*O, ObjType)) 3690 return false; 3691 3692 // If we modified a bit-field, truncate it to the right width. 3693 if (isModification(handler.AccessKind) && 3694 LastField && LastField->isBitField() && 3695 !truncateBitfieldValue(Info, E, *O, LastField)) 3696 return false; 3697 3698 return true; 3699 } 3700 3701 LastField = nullptr; 3702 if (ObjType->isArrayType()) { 3703 // Next subobject is an array element. 3704 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3705 assert(CAT && "vla in literal type?"); 3706 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3707 if (CAT->getSize().ule(Index)) { 3708 // Note, it should not be possible to form a pointer with a valid 3709 // designator which points more than one past the end of the array. 3710 if (Info.getLangOpts().CPlusPlus11) 3711 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3712 << handler.AccessKind; 3713 else 3714 Info.FFDiag(E); 3715 return handler.failed(); 3716 } 3717 3718 ObjType = CAT->getElementType(); 3719 3720 if (O->getArrayInitializedElts() > Index) 3721 O = &O->getArrayInitializedElt(Index); 3722 else if (!isRead(handler.AccessKind)) { 3723 expandArray(*O, Index); 3724 O = &O->getArrayInitializedElt(Index); 3725 } else 3726 O = &O->getArrayFiller(); 3727 } else if (ObjType->isAnyComplexType()) { 3728 // Next subobject is a complex number. 3729 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3730 if (Index > 1) { 3731 if (Info.getLangOpts().CPlusPlus11) 3732 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3733 << handler.AccessKind; 3734 else 3735 Info.FFDiag(E); 3736 return handler.failed(); 3737 } 3738 3739 ObjType = getSubobjectType( 3740 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3741 3742 assert(I == N - 1 && "extracting subobject of scalar?"); 3743 if (O->isComplexInt()) { 3744 return handler.found(Index ? O->getComplexIntImag() 3745 : O->getComplexIntReal(), ObjType); 3746 } else { 3747 assert(O->isComplexFloat()); 3748 return handler.found(Index ? O->getComplexFloatImag() 3749 : O->getComplexFloatReal(), ObjType); 3750 } 3751 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3752 if (Field->isMutable() && 3753 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3754 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3755 << handler.AccessKind << Field; 3756 Info.Note(Field->getLocation(), diag::note_declared_at); 3757 return handler.failed(); 3758 } 3759 3760 // Next subobject is a class, struct or union field. 3761 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3762 if (RD->isUnion()) { 3763 const FieldDecl *UnionField = O->getUnionField(); 3764 if (!UnionField || 3765 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3766 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3767 // Placement new onto an inactive union member makes it active. 3768 O->setUnion(Field, APValue()); 3769 } else { 3770 // FIXME: If O->getUnionValue() is absent, report that there's no 3771 // active union member rather than reporting the prior active union 3772 // member. We'll need to fix nullptr_t to not use APValue() as its 3773 // representation first. 3774 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3775 << handler.AccessKind << Field << !UnionField << UnionField; 3776 return handler.failed(); 3777 } 3778 } 3779 O = &O->getUnionValue(); 3780 } else 3781 O = &O->getStructField(Field->getFieldIndex()); 3782 3783 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3784 LastField = Field; 3785 if (Field->getType().isVolatileQualified()) 3786 VolatileField = Field; 3787 } else { 3788 // Next subobject is a base class. 3789 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3790 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3791 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3792 3793 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3794 } 3795 } 3796 } 3797 3798 namespace { 3799 struct ExtractSubobjectHandler { 3800 EvalInfo &Info; 3801 const Expr *E; 3802 APValue &Result; 3803 const AccessKinds AccessKind; 3804 3805 typedef bool result_type; 3806 bool failed() { return false; } 3807 bool found(APValue &Subobj, QualType SubobjType) { 3808 Result = Subobj; 3809 if (AccessKind == AK_ReadObjectRepresentation) 3810 return true; 3811 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3812 } 3813 bool found(APSInt &Value, QualType SubobjType) { 3814 Result = APValue(Value); 3815 return true; 3816 } 3817 bool found(APFloat &Value, QualType SubobjType) { 3818 Result = APValue(Value); 3819 return true; 3820 } 3821 }; 3822 } // end anonymous namespace 3823 3824 /// Extract the designated sub-object of an rvalue. 3825 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3826 const CompleteObject &Obj, 3827 const SubobjectDesignator &Sub, APValue &Result, 3828 AccessKinds AK = AK_Read) { 3829 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3830 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3831 return findSubobject(Info, E, Obj, Sub, Handler); 3832 } 3833 3834 namespace { 3835 struct ModifySubobjectHandler { 3836 EvalInfo &Info; 3837 APValue &NewVal; 3838 const Expr *E; 3839 3840 typedef bool result_type; 3841 static const AccessKinds AccessKind = AK_Assign; 3842 3843 bool checkConst(QualType QT) { 3844 // Assigning to a const object has undefined behavior. 3845 if (QT.isConstQualified()) { 3846 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3847 return false; 3848 } 3849 return true; 3850 } 3851 3852 bool failed() { return false; } 3853 bool found(APValue &Subobj, QualType SubobjType) { 3854 if (!checkConst(SubobjType)) 3855 return false; 3856 // We've been given ownership of NewVal, so just swap it in. 3857 Subobj.swap(NewVal); 3858 return true; 3859 } 3860 bool found(APSInt &Value, QualType SubobjType) { 3861 if (!checkConst(SubobjType)) 3862 return false; 3863 if (!NewVal.isInt()) { 3864 // Maybe trying to write a cast pointer value into a complex? 3865 Info.FFDiag(E); 3866 return false; 3867 } 3868 Value = NewVal.getInt(); 3869 return true; 3870 } 3871 bool found(APFloat &Value, QualType SubobjType) { 3872 if (!checkConst(SubobjType)) 3873 return false; 3874 Value = NewVal.getFloat(); 3875 return true; 3876 } 3877 }; 3878 } // end anonymous namespace 3879 3880 const AccessKinds ModifySubobjectHandler::AccessKind; 3881 3882 /// Update the designated sub-object of an rvalue to the given value. 3883 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3884 const CompleteObject &Obj, 3885 const SubobjectDesignator &Sub, 3886 APValue &NewVal) { 3887 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3888 return findSubobject(Info, E, Obj, Sub, Handler); 3889 } 3890 3891 /// Find the position where two subobject designators diverge, or equivalently 3892 /// the length of the common initial subsequence. 3893 static unsigned FindDesignatorMismatch(QualType ObjType, 3894 const SubobjectDesignator &A, 3895 const SubobjectDesignator &B, 3896 bool &WasArrayIndex) { 3897 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3898 for (/**/; I != N; ++I) { 3899 if (!ObjType.isNull() && 3900 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3901 // Next subobject is an array element. 3902 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3903 WasArrayIndex = true; 3904 return I; 3905 } 3906 if (ObjType->isAnyComplexType()) 3907 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3908 else 3909 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3910 } else { 3911 if (A.Entries[I].getAsBaseOrMember() != 3912 B.Entries[I].getAsBaseOrMember()) { 3913 WasArrayIndex = false; 3914 return I; 3915 } 3916 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3917 // Next subobject is a field. 3918 ObjType = FD->getType(); 3919 else 3920 // Next subobject is a base class. 3921 ObjType = QualType(); 3922 } 3923 } 3924 WasArrayIndex = false; 3925 return I; 3926 } 3927 3928 /// Determine whether the given subobject designators refer to elements of the 3929 /// same array object. 3930 static bool AreElementsOfSameArray(QualType ObjType, 3931 const SubobjectDesignator &A, 3932 const SubobjectDesignator &B) { 3933 if (A.Entries.size() != B.Entries.size()) 3934 return false; 3935 3936 bool IsArray = A.MostDerivedIsArrayElement; 3937 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3938 // A is a subobject of the array element. 3939 return false; 3940 3941 // If A (and B) designates an array element, the last entry will be the array 3942 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3943 // of length 1' case, and the entire path must match. 3944 bool WasArrayIndex; 3945 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3946 return CommonLength >= A.Entries.size() - IsArray; 3947 } 3948 3949 /// Find the complete object to which an LValue refers. 3950 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3951 AccessKinds AK, const LValue &LVal, 3952 QualType LValType) { 3953 if (LVal.InvalidBase) { 3954 Info.FFDiag(E); 3955 return CompleteObject(); 3956 } 3957 3958 if (!LVal.Base) { 3959 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3960 return CompleteObject(); 3961 } 3962 3963 CallStackFrame *Frame = nullptr; 3964 unsigned Depth = 0; 3965 if (LVal.getLValueCallIndex()) { 3966 std::tie(Frame, Depth) = 3967 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3968 if (!Frame) { 3969 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3970 << AK << LVal.Base.is<const ValueDecl*>(); 3971 NoteLValueLocation(Info, LVal.Base); 3972 return CompleteObject(); 3973 } 3974 } 3975 3976 bool IsAccess = isAnyAccess(AK); 3977 3978 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3979 // is not a constant expression (even if the object is non-volatile). We also 3980 // apply this rule to C++98, in order to conform to the expected 'volatile' 3981 // semantics. 3982 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3983 if (Info.getLangOpts().CPlusPlus) 3984 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3985 << AK << LValType; 3986 else 3987 Info.FFDiag(E); 3988 return CompleteObject(); 3989 } 3990 3991 // Compute value storage location and type of base object. 3992 APValue *BaseVal = nullptr; 3993 QualType BaseType = getType(LVal.Base); 3994 3995 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3996 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3997 // This is the object whose initializer we're evaluating, so its lifetime 3998 // started in the current evaluation. 3999 BaseVal = Info.EvaluatingDeclValue; 4000 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4001 // Allow reading from a GUID declaration. 4002 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4003 if (isModification(AK)) { 4004 // All the remaining cases do not permit modification of the object. 4005 Info.FFDiag(E, diag::note_constexpr_modify_global); 4006 return CompleteObject(); 4007 } 4008 APValue &V = GD->getAsAPValue(); 4009 if (V.isAbsent()) { 4010 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4011 << GD->getType(); 4012 return CompleteObject(); 4013 } 4014 return CompleteObject(LVal.Base, &V, GD->getType()); 4015 } 4016 4017 // Allow reading from template parameter objects. 4018 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4019 if (isModification(AK)) { 4020 Info.FFDiag(E, diag::note_constexpr_modify_global); 4021 return CompleteObject(); 4022 } 4023 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4024 TPO->getType()); 4025 } 4026 4027 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4028 // In C++11, constexpr, non-volatile variables initialized with constant 4029 // expressions are constant expressions too. Inside constexpr functions, 4030 // parameters are constant expressions even if they're non-const. 4031 // In C++1y, objects local to a constant expression (those with a Frame) are 4032 // both readable and writable inside constant expressions. 4033 // In C, such things can also be folded, although they are not ICEs. 4034 const VarDecl *VD = dyn_cast<VarDecl>(D); 4035 if (VD) { 4036 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4037 VD = VDef; 4038 } 4039 if (!VD || VD->isInvalidDecl()) { 4040 Info.FFDiag(E); 4041 return CompleteObject(); 4042 } 4043 4044 bool IsConstant = BaseType.isConstant(Info.Ctx); 4045 4046 // Unless we're looking at a local variable or argument in a constexpr call, 4047 // the variable we're reading must be const. 4048 if (!Frame) { 4049 if (IsAccess && isa<ParmVarDecl>(VD)) { 4050 // Access of a parameter that's not associated with a frame isn't going 4051 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4052 // suitable diagnostic. 4053 } else if (Info.getLangOpts().CPlusPlus14 && 4054 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4055 // OK, we can read and modify an object if we're in the process of 4056 // evaluating its initializer, because its lifetime began in this 4057 // evaluation. 4058 } else if (isModification(AK)) { 4059 // All the remaining cases do not permit modification of the object. 4060 Info.FFDiag(E, diag::note_constexpr_modify_global); 4061 return CompleteObject(); 4062 } else if (VD->isConstexpr()) { 4063 // OK, we can read this variable. 4064 } else if (BaseType->isIntegralOrEnumerationType()) { 4065 if (!IsConstant) { 4066 if (!IsAccess) 4067 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4068 if (Info.getLangOpts().CPlusPlus) { 4069 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4070 Info.Note(VD->getLocation(), diag::note_declared_at); 4071 } else { 4072 Info.FFDiag(E); 4073 } 4074 return CompleteObject(); 4075 } 4076 } else if (!IsAccess) { 4077 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4078 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4079 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4080 // This variable might end up being constexpr. Don't diagnose it yet. 4081 } else if (IsConstant) { 4082 // Keep evaluating to see what we can do. In particular, we support 4083 // folding of const floating-point types, in order to make static const 4084 // data members of such types (supported as an extension) more useful. 4085 if (Info.getLangOpts().CPlusPlus) { 4086 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4087 ? diag::note_constexpr_ltor_non_constexpr 4088 : diag::note_constexpr_ltor_non_integral, 1) 4089 << VD << BaseType; 4090 Info.Note(VD->getLocation(), diag::note_declared_at); 4091 } else { 4092 Info.CCEDiag(E); 4093 } 4094 } else { 4095 // Never allow reading a non-const value. 4096 if (Info.getLangOpts().CPlusPlus) { 4097 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4098 ? diag::note_constexpr_ltor_non_constexpr 4099 : diag::note_constexpr_ltor_non_integral, 1) 4100 << VD << BaseType; 4101 Info.Note(VD->getLocation(), diag::note_declared_at); 4102 } else { 4103 Info.FFDiag(E); 4104 } 4105 return CompleteObject(); 4106 } 4107 } 4108 4109 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4110 return CompleteObject(); 4111 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4112 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4113 if (!Alloc) { 4114 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4115 return CompleteObject(); 4116 } 4117 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4118 LVal.Base.getDynamicAllocType()); 4119 } else { 4120 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4121 4122 if (!Frame) { 4123 if (const MaterializeTemporaryExpr *MTE = 4124 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4125 assert(MTE->getStorageDuration() == SD_Static && 4126 "should have a frame for a non-global materialized temporary"); 4127 4128 // C++20 [expr.const]p4: [DR2126] 4129 // An object or reference is usable in constant expressions if it is 4130 // - a temporary object of non-volatile const-qualified literal type 4131 // whose lifetime is extended to that of a variable that is usable 4132 // in constant expressions 4133 // 4134 // C++20 [expr.const]p5: 4135 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4136 // - a non-volatile glvalue that refers to an object that is usable 4137 // in constant expressions, or 4138 // - a non-volatile glvalue of literal type that refers to a 4139 // non-volatile object whose lifetime began within the evaluation 4140 // of E; 4141 // 4142 // C++11 misses the 'began within the evaluation of e' check and 4143 // instead allows all temporaries, including things like: 4144 // int &&r = 1; 4145 // int x = ++r; 4146 // constexpr int k = r; 4147 // Therefore we use the C++14-onwards rules in C++11 too. 4148 // 4149 // Note that temporaries whose lifetimes began while evaluating a 4150 // variable's constructor are not usable while evaluating the 4151 // corresponding destructor, not even if they're of const-qualified 4152 // types. 4153 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4154 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4155 if (!IsAccess) 4156 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4157 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4158 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4159 return CompleteObject(); 4160 } 4161 4162 BaseVal = MTE->getOrCreateValue(false); 4163 assert(BaseVal && "got reference to unevaluated temporary"); 4164 } else { 4165 if (!IsAccess) 4166 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4167 APValue Val; 4168 LVal.moveInto(Val); 4169 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4170 << AK 4171 << Val.getAsString(Info.Ctx, 4172 Info.Ctx.getLValueReferenceType(LValType)); 4173 NoteLValueLocation(Info, LVal.Base); 4174 return CompleteObject(); 4175 } 4176 } else { 4177 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4178 assert(BaseVal && "missing value for temporary"); 4179 } 4180 } 4181 4182 // In C++14, we can't safely access any mutable state when we might be 4183 // evaluating after an unmodeled side effect. Parameters are modeled as state 4184 // in the caller, but aren't visible once the call returns, so they can be 4185 // modified in a speculatively-evaluated call. 4186 // 4187 // FIXME: Not all local state is mutable. Allow local constant subobjects 4188 // to be read here (but take care with 'mutable' fields). 4189 unsigned VisibleDepth = Depth; 4190 if (llvm::isa_and_nonnull<ParmVarDecl>( 4191 LVal.Base.dyn_cast<const ValueDecl *>())) 4192 ++VisibleDepth; 4193 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4194 Info.EvalStatus.HasSideEffects) || 4195 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4196 return CompleteObject(); 4197 4198 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4199 } 4200 4201 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4202 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4203 /// glvalue referred to by an entity of reference type. 4204 /// 4205 /// \param Info - Information about the ongoing evaluation. 4206 /// \param Conv - The expression for which we are performing the conversion. 4207 /// Used for diagnostics. 4208 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4209 /// case of a non-class type). 4210 /// \param LVal - The glvalue on which we are attempting to perform this action. 4211 /// \param RVal - The produced value will be placed here. 4212 /// \param WantObjectRepresentation - If true, we're looking for the object 4213 /// representation rather than the value, and in particular, 4214 /// there is no requirement that the result be fully initialized. 4215 static bool 4216 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4217 const LValue &LVal, APValue &RVal, 4218 bool WantObjectRepresentation = false) { 4219 if (LVal.Designator.Invalid) 4220 return false; 4221 4222 // Check for special cases where there is no existing APValue to look at. 4223 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4224 4225 AccessKinds AK = 4226 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4227 4228 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4229 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4230 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4231 // initializer until now for such expressions. Such an expression can't be 4232 // an ICE in C, so this only matters for fold. 4233 if (Type.isVolatileQualified()) { 4234 Info.FFDiag(Conv); 4235 return false; 4236 } 4237 APValue Lit; 4238 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4239 return false; 4240 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4241 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4242 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4243 // Special-case character extraction so we don't have to construct an 4244 // APValue for the whole string. 4245 assert(LVal.Designator.Entries.size() <= 1 && 4246 "Can only read characters from string literals"); 4247 if (LVal.Designator.Entries.empty()) { 4248 // Fail for now for LValue to RValue conversion of an array. 4249 // (This shouldn't show up in C/C++, but it could be triggered by a 4250 // weird EvaluateAsRValue call from a tool.) 4251 Info.FFDiag(Conv); 4252 return false; 4253 } 4254 if (LVal.Designator.isOnePastTheEnd()) { 4255 if (Info.getLangOpts().CPlusPlus11) 4256 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4257 else 4258 Info.FFDiag(Conv); 4259 return false; 4260 } 4261 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4262 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4263 return true; 4264 } 4265 } 4266 4267 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4268 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4269 } 4270 4271 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4272 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4273 QualType LValType, APValue &Val) { 4274 if (LVal.Designator.Invalid) 4275 return false; 4276 4277 if (!Info.getLangOpts().CPlusPlus14) { 4278 Info.FFDiag(E); 4279 return false; 4280 } 4281 4282 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4283 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4284 } 4285 4286 namespace { 4287 struct CompoundAssignSubobjectHandler { 4288 EvalInfo &Info; 4289 const CompoundAssignOperator *E; 4290 QualType PromotedLHSType; 4291 BinaryOperatorKind Opcode; 4292 const APValue &RHS; 4293 4294 static const AccessKinds AccessKind = AK_Assign; 4295 4296 typedef bool result_type; 4297 4298 bool checkConst(QualType QT) { 4299 // Assigning to a const object has undefined behavior. 4300 if (QT.isConstQualified()) { 4301 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4302 return false; 4303 } 4304 return true; 4305 } 4306 4307 bool failed() { return false; } 4308 bool found(APValue &Subobj, QualType SubobjType) { 4309 switch (Subobj.getKind()) { 4310 case APValue::Int: 4311 return found(Subobj.getInt(), SubobjType); 4312 case APValue::Float: 4313 return found(Subobj.getFloat(), SubobjType); 4314 case APValue::ComplexInt: 4315 case APValue::ComplexFloat: 4316 // FIXME: Implement complex compound assignment. 4317 Info.FFDiag(E); 4318 return false; 4319 case APValue::LValue: 4320 return foundPointer(Subobj, SubobjType); 4321 case APValue::Vector: 4322 return foundVector(Subobj, SubobjType); 4323 default: 4324 // FIXME: can this happen? 4325 Info.FFDiag(E); 4326 return false; 4327 } 4328 } 4329 4330 bool foundVector(APValue &Value, QualType SubobjType) { 4331 if (!checkConst(SubobjType)) 4332 return false; 4333 4334 if (!SubobjType->isVectorType()) { 4335 Info.FFDiag(E); 4336 return false; 4337 } 4338 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4339 } 4340 4341 bool found(APSInt &Value, QualType SubobjType) { 4342 if (!checkConst(SubobjType)) 4343 return false; 4344 4345 if (!SubobjType->isIntegerType()) { 4346 // We don't support compound assignment on integer-cast-to-pointer 4347 // values. 4348 Info.FFDiag(E); 4349 return false; 4350 } 4351 4352 if (RHS.isInt()) { 4353 APSInt LHS = 4354 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4355 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4356 return false; 4357 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4358 return true; 4359 } else if (RHS.isFloat()) { 4360 const FPOptions FPO = E->getFPFeaturesInEffect( 4361 Info.Ctx.getLangOpts()); 4362 APFloat FValue(0.0); 4363 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4364 PromotedLHSType, FValue) && 4365 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4366 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4367 Value); 4368 } 4369 4370 Info.FFDiag(E); 4371 return false; 4372 } 4373 bool found(APFloat &Value, QualType SubobjType) { 4374 return checkConst(SubobjType) && 4375 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4376 Value) && 4377 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4378 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4379 } 4380 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4381 if (!checkConst(SubobjType)) 4382 return false; 4383 4384 QualType PointeeType; 4385 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4386 PointeeType = PT->getPointeeType(); 4387 4388 if (PointeeType.isNull() || !RHS.isInt() || 4389 (Opcode != BO_Add && Opcode != BO_Sub)) { 4390 Info.FFDiag(E); 4391 return false; 4392 } 4393 4394 APSInt Offset = RHS.getInt(); 4395 if (Opcode == BO_Sub) 4396 negateAsSigned(Offset); 4397 4398 LValue LVal; 4399 LVal.setFrom(Info.Ctx, Subobj); 4400 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4401 return false; 4402 LVal.moveInto(Subobj); 4403 return true; 4404 } 4405 }; 4406 } // end anonymous namespace 4407 4408 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4409 4410 /// Perform a compound assignment of LVal <op>= RVal. 4411 static bool handleCompoundAssignment(EvalInfo &Info, 4412 const CompoundAssignOperator *E, 4413 const LValue &LVal, QualType LValType, 4414 QualType PromotedLValType, 4415 BinaryOperatorKind Opcode, 4416 const APValue &RVal) { 4417 if (LVal.Designator.Invalid) 4418 return false; 4419 4420 if (!Info.getLangOpts().CPlusPlus14) { 4421 Info.FFDiag(E); 4422 return false; 4423 } 4424 4425 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4426 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4427 RVal }; 4428 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4429 } 4430 4431 namespace { 4432 struct IncDecSubobjectHandler { 4433 EvalInfo &Info; 4434 const UnaryOperator *E; 4435 AccessKinds AccessKind; 4436 APValue *Old; 4437 4438 typedef bool result_type; 4439 4440 bool checkConst(QualType QT) { 4441 // Assigning to a const object has undefined behavior. 4442 if (QT.isConstQualified()) { 4443 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4444 return false; 4445 } 4446 return true; 4447 } 4448 4449 bool failed() { return false; } 4450 bool found(APValue &Subobj, QualType SubobjType) { 4451 // Stash the old value. Also clear Old, so we don't clobber it later 4452 // if we're post-incrementing a complex. 4453 if (Old) { 4454 *Old = Subobj; 4455 Old = nullptr; 4456 } 4457 4458 switch (Subobj.getKind()) { 4459 case APValue::Int: 4460 return found(Subobj.getInt(), SubobjType); 4461 case APValue::Float: 4462 return found(Subobj.getFloat(), SubobjType); 4463 case APValue::ComplexInt: 4464 return found(Subobj.getComplexIntReal(), 4465 SubobjType->castAs<ComplexType>()->getElementType() 4466 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4467 case APValue::ComplexFloat: 4468 return found(Subobj.getComplexFloatReal(), 4469 SubobjType->castAs<ComplexType>()->getElementType() 4470 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4471 case APValue::LValue: 4472 return foundPointer(Subobj, SubobjType); 4473 default: 4474 // FIXME: can this happen? 4475 Info.FFDiag(E); 4476 return false; 4477 } 4478 } 4479 bool found(APSInt &Value, QualType SubobjType) { 4480 if (!checkConst(SubobjType)) 4481 return false; 4482 4483 if (!SubobjType->isIntegerType()) { 4484 // We don't support increment / decrement on integer-cast-to-pointer 4485 // values. 4486 Info.FFDiag(E); 4487 return false; 4488 } 4489 4490 if (Old) *Old = APValue(Value); 4491 4492 // bool arithmetic promotes to int, and the conversion back to bool 4493 // doesn't reduce mod 2^n, so special-case it. 4494 if (SubobjType->isBooleanType()) { 4495 if (AccessKind == AK_Increment) 4496 Value = 1; 4497 else 4498 Value = !Value; 4499 return true; 4500 } 4501 4502 bool WasNegative = Value.isNegative(); 4503 if (AccessKind == AK_Increment) { 4504 ++Value; 4505 4506 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4507 APSInt ActualValue(Value, /*IsUnsigned*/true); 4508 return HandleOverflow(Info, E, ActualValue, SubobjType); 4509 } 4510 } else { 4511 --Value; 4512 4513 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4514 unsigned BitWidth = Value.getBitWidth(); 4515 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4516 ActualValue.setBit(BitWidth); 4517 return HandleOverflow(Info, E, ActualValue, SubobjType); 4518 } 4519 } 4520 return true; 4521 } 4522 bool found(APFloat &Value, QualType SubobjType) { 4523 if (!checkConst(SubobjType)) 4524 return false; 4525 4526 if (Old) *Old = APValue(Value); 4527 4528 APFloat One(Value.getSemantics(), 1); 4529 if (AccessKind == AK_Increment) 4530 Value.add(One, APFloat::rmNearestTiesToEven); 4531 else 4532 Value.subtract(One, APFloat::rmNearestTiesToEven); 4533 return true; 4534 } 4535 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4536 if (!checkConst(SubobjType)) 4537 return false; 4538 4539 QualType PointeeType; 4540 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4541 PointeeType = PT->getPointeeType(); 4542 else { 4543 Info.FFDiag(E); 4544 return false; 4545 } 4546 4547 LValue LVal; 4548 LVal.setFrom(Info.Ctx, Subobj); 4549 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4550 AccessKind == AK_Increment ? 1 : -1)) 4551 return false; 4552 LVal.moveInto(Subobj); 4553 return true; 4554 } 4555 }; 4556 } // end anonymous namespace 4557 4558 /// Perform an increment or decrement on LVal. 4559 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4560 QualType LValType, bool IsIncrement, APValue *Old) { 4561 if (LVal.Designator.Invalid) 4562 return false; 4563 4564 if (!Info.getLangOpts().CPlusPlus14) { 4565 Info.FFDiag(E); 4566 return false; 4567 } 4568 4569 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4570 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4571 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4572 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4573 } 4574 4575 /// Build an lvalue for the object argument of a member function call. 4576 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4577 LValue &This) { 4578 if (Object->getType()->isPointerType() && Object->isPRValue()) 4579 return EvaluatePointer(Object, This, Info); 4580 4581 if (Object->isGLValue()) 4582 return EvaluateLValue(Object, This, Info); 4583 4584 if (Object->getType()->isLiteralType(Info.Ctx)) 4585 return EvaluateTemporary(Object, This, Info); 4586 4587 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4588 return false; 4589 } 4590 4591 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4592 /// lvalue referring to the result. 4593 /// 4594 /// \param Info - Information about the ongoing evaluation. 4595 /// \param LV - An lvalue referring to the base of the member pointer. 4596 /// \param RHS - The member pointer expression. 4597 /// \param IncludeMember - Specifies whether the member itself is included in 4598 /// the resulting LValue subobject designator. This is not possible when 4599 /// creating a bound member function. 4600 /// \return The field or method declaration to which the member pointer refers, 4601 /// or 0 if evaluation fails. 4602 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4603 QualType LVType, 4604 LValue &LV, 4605 const Expr *RHS, 4606 bool IncludeMember = true) { 4607 MemberPtr MemPtr; 4608 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4609 return nullptr; 4610 4611 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4612 // member value, the behavior is undefined. 4613 if (!MemPtr.getDecl()) { 4614 // FIXME: Specific diagnostic. 4615 Info.FFDiag(RHS); 4616 return nullptr; 4617 } 4618 4619 if (MemPtr.isDerivedMember()) { 4620 // This is a member of some derived class. Truncate LV appropriately. 4621 // The end of the derived-to-base path for the base object must match the 4622 // derived-to-base path for the member pointer. 4623 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4624 LV.Designator.Entries.size()) { 4625 Info.FFDiag(RHS); 4626 return nullptr; 4627 } 4628 unsigned PathLengthToMember = 4629 LV.Designator.Entries.size() - MemPtr.Path.size(); 4630 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4631 const CXXRecordDecl *LVDecl = getAsBaseClass( 4632 LV.Designator.Entries[PathLengthToMember + I]); 4633 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4634 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4635 Info.FFDiag(RHS); 4636 return nullptr; 4637 } 4638 } 4639 4640 // Truncate the lvalue to the appropriate derived class. 4641 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4642 PathLengthToMember)) 4643 return nullptr; 4644 } else if (!MemPtr.Path.empty()) { 4645 // Extend the LValue path with the member pointer's path. 4646 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4647 MemPtr.Path.size() + IncludeMember); 4648 4649 // Walk down to the appropriate base class. 4650 if (const PointerType *PT = LVType->getAs<PointerType>()) 4651 LVType = PT->getPointeeType(); 4652 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4653 assert(RD && "member pointer access on non-class-type expression"); 4654 // The first class in the path is that of the lvalue. 4655 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4656 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4657 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4658 return nullptr; 4659 RD = Base; 4660 } 4661 // Finally cast to the class containing the member. 4662 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4663 MemPtr.getContainingRecord())) 4664 return nullptr; 4665 } 4666 4667 // Add the member. Note that we cannot build bound member functions here. 4668 if (IncludeMember) { 4669 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4670 if (!HandleLValueMember(Info, RHS, LV, FD)) 4671 return nullptr; 4672 } else if (const IndirectFieldDecl *IFD = 4673 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4674 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4675 return nullptr; 4676 } else { 4677 llvm_unreachable("can't construct reference to bound member function"); 4678 } 4679 } 4680 4681 return MemPtr.getDecl(); 4682 } 4683 4684 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4685 const BinaryOperator *BO, 4686 LValue &LV, 4687 bool IncludeMember = true) { 4688 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4689 4690 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4691 if (Info.noteFailure()) { 4692 MemberPtr MemPtr; 4693 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4694 } 4695 return nullptr; 4696 } 4697 4698 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4699 BO->getRHS(), IncludeMember); 4700 } 4701 4702 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4703 /// the provided lvalue, which currently refers to the base object. 4704 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4705 LValue &Result) { 4706 SubobjectDesignator &D = Result.Designator; 4707 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4708 return false; 4709 4710 QualType TargetQT = E->getType(); 4711 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4712 TargetQT = PT->getPointeeType(); 4713 4714 // Check this cast lands within the final derived-to-base subobject path. 4715 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4716 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4717 << D.MostDerivedType << TargetQT; 4718 return false; 4719 } 4720 4721 // Check the type of the final cast. We don't need to check the path, 4722 // since a cast can only be formed if the path is unique. 4723 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4724 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4725 const CXXRecordDecl *FinalType; 4726 if (NewEntriesSize == D.MostDerivedPathLength) 4727 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4728 else 4729 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4730 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4731 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4732 << D.MostDerivedType << TargetQT; 4733 return false; 4734 } 4735 4736 // Truncate the lvalue to the appropriate derived class. 4737 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4738 } 4739 4740 /// Get the value to use for a default-initialized object of type T. 4741 /// Return false if it encounters something invalid. 4742 static bool getDefaultInitValue(QualType T, APValue &Result) { 4743 bool Success = true; 4744 if (auto *RD = T->getAsCXXRecordDecl()) { 4745 if (RD->isInvalidDecl()) { 4746 Result = APValue(); 4747 return false; 4748 } 4749 if (RD->isUnion()) { 4750 Result = APValue((const FieldDecl *)nullptr); 4751 return true; 4752 } 4753 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4754 std::distance(RD->field_begin(), RD->field_end())); 4755 4756 unsigned Index = 0; 4757 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4758 End = RD->bases_end(); 4759 I != End; ++I, ++Index) 4760 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4761 4762 for (const auto *I : RD->fields()) { 4763 if (I->isUnnamedBitfield()) 4764 continue; 4765 Success &= getDefaultInitValue(I->getType(), 4766 Result.getStructField(I->getFieldIndex())); 4767 } 4768 return Success; 4769 } 4770 4771 if (auto *AT = 4772 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4773 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4774 if (Result.hasArrayFiller()) 4775 Success &= 4776 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4777 4778 return Success; 4779 } 4780 4781 Result = APValue::IndeterminateValue(); 4782 return true; 4783 } 4784 4785 namespace { 4786 enum EvalStmtResult { 4787 /// Evaluation failed. 4788 ESR_Failed, 4789 /// Hit a 'return' statement. 4790 ESR_Returned, 4791 /// Evaluation succeeded. 4792 ESR_Succeeded, 4793 /// Hit a 'continue' statement. 4794 ESR_Continue, 4795 /// Hit a 'break' statement. 4796 ESR_Break, 4797 /// Still scanning for 'case' or 'default' statement. 4798 ESR_CaseNotFound 4799 }; 4800 } 4801 4802 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4803 // We don't need to evaluate the initializer for a static local. 4804 if (!VD->hasLocalStorage()) 4805 return true; 4806 4807 LValue Result; 4808 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4809 ScopeKind::Block, Result); 4810 4811 const Expr *InitE = VD->getInit(); 4812 if (!InitE) { 4813 if (VD->getType()->isDependentType()) 4814 return Info.noteSideEffect(); 4815 return getDefaultInitValue(VD->getType(), Val); 4816 } 4817 if (InitE->isValueDependent()) 4818 return false; 4819 4820 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4821 // Wipe out any partially-computed value, to allow tracking that this 4822 // evaluation failed. 4823 Val = APValue(); 4824 return false; 4825 } 4826 4827 return true; 4828 } 4829 4830 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4831 bool OK = true; 4832 4833 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4834 OK &= EvaluateVarDecl(Info, VD); 4835 4836 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4837 for (auto *BD : DD->bindings()) 4838 if (auto *VD = BD->getHoldingVar()) 4839 OK &= EvaluateDecl(Info, VD); 4840 4841 return OK; 4842 } 4843 4844 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4845 assert(E->isValueDependent()); 4846 if (Info.noteSideEffect()) 4847 return true; 4848 assert(E->containsErrors() && "valid value-dependent expression should never " 4849 "reach invalid code path."); 4850 return false; 4851 } 4852 4853 /// Evaluate a condition (either a variable declaration or an expression). 4854 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4855 const Expr *Cond, bool &Result) { 4856 if (Cond->isValueDependent()) 4857 return false; 4858 FullExpressionRAII Scope(Info); 4859 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4860 return false; 4861 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4862 return false; 4863 return Scope.destroy(); 4864 } 4865 4866 namespace { 4867 /// A location where the result (returned value) of evaluating a 4868 /// statement should be stored. 4869 struct StmtResult { 4870 /// The APValue that should be filled in with the returned value. 4871 APValue &Value; 4872 /// The location containing the result, if any (used to support RVO). 4873 const LValue *Slot; 4874 }; 4875 4876 struct TempVersionRAII { 4877 CallStackFrame &Frame; 4878 4879 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4880 Frame.pushTempVersion(); 4881 } 4882 4883 ~TempVersionRAII() { 4884 Frame.popTempVersion(); 4885 } 4886 }; 4887 4888 } 4889 4890 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4891 const Stmt *S, 4892 const SwitchCase *SC = nullptr); 4893 4894 /// Evaluate the body of a loop, and translate the result as appropriate. 4895 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4896 const Stmt *Body, 4897 const SwitchCase *Case = nullptr) { 4898 BlockScopeRAII Scope(Info); 4899 4900 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4901 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4902 ESR = ESR_Failed; 4903 4904 switch (ESR) { 4905 case ESR_Break: 4906 return ESR_Succeeded; 4907 case ESR_Succeeded: 4908 case ESR_Continue: 4909 return ESR_Continue; 4910 case ESR_Failed: 4911 case ESR_Returned: 4912 case ESR_CaseNotFound: 4913 return ESR; 4914 } 4915 llvm_unreachable("Invalid EvalStmtResult!"); 4916 } 4917 4918 /// Evaluate a switch statement. 4919 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4920 const SwitchStmt *SS) { 4921 BlockScopeRAII Scope(Info); 4922 4923 // Evaluate the switch condition. 4924 APSInt Value; 4925 { 4926 if (const Stmt *Init = SS->getInit()) { 4927 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4928 if (ESR != ESR_Succeeded) { 4929 if (ESR != ESR_Failed && !Scope.destroy()) 4930 ESR = ESR_Failed; 4931 return ESR; 4932 } 4933 } 4934 4935 FullExpressionRAII CondScope(Info); 4936 if (SS->getConditionVariable() && 4937 !EvaluateDecl(Info, SS->getConditionVariable())) 4938 return ESR_Failed; 4939 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4940 return ESR_Failed; 4941 if (!CondScope.destroy()) 4942 return ESR_Failed; 4943 } 4944 4945 // Find the switch case corresponding to the value of the condition. 4946 // FIXME: Cache this lookup. 4947 const SwitchCase *Found = nullptr; 4948 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4949 SC = SC->getNextSwitchCase()) { 4950 if (isa<DefaultStmt>(SC)) { 4951 Found = SC; 4952 continue; 4953 } 4954 4955 const CaseStmt *CS = cast<CaseStmt>(SC); 4956 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4957 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4958 : LHS; 4959 if (LHS <= Value && Value <= RHS) { 4960 Found = SC; 4961 break; 4962 } 4963 } 4964 4965 if (!Found) 4966 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4967 4968 // Search the switch body for the switch case and evaluate it from there. 4969 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4970 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4971 return ESR_Failed; 4972 4973 switch (ESR) { 4974 case ESR_Break: 4975 return ESR_Succeeded; 4976 case ESR_Succeeded: 4977 case ESR_Continue: 4978 case ESR_Failed: 4979 case ESR_Returned: 4980 return ESR; 4981 case ESR_CaseNotFound: 4982 // This can only happen if the switch case is nested within a statement 4983 // expression. We have no intention of supporting that. 4984 Info.FFDiag(Found->getBeginLoc(), 4985 diag::note_constexpr_stmt_expr_unsupported); 4986 return ESR_Failed; 4987 } 4988 llvm_unreachable("Invalid EvalStmtResult!"); 4989 } 4990 4991 // Evaluate a statement. 4992 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4993 const Stmt *S, const SwitchCase *Case) { 4994 if (!Info.nextStep(S)) 4995 return ESR_Failed; 4996 4997 // If we're hunting down a 'case' or 'default' label, recurse through 4998 // substatements until we hit the label. 4999 if (Case) { 5000 switch (S->getStmtClass()) { 5001 case Stmt::CompoundStmtClass: 5002 // FIXME: Precompute which substatement of a compound statement we 5003 // would jump to, and go straight there rather than performing a 5004 // linear scan each time. 5005 case Stmt::LabelStmtClass: 5006 case Stmt::AttributedStmtClass: 5007 case Stmt::DoStmtClass: 5008 break; 5009 5010 case Stmt::CaseStmtClass: 5011 case Stmt::DefaultStmtClass: 5012 if (Case == S) 5013 Case = nullptr; 5014 break; 5015 5016 case Stmt::IfStmtClass: { 5017 // FIXME: Precompute which side of an 'if' we would jump to, and go 5018 // straight there rather than scanning both sides. 5019 const IfStmt *IS = cast<IfStmt>(S); 5020 5021 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5022 // preceded by our switch label. 5023 BlockScopeRAII Scope(Info); 5024 5025 // Step into the init statement in case it brings an (uninitialized) 5026 // variable into scope. 5027 if (const Stmt *Init = IS->getInit()) { 5028 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5029 if (ESR != ESR_CaseNotFound) { 5030 assert(ESR != ESR_Succeeded); 5031 return ESR; 5032 } 5033 } 5034 5035 // Condition variable must be initialized if it exists. 5036 // FIXME: We can skip evaluating the body if there's a condition 5037 // variable, as there can't be any case labels within it. 5038 // (The same is true for 'for' statements.) 5039 5040 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5041 if (ESR == ESR_Failed) 5042 return ESR; 5043 if (ESR != ESR_CaseNotFound) 5044 return Scope.destroy() ? ESR : ESR_Failed; 5045 if (!IS->getElse()) 5046 return ESR_CaseNotFound; 5047 5048 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5049 if (ESR == ESR_Failed) 5050 return ESR; 5051 if (ESR != ESR_CaseNotFound) 5052 return Scope.destroy() ? ESR : ESR_Failed; 5053 return ESR_CaseNotFound; 5054 } 5055 5056 case Stmt::WhileStmtClass: { 5057 EvalStmtResult ESR = 5058 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5059 if (ESR != ESR_Continue) 5060 return ESR; 5061 break; 5062 } 5063 5064 case Stmt::ForStmtClass: { 5065 const ForStmt *FS = cast<ForStmt>(S); 5066 BlockScopeRAII Scope(Info); 5067 5068 // Step into the init statement in case it brings an (uninitialized) 5069 // variable into scope. 5070 if (const Stmt *Init = FS->getInit()) { 5071 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5072 if (ESR != ESR_CaseNotFound) { 5073 assert(ESR != ESR_Succeeded); 5074 return ESR; 5075 } 5076 } 5077 5078 EvalStmtResult ESR = 5079 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5080 if (ESR != ESR_Continue) 5081 return ESR; 5082 if (const auto *Inc = FS->getInc()) { 5083 if (Inc->isValueDependent()) { 5084 if (!EvaluateDependentExpr(Inc, Info)) 5085 return ESR_Failed; 5086 } else { 5087 FullExpressionRAII IncScope(Info); 5088 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5089 return ESR_Failed; 5090 } 5091 } 5092 break; 5093 } 5094 5095 case Stmt::DeclStmtClass: { 5096 // Start the lifetime of any uninitialized variables we encounter. They 5097 // might be used by the selected branch of the switch. 5098 const DeclStmt *DS = cast<DeclStmt>(S); 5099 for (const auto *D : DS->decls()) { 5100 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5101 if (VD->hasLocalStorage() && !VD->getInit()) 5102 if (!EvaluateVarDecl(Info, VD)) 5103 return ESR_Failed; 5104 // FIXME: If the variable has initialization that can't be jumped 5105 // over, bail out of any immediately-surrounding compound-statement 5106 // too. There can't be any case labels here. 5107 } 5108 } 5109 return ESR_CaseNotFound; 5110 } 5111 5112 default: 5113 return ESR_CaseNotFound; 5114 } 5115 } 5116 5117 switch (S->getStmtClass()) { 5118 default: 5119 if (const Expr *E = dyn_cast<Expr>(S)) { 5120 if (E->isValueDependent()) { 5121 if (!EvaluateDependentExpr(E, Info)) 5122 return ESR_Failed; 5123 } else { 5124 // Don't bother evaluating beyond an expression-statement which couldn't 5125 // be evaluated. 5126 // FIXME: Do we need the FullExpressionRAII object here? 5127 // VisitExprWithCleanups should create one when necessary. 5128 FullExpressionRAII Scope(Info); 5129 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5130 return ESR_Failed; 5131 } 5132 return ESR_Succeeded; 5133 } 5134 5135 Info.FFDiag(S->getBeginLoc()); 5136 return ESR_Failed; 5137 5138 case Stmt::NullStmtClass: 5139 return ESR_Succeeded; 5140 5141 case Stmt::DeclStmtClass: { 5142 const DeclStmt *DS = cast<DeclStmt>(S); 5143 for (const auto *D : DS->decls()) { 5144 // Each declaration initialization is its own full-expression. 5145 FullExpressionRAII Scope(Info); 5146 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5147 return ESR_Failed; 5148 if (!Scope.destroy()) 5149 return ESR_Failed; 5150 } 5151 return ESR_Succeeded; 5152 } 5153 5154 case Stmt::ReturnStmtClass: { 5155 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5156 FullExpressionRAII Scope(Info); 5157 if (RetExpr && RetExpr->isValueDependent()) { 5158 EvaluateDependentExpr(RetExpr, Info); 5159 // We know we returned, but we don't know what the value is. 5160 return ESR_Failed; 5161 } 5162 if (RetExpr && 5163 !(Result.Slot 5164 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5165 : Evaluate(Result.Value, Info, RetExpr))) 5166 return ESR_Failed; 5167 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5168 } 5169 5170 case Stmt::CompoundStmtClass: { 5171 BlockScopeRAII Scope(Info); 5172 5173 const CompoundStmt *CS = cast<CompoundStmt>(S); 5174 for (const auto *BI : CS->body()) { 5175 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5176 if (ESR == ESR_Succeeded) 5177 Case = nullptr; 5178 else if (ESR != ESR_CaseNotFound) { 5179 if (ESR != ESR_Failed && !Scope.destroy()) 5180 return ESR_Failed; 5181 return ESR; 5182 } 5183 } 5184 if (Case) 5185 return ESR_CaseNotFound; 5186 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5187 } 5188 5189 case Stmt::IfStmtClass: { 5190 const IfStmt *IS = cast<IfStmt>(S); 5191 5192 // Evaluate the condition, as either a var decl or as an expression. 5193 BlockScopeRAII Scope(Info); 5194 if (const Stmt *Init = IS->getInit()) { 5195 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5196 if (ESR != ESR_Succeeded) { 5197 if (ESR != ESR_Failed && !Scope.destroy()) 5198 return ESR_Failed; 5199 return ESR; 5200 } 5201 } 5202 bool Cond; 5203 if (IS->isConsteval()) 5204 Cond = IS->isNonNegatedConsteval(); 5205 else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5206 Cond)) 5207 return ESR_Failed; 5208 5209 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5210 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5211 if (ESR != ESR_Succeeded) { 5212 if (ESR != ESR_Failed && !Scope.destroy()) 5213 return ESR_Failed; 5214 return ESR; 5215 } 5216 } 5217 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5218 } 5219 5220 case Stmt::WhileStmtClass: { 5221 const WhileStmt *WS = cast<WhileStmt>(S); 5222 while (true) { 5223 BlockScopeRAII Scope(Info); 5224 bool Continue; 5225 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5226 Continue)) 5227 return ESR_Failed; 5228 if (!Continue) 5229 break; 5230 5231 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5232 if (ESR != ESR_Continue) { 5233 if (ESR != ESR_Failed && !Scope.destroy()) 5234 return ESR_Failed; 5235 return ESR; 5236 } 5237 if (!Scope.destroy()) 5238 return ESR_Failed; 5239 } 5240 return ESR_Succeeded; 5241 } 5242 5243 case Stmt::DoStmtClass: { 5244 const DoStmt *DS = cast<DoStmt>(S); 5245 bool Continue; 5246 do { 5247 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5248 if (ESR != ESR_Continue) 5249 return ESR; 5250 Case = nullptr; 5251 5252 if (DS->getCond()->isValueDependent()) { 5253 EvaluateDependentExpr(DS->getCond(), Info); 5254 // Bailout as we don't know whether to keep going or terminate the loop. 5255 return ESR_Failed; 5256 } 5257 FullExpressionRAII CondScope(Info); 5258 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5259 !CondScope.destroy()) 5260 return ESR_Failed; 5261 } while (Continue); 5262 return ESR_Succeeded; 5263 } 5264 5265 case Stmt::ForStmtClass: { 5266 const ForStmt *FS = cast<ForStmt>(S); 5267 BlockScopeRAII ForScope(Info); 5268 if (FS->getInit()) { 5269 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5270 if (ESR != ESR_Succeeded) { 5271 if (ESR != ESR_Failed && !ForScope.destroy()) 5272 return ESR_Failed; 5273 return ESR; 5274 } 5275 } 5276 while (true) { 5277 BlockScopeRAII IterScope(Info); 5278 bool Continue = true; 5279 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5280 FS->getCond(), Continue)) 5281 return ESR_Failed; 5282 if (!Continue) 5283 break; 5284 5285 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5286 if (ESR != ESR_Continue) { 5287 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5288 return ESR_Failed; 5289 return ESR; 5290 } 5291 5292 if (const auto *Inc = FS->getInc()) { 5293 if (Inc->isValueDependent()) { 5294 if (!EvaluateDependentExpr(Inc, Info)) 5295 return ESR_Failed; 5296 } else { 5297 FullExpressionRAII IncScope(Info); 5298 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5299 return ESR_Failed; 5300 } 5301 } 5302 5303 if (!IterScope.destroy()) 5304 return ESR_Failed; 5305 } 5306 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5307 } 5308 5309 case Stmt::CXXForRangeStmtClass: { 5310 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5311 BlockScopeRAII Scope(Info); 5312 5313 // Evaluate the init-statement if present. 5314 if (FS->getInit()) { 5315 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5316 if (ESR != ESR_Succeeded) { 5317 if (ESR != ESR_Failed && !Scope.destroy()) 5318 return ESR_Failed; 5319 return ESR; 5320 } 5321 } 5322 5323 // Initialize the __range variable. 5324 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5325 if (ESR != ESR_Succeeded) { 5326 if (ESR != ESR_Failed && !Scope.destroy()) 5327 return ESR_Failed; 5328 return ESR; 5329 } 5330 5331 // In error-recovery cases it's possible to get here even if we failed to 5332 // synthesize the __begin and __end variables. 5333 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5334 return ESR_Failed; 5335 5336 // Create the __begin and __end iterators. 5337 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5338 if (ESR != ESR_Succeeded) { 5339 if (ESR != ESR_Failed && !Scope.destroy()) 5340 return ESR_Failed; 5341 return ESR; 5342 } 5343 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5344 if (ESR != ESR_Succeeded) { 5345 if (ESR != ESR_Failed && !Scope.destroy()) 5346 return ESR_Failed; 5347 return ESR; 5348 } 5349 5350 while (true) { 5351 // Condition: __begin != __end. 5352 { 5353 if (FS->getCond()->isValueDependent()) { 5354 EvaluateDependentExpr(FS->getCond(), Info); 5355 // We don't know whether to keep going or terminate the loop. 5356 return ESR_Failed; 5357 } 5358 bool Continue = true; 5359 FullExpressionRAII CondExpr(Info); 5360 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5361 return ESR_Failed; 5362 if (!Continue) 5363 break; 5364 } 5365 5366 // User's variable declaration, initialized by *__begin. 5367 BlockScopeRAII InnerScope(Info); 5368 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5369 if (ESR != ESR_Succeeded) { 5370 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5371 return ESR_Failed; 5372 return ESR; 5373 } 5374 5375 // Loop body. 5376 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5377 if (ESR != ESR_Continue) { 5378 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5379 return ESR_Failed; 5380 return ESR; 5381 } 5382 if (FS->getInc()->isValueDependent()) { 5383 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5384 return ESR_Failed; 5385 } else { 5386 // Increment: ++__begin 5387 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5388 return ESR_Failed; 5389 } 5390 5391 if (!InnerScope.destroy()) 5392 return ESR_Failed; 5393 } 5394 5395 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5396 } 5397 5398 case Stmt::SwitchStmtClass: 5399 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5400 5401 case Stmt::ContinueStmtClass: 5402 return ESR_Continue; 5403 5404 case Stmt::BreakStmtClass: 5405 return ESR_Break; 5406 5407 case Stmt::LabelStmtClass: 5408 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5409 5410 case Stmt::AttributedStmtClass: 5411 // As a general principle, C++11 attributes can be ignored without 5412 // any semantic impact. 5413 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5414 Case); 5415 5416 case Stmt::CaseStmtClass: 5417 case Stmt::DefaultStmtClass: 5418 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5419 case Stmt::CXXTryStmtClass: 5420 // Evaluate try blocks by evaluating all sub statements. 5421 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5422 } 5423 } 5424 5425 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5426 /// default constructor. If so, we'll fold it whether or not it's marked as 5427 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5428 /// so we need special handling. 5429 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5430 const CXXConstructorDecl *CD, 5431 bool IsValueInitialization) { 5432 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5433 return false; 5434 5435 // Value-initialization does not call a trivial default constructor, so such a 5436 // call is a core constant expression whether or not the constructor is 5437 // constexpr. 5438 if (!CD->isConstexpr() && !IsValueInitialization) { 5439 if (Info.getLangOpts().CPlusPlus11) { 5440 // FIXME: If DiagDecl is an implicitly-declared special member function, 5441 // we should be much more explicit about why it's not constexpr. 5442 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5443 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5444 Info.Note(CD->getLocation(), diag::note_declared_at); 5445 } else { 5446 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5447 } 5448 } 5449 return true; 5450 } 5451 5452 /// CheckConstexprFunction - Check that a function can be called in a constant 5453 /// expression. 5454 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5455 const FunctionDecl *Declaration, 5456 const FunctionDecl *Definition, 5457 const Stmt *Body) { 5458 // Potential constant expressions can contain calls to declared, but not yet 5459 // defined, constexpr functions. 5460 if (Info.checkingPotentialConstantExpression() && !Definition && 5461 Declaration->isConstexpr()) 5462 return false; 5463 5464 // Bail out if the function declaration itself is invalid. We will 5465 // have produced a relevant diagnostic while parsing it, so just 5466 // note the problematic sub-expression. 5467 if (Declaration->isInvalidDecl()) { 5468 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5469 return false; 5470 } 5471 5472 // DR1872: An instantiated virtual constexpr function can't be called in a 5473 // constant expression (prior to C++20). We can still constant-fold such a 5474 // call. 5475 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5476 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5477 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5478 5479 if (Definition && Definition->isInvalidDecl()) { 5480 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5481 return false; 5482 } 5483 5484 // Can we evaluate this function call? 5485 if (Definition && Definition->isConstexpr() && Body) 5486 return true; 5487 5488 if (Info.getLangOpts().CPlusPlus11) { 5489 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5490 5491 // If this function is not constexpr because it is an inherited 5492 // non-constexpr constructor, diagnose that directly. 5493 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5494 if (CD && CD->isInheritingConstructor()) { 5495 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5496 if (!Inherited->isConstexpr()) 5497 DiagDecl = CD = Inherited; 5498 } 5499 5500 // FIXME: If DiagDecl is an implicitly-declared special member function 5501 // or an inheriting constructor, we should be much more explicit about why 5502 // it's not constexpr. 5503 if (CD && CD->isInheritingConstructor()) 5504 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5505 << CD->getInheritedConstructor().getConstructor()->getParent(); 5506 else 5507 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5508 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5509 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5510 } else { 5511 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5512 } 5513 return false; 5514 } 5515 5516 namespace { 5517 struct CheckDynamicTypeHandler { 5518 AccessKinds AccessKind; 5519 typedef bool result_type; 5520 bool failed() { return false; } 5521 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5522 bool found(APSInt &Value, QualType SubobjType) { return true; } 5523 bool found(APFloat &Value, QualType SubobjType) { return true; } 5524 }; 5525 } // end anonymous namespace 5526 5527 /// Check that we can access the notional vptr of an object / determine its 5528 /// dynamic type. 5529 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5530 AccessKinds AK, bool Polymorphic) { 5531 if (This.Designator.Invalid) 5532 return false; 5533 5534 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5535 5536 if (!Obj) 5537 return false; 5538 5539 if (!Obj.Value) { 5540 // The object is not usable in constant expressions, so we can't inspect 5541 // its value to see if it's in-lifetime or what the active union members 5542 // are. We can still check for a one-past-the-end lvalue. 5543 if (This.Designator.isOnePastTheEnd() || 5544 This.Designator.isMostDerivedAnUnsizedArray()) { 5545 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5546 ? diag::note_constexpr_access_past_end 5547 : diag::note_constexpr_access_unsized_array) 5548 << AK; 5549 return false; 5550 } else if (Polymorphic) { 5551 // Conservatively refuse to perform a polymorphic operation if we would 5552 // not be able to read a notional 'vptr' value. 5553 APValue Val; 5554 This.moveInto(Val); 5555 QualType StarThisType = 5556 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5557 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5558 << AK << Val.getAsString(Info.Ctx, StarThisType); 5559 return false; 5560 } 5561 return true; 5562 } 5563 5564 CheckDynamicTypeHandler Handler{AK}; 5565 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5566 } 5567 5568 /// Check that the pointee of the 'this' pointer in a member function call is 5569 /// either within its lifetime or in its period of construction or destruction. 5570 static bool 5571 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5572 const LValue &This, 5573 const CXXMethodDecl *NamedMember) { 5574 return checkDynamicType( 5575 Info, E, This, 5576 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5577 } 5578 5579 struct DynamicType { 5580 /// The dynamic class type of the object. 5581 const CXXRecordDecl *Type; 5582 /// The corresponding path length in the lvalue. 5583 unsigned PathLength; 5584 }; 5585 5586 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5587 unsigned PathLength) { 5588 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5589 Designator.Entries.size() && "invalid path length"); 5590 return (PathLength == Designator.MostDerivedPathLength) 5591 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5592 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5593 } 5594 5595 /// Determine the dynamic type of an object. 5596 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5597 LValue &This, AccessKinds AK) { 5598 // If we don't have an lvalue denoting an object of class type, there is no 5599 // meaningful dynamic type. (We consider objects of non-class type to have no 5600 // dynamic type.) 5601 if (!checkDynamicType(Info, E, This, AK, true)) 5602 return None; 5603 5604 // Refuse to compute a dynamic type in the presence of virtual bases. This 5605 // shouldn't happen other than in constant-folding situations, since literal 5606 // types can't have virtual bases. 5607 // 5608 // Note that consumers of DynamicType assume that the type has no virtual 5609 // bases, and will need modifications if this restriction is relaxed. 5610 const CXXRecordDecl *Class = 5611 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5612 if (!Class || Class->getNumVBases()) { 5613 Info.FFDiag(E); 5614 return None; 5615 } 5616 5617 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5618 // binary search here instead. But the overwhelmingly common case is that 5619 // we're not in the middle of a constructor, so it probably doesn't matter 5620 // in practice. 5621 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5622 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5623 PathLength <= Path.size(); ++PathLength) { 5624 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5625 Path.slice(0, PathLength))) { 5626 case ConstructionPhase::Bases: 5627 case ConstructionPhase::DestroyingBases: 5628 // We're constructing or destroying a base class. This is not the dynamic 5629 // type. 5630 break; 5631 5632 case ConstructionPhase::None: 5633 case ConstructionPhase::AfterBases: 5634 case ConstructionPhase::AfterFields: 5635 case ConstructionPhase::Destroying: 5636 // We've finished constructing the base classes and not yet started 5637 // destroying them again, so this is the dynamic type. 5638 return DynamicType{getBaseClassType(This.Designator, PathLength), 5639 PathLength}; 5640 } 5641 } 5642 5643 // CWG issue 1517: we're constructing a base class of the object described by 5644 // 'This', so that object has not yet begun its period of construction and 5645 // any polymorphic operation on it results in undefined behavior. 5646 Info.FFDiag(E); 5647 return None; 5648 } 5649 5650 /// Perform virtual dispatch. 5651 static const CXXMethodDecl *HandleVirtualDispatch( 5652 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5653 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5654 Optional<DynamicType> DynType = ComputeDynamicType( 5655 Info, E, This, 5656 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5657 if (!DynType) 5658 return nullptr; 5659 5660 // Find the final overrider. It must be declared in one of the classes on the 5661 // path from the dynamic type to the static type. 5662 // FIXME: If we ever allow literal types to have virtual base classes, that 5663 // won't be true. 5664 const CXXMethodDecl *Callee = Found; 5665 unsigned PathLength = DynType->PathLength; 5666 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5667 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5668 const CXXMethodDecl *Overrider = 5669 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5670 if (Overrider) { 5671 Callee = Overrider; 5672 break; 5673 } 5674 } 5675 5676 // C++2a [class.abstract]p6: 5677 // the effect of making a virtual call to a pure virtual function [...] is 5678 // undefined 5679 if (Callee->isPure()) { 5680 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5681 Info.Note(Callee->getLocation(), diag::note_declared_at); 5682 return nullptr; 5683 } 5684 5685 // If necessary, walk the rest of the path to determine the sequence of 5686 // covariant adjustment steps to apply. 5687 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5688 Found->getReturnType())) { 5689 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5690 for (unsigned CovariantPathLength = PathLength + 1; 5691 CovariantPathLength != This.Designator.Entries.size(); 5692 ++CovariantPathLength) { 5693 const CXXRecordDecl *NextClass = 5694 getBaseClassType(This.Designator, CovariantPathLength); 5695 const CXXMethodDecl *Next = 5696 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5697 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5698 Next->getReturnType(), CovariantAdjustmentPath.back())) 5699 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5700 } 5701 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5702 CovariantAdjustmentPath.back())) 5703 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5704 } 5705 5706 // Perform 'this' adjustment. 5707 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5708 return nullptr; 5709 5710 return Callee; 5711 } 5712 5713 /// Perform the adjustment from a value returned by a virtual function to 5714 /// a value of the statically expected type, which may be a pointer or 5715 /// reference to a base class of the returned type. 5716 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5717 APValue &Result, 5718 ArrayRef<QualType> Path) { 5719 assert(Result.isLValue() && 5720 "unexpected kind of APValue for covariant return"); 5721 if (Result.isNullPointer()) 5722 return true; 5723 5724 LValue LVal; 5725 LVal.setFrom(Info.Ctx, Result); 5726 5727 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5728 for (unsigned I = 1; I != Path.size(); ++I) { 5729 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5730 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5731 if (OldClass != NewClass && 5732 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5733 return false; 5734 OldClass = NewClass; 5735 } 5736 5737 LVal.moveInto(Result); 5738 return true; 5739 } 5740 5741 /// Determine whether \p Base, which is known to be a direct base class of 5742 /// \p Derived, is a public base class. 5743 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5744 const CXXRecordDecl *Base) { 5745 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5746 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5747 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5748 return BaseSpec.getAccessSpecifier() == AS_public; 5749 } 5750 llvm_unreachable("Base is not a direct base of Derived"); 5751 } 5752 5753 /// Apply the given dynamic cast operation on the provided lvalue. 5754 /// 5755 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5756 /// to find a suitable target subobject. 5757 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5758 LValue &Ptr) { 5759 // We can't do anything with a non-symbolic pointer value. 5760 SubobjectDesignator &D = Ptr.Designator; 5761 if (D.Invalid) 5762 return false; 5763 5764 // C++ [expr.dynamic.cast]p6: 5765 // If v is a null pointer value, the result is a null pointer value. 5766 if (Ptr.isNullPointer() && !E->isGLValue()) 5767 return true; 5768 5769 // For all the other cases, we need the pointer to point to an object within 5770 // its lifetime / period of construction / destruction, and we need to know 5771 // its dynamic type. 5772 Optional<DynamicType> DynType = 5773 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5774 if (!DynType) 5775 return false; 5776 5777 // C++ [expr.dynamic.cast]p7: 5778 // If T is "pointer to cv void", then the result is a pointer to the most 5779 // derived object 5780 if (E->getType()->isVoidPointerType()) 5781 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5782 5783 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5784 assert(C && "dynamic_cast target is not void pointer nor class"); 5785 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5786 5787 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5788 // C++ [expr.dynamic.cast]p9: 5789 if (!E->isGLValue()) { 5790 // The value of a failed cast to pointer type is the null pointer value 5791 // of the required result type. 5792 Ptr.setNull(Info.Ctx, E->getType()); 5793 return true; 5794 } 5795 5796 // A failed cast to reference type throws [...] std::bad_cast. 5797 unsigned DiagKind; 5798 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5799 DynType->Type->isDerivedFrom(C))) 5800 DiagKind = 0; 5801 else if (!Paths || Paths->begin() == Paths->end()) 5802 DiagKind = 1; 5803 else if (Paths->isAmbiguous(CQT)) 5804 DiagKind = 2; 5805 else { 5806 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5807 DiagKind = 3; 5808 } 5809 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5810 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5811 << Info.Ctx.getRecordType(DynType->Type) 5812 << E->getType().getUnqualifiedType(); 5813 return false; 5814 }; 5815 5816 // Runtime check, phase 1: 5817 // Walk from the base subobject towards the derived object looking for the 5818 // target type. 5819 for (int PathLength = Ptr.Designator.Entries.size(); 5820 PathLength >= (int)DynType->PathLength; --PathLength) { 5821 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5822 if (declaresSameEntity(Class, C)) 5823 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5824 // We can only walk across public inheritance edges. 5825 if (PathLength > (int)DynType->PathLength && 5826 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5827 Class)) 5828 return RuntimeCheckFailed(nullptr); 5829 } 5830 5831 // Runtime check, phase 2: 5832 // Search the dynamic type for an unambiguous public base of type C. 5833 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5834 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5835 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5836 Paths.front().Access == AS_public) { 5837 // Downcast to the dynamic type... 5838 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5839 return false; 5840 // ... then upcast to the chosen base class subobject. 5841 for (CXXBasePathElement &Elem : Paths.front()) 5842 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5843 return false; 5844 return true; 5845 } 5846 5847 // Otherwise, the runtime check fails. 5848 return RuntimeCheckFailed(&Paths); 5849 } 5850 5851 namespace { 5852 struct StartLifetimeOfUnionMemberHandler { 5853 EvalInfo &Info; 5854 const Expr *LHSExpr; 5855 const FieldDecl *Field; 5856 bool DuringInit; 5857 bool Failed = false; 5858 static const AccessKinds AccessKind = AK_Assign; 5859 5860 typedef bool result_type; 5861 bool failed() { return Failed; } 5862 bool found(APValue &Subobj, QualType SubobjType) { 5863 // We are supposed to perform no initialization but begin the lifetime of 5864 // the object. We interpret that as meaning to do what default 5865 // initialization of the object would do if all constructors involved were 5866 // trivial: 5867 // * All base, non-variant member, and array element subobjects' lifetimes 5868 // begin 5869 // * No variant members' lifetimes begin 5870 // * All scalar subobjects whose lifetimes begin have indeterminate values 5871 assert(SubobjType->isUnionType()); 5872 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5873 // This union member is already active. If it's also in-lifetime, there's 5874 // nothing to do. 5875 if (Subobj.getUnionValue().hasValue()) 5876 return true; 5877 } else if (DuringInit) { 5878 // We're currently in the process of initializing a different union 5879 // member. If we carried on, that initialization would attempt to 5880 // store to an inactive union member, resulting in undefined behavior. 5881 Info.FFDiag(LHSExpr, 5882 diag::note_constexpr_union_member_change_during_init); 5883 return false; 5884 } 5885 APValue Result; 5886 Failed = !getDefaultInitValue(Field->getType(), Result); 5887 Subobj.setUnion(Field, Result); 5888 return true; 5889 } 5890 bool found(APSInt &Value, QualType SubobjType) { 5891 llvm_unreachable("wrong value kind for union object"); 5892 } 5893 bool found(APFloat &Value, QualType SubobjType) { 5894 llvm_unreachable("wrong value kind for union object"); 5895 } 5896 }; 5897 } // end anonymous namespace 5898 5899 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5900 5901 /// Handle a builtin simple-assignment or a call to a trivial assignment 5902 /// operator whose left-hand side might involve a union member access. If it 5903 /// does, implicitly start the lifetime of any accessed union elements per 5904 /// C++20 [class.union]5. 5905 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5906 const LValue &LHS) { 5907 if (LHS.InvalidBase || LHS.Designator.Invalid) 5908 return false; 5909 5910 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5911 // C++ [class.union]p5: 5912 // define the set S(E) of subexpressions of E as follows: 5913 unsigned PathLength = LHS.Designator.Entries.size(); 5914 for (const Expr *E = LHSExpr; E != nullptr;) { 5915 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5916 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5917 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5918 // Note that we can't implicitly start the lifetime of a reference, 5919 // so we don't need to proceed any further if we reach one. 5920 if (!FD || FD->getType()->isReferenceType()) 5921 break; 5922 5923 // ... and also contains A.B if B names a union member ... 5924 if (FD->getParent()->isUnion()) { 5925 // ... of a non-class, non-array type, or of a class type with a 5926 // trivial default constructor that is not deleted, or an array of 5927 // such types. 5928 auto *RD = 5929 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5930 if (!RD || RD->hasTrivialDefaultConstructor()) 5931 UnionPathLengths.push_back({PathLength - 1, FD}); 5932 } 5933 5934 E = ME->getBase(); 5935 --PathLength; 5936 assert(declaresSameEntity(FD, 5937 LHS.Designator.Entries[PathLength] 5938 .getAsBaseOrMember().getPointer())); 5939 5940 // -- If E is of the form A[B] and is interpreted as a built-in array 5941 // subscripting operator, S(E) is [S(the array operand, if any)]. 5942 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5943 // Step over an ArrayToPointerDecay implicit cast. 5944 auto *Base = ASE->getBase()->IgnoreImplicit(); 5945 if (!Base->getType()->isArrayType()) 5946 break; 5947 5948 E = Base; 5949 --PathLength; 5950 5951 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5952 // Step over a derived-to-base conversion. 5953 E = ICE->getSubExpr(); 5954 if (ICE->getCastKind() == CK_NoOp) 5955 continue; 5956 if (ICE->getCastKind() != CK_DerivedToBase && 5957 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5958 break; 5959 // Walk path backwards as we walk up from the base to the derived class. 5960 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5961 --PathLength; 5962 (void)Elt; 5963 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5964 LHS.Designator.Entries[PathLength] 5965 .getAsBaseOrMember().getPointer())); 5966 } 5967 5968 // -- Otherwise, S(E) is empty. 5969 } else { 5970 break; 5971 } 5972 } 5973 5974 // Common case: no unions' lifetimes are started. 5975 if (UnionPathLengths.empty()) 5976 return true; 5977 5978 // if modification of X [would access an inactive union member], an object 5979 // of the type of X is implicitly created 5980 CompleteObject Obj = 5981 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5982 if (!Obj) 5983 return false; 5984 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5985 llvm::reverse(UnionPathLengths)) { 5986 // Form a designator for the union object. 5987 SubobjectDesignator D = LHS.Designator; 5988 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5989 5990 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5991 ConstructionPhase::AfterBases; 5992 StartLifetimeOfUnionMemberHandler StartLifetime{ 5993 Info, LHSExpr, LengthAndField.second, DuringInit}; 5994 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5995 return false; 5996 } 5997 5998 return true; 5999 } 6000 6001 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6002 CallRef Call, EvalInfo &Info, 6003 bool NonNull = false) { 6004 LValue LV; 6005 // Create the parameter slot and register its destruction. For a vararg 6006 // argument, create a temporary. 6007 // FIXME: For calling conventions that destroy parameters in the callee, 6008 // should we consider performing destruction when the function returns 6009 // instead? 6010 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6011 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6012 ScopeKind::Call, LV); 6013 if (!EvaluateInPlace(V, Info, LV, Arg)) 6014 return false; 6015 6016 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6017 // undefined behavior, so is non-constant. 6018 if (NonNull && V.isLValue() && V.isNullPointer()) { 6019 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6020 return false; 6021 } 6022 6023 return true; 6024 } 6025 6026 /// Evaluate the arguments to a function call. 6027 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6028 EvalInfo &Info, const FunctionDecl *Callee, 6029 bool RightToLeft = false) { 6030 bool Success = true; 6031 llvm::SmallBitVector ForbiddenNullArgs; 6032 if (Callee->hasAttr<NonNullAttr>()) { 6033 ForbiddenNullArgs.resize(Args.size()); 6034 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6035 if (!Attr->args_size()) { 6036 ForbiddenNullArgs.set(); 6037 break; 6038 } else 6039 for (auto Idx : Attr->args()) { 6040 unsigned ASTIdx = Idx.getASTIndex(); 6041 if (ASTIdx >= Args.size()) 6042 continue; 6043 ForbiddenNullArgs[ASTIdx] = 1; 6044 } 6045 } 6046 } 6047 for (unsigned I = 0; I < Args.size(); I++) { 6048 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6049 const ParmVarDecl *PVD = 6050 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6051 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6052 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6053 // If we're checking for a potential constant expression, evaluate all 6054 // initializers even if some of them fail. 6055 if (!Info.noteFailure()) 6056 return false; 6057 Success = false; 6058 } 6059 } 6060 return Success; 6061 } 6062 6063 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6064 /// constructor or assignment operator. 6065 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6066 const Expr *E, APValue &Result, 6067 bool CopyObjectRepresentation) { 6068 // Find the reference argument. 6069 CallStackFrame *Frame = Info.CurrentCall; 6070 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6071 if (!RefValue) { 6072 Info.FFDiag(E); 6073 return false; 6074 } 6075 6076 // Copy out the contents of the RHS object. 6077 LValue RefLValue; 6078 RefLValue.setFrom(Info.Ctx, *RefValue); 6079 return handleLValueToRValueConversion( 6080 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6081 CopyObjectRepresentation); 6082 } 6083 6084 /// Evaluate a function call. 6085 static bool HandleFunctionCall(SourceLocation CallLoc, 6086 const FunctionDecl *Callee, const LValue *This, 6087 ArrayRef<const Expr *> Args, CallRef Call, 6088 const Stmt *Body, EvalInfo &Info, 6089 APValue &Result, const LValue *ResultSlot) { 6090 if (!Info.CheckCallLimit(CallLoc)) 6091 return false; 6092 6093 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6094 6095 // For a trivial copy or move assignment, perform an APValue copy. This is 6096 // essential for unions, where the operations performed by the assignment 6097 // operator cannot be represented as statements. 6098 // 6099 // Skip this for non-union classes with no fields; in that case, the defaulted 6100 // copy/move does not actually read the object. 6101 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6102 if (MD && MD->isDefaulted() && 6103 (MD->getParent()->isUnion() || 6104 (MD->isTrivial() && 6105 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6106 assert(This && 6107 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6108 APValue RHSValue; 6109 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6110 MD->getParent()->isUnion())) 6111 return false; 6112 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6113 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6114 return false; 6115 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6116 RHSValue)) 6117 return false; 6118 This->moveInto(Result); 6119 return true; 6120 } else if (MD && isLambdaCallOperator(MD)) { 6121 // We're in a lambda; determine the lambda capture field maps unless we're 6122 // just constexpr checking a lambda's call operator. constexpr checking is 6123 // done before the captures have been added to the closure object (unless 6124 // we're inferring constexpr-ness), so we don't have access to them in this 6125 // case. But since we don't need the captures to constexpr check, we can 6126 // just ignore them. 6127 if (!Info.checkingPotentialConstantExpression()) 6128 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6129 Frame.LambdaThisCaptureField); 6130 } 6131 6132 StmtResult Ret = {Result, ResultSlot}; 6133 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6134 if (ESR == ESR_Succeeded) { 6135 if (Callee->getReturnType()->isVoidType()) 6136 return true; 6137 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6138 } 6139 return ESR == ESR_Returned; 6140 } 6141 6142 /// Evaluate a constructor call. 6143 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6144 CallRef Call, 6145 const CXXConstructorDecl *Definition, 6146 EvalInfo &Info, APValue &Result) { 6147 SourceLocation CallLoc = E->getExprLoc(); 6148 if (!Info.CheckCallLimit(CallLoc)) 6149 return false; 6150 6151 const CXXRecordDecl *RD = Definition->getParent(); 6152 if (RD->getNumVBases()) { 6153 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6154 return false; 6155 } 6156 6157 EvalInfo::EvaluatingConstructorRAII EvalObj( 6158 Info, 6159 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6160 RD->getNumBases()); 6161 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6162 6163 // FIXME: Creating an APValue just to hold a nonexistent return value is 6164 // wasteful. 6165 APValue RetVal; 6166 StmtResult Ret = {RetVal, nullptr}; 6167 6168 // If it's a delegating constructor, delegate. 6169 if (Definition->isDelegatingConstructor()) { 6170 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6171 if ((*I)->getInit()->isValueDependent()) { 6172 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6173 return false; 6174 } else { 6175 FullExpressionRAII InitScope(Info); 6176 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6177 !InitScope.destroy()) 6178 return false; 6179 } 6180 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6181 } 6182 6183 // For a trivial copy or move constructor, perform an APValue copy. This is 6184 // essential for unions (or classes with anonymous union members), where the 6185 // operations performed by the constructor cannot be represented by 6186 // ctor-initializers. 6187 // 6188 // Skip this for empty non-union classes; we should not perform an 6189 // lvalue-to-rvalue conversion on them because their copy constructor does not 6190 // actually read them. 6191 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6192 (Definition->getParent()->isUnion() || 6193 (Definition->isTrivial() && 6194 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6195 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6196 Definition->getParent()->isUnion()); 6197 } 6198 6199 // Reserve space for the struct members. 6200 if (!Result.hasValue()) { 6201 if (!RD->isUnion()) 6202 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6203 std::distance(RD->field_begin(), RD->field_end())); 6204 else 6205 // A union starts with no active member. 6206 Result = APValue((const FieldDecl*)nullptr); 6207 } 6208 6209 if (RD->isInvalidDecl()) return false; 6210 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6211 6212 // A scope for temporaries lifetime-extended by reference members. 6213 BlockScopeRAII LifetimeExtendedScope(Info); 6214 6215 bool Success = true; 6216 unsigned BasesSeen = 0; 6217 #ifndef NDEBUG 6218 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6219 #endif 6220 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6221 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6222 // We might be initializing the same field again if this is an indirect 6223 // field initialization. 6224 if (FieldIt == RD->field_end() || 6225 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6226 assert(Indirect && "fields out of order?"); 6227 return; 6228 } 6229 6230 // Default-initialize any fields with no explicit initializer. 6231 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6232 assert(FieldIt != RD->field_end() && "missing field?"); 6233 if (!FieldIt->isUnnamedBitfield()) 6234 Success &= getDefaultInitValue( 6235 FieldIt->getType(), 6236 Result.getStructField(FieldIt->getFieldIndex())); 6237 } 6238 ++FieldIt; 6239 }; 6240 for (const auto *I : Definition->inits()) { 6241 LValue Subobject = This; 6242 LValue SubobjectParent = This; 6243 APValue *Value = &Result; 6244 6245 // Determine the subobject to initialize. 6246 FieldDecl *FD = nullptr; 6247 if (I->isBaseInitializer()) { 6248 QualType BaseType(I->getBaseClass(), 0); 6249 #ifndef NDEBUG 6250 // Non-virtual base classes are initialized in the order in the class 6251 // definition. We have already checked for virtual base classes. 6252 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6253 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6254 "base class initializers not in expected order"); 6255 ++BaseIt; 6256 #endif 6257 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6258 BaseType->getAsCXXRecordDecl(), &Layout)) 6259 return false; 6260 Value = &Result.getStructBase(BasesSeen++); 6261 } else if ((FD = I->getMember())) { 6262 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6263 return false; 6264 if (RD->isUnion()) { 6265 Result = APValue(FD); 6266 Value = &Result.getUnionValue(); 6267 } else { 6268 SkipToField(FD, false); 6269 Value = &Result.getStructField(FD->getFieldIndex()); 6270 } 6271 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6272 // Walk the indirect field decl's chain to find the object to initialize, 6273 // and make sure we've initialized every step along it. 6274 auto IndirectFieldChain = IFD->chain(); 6275 for (auto *C : IndirectFieldChain) { 6276 FD = cast<FieldDecl>(C); 6277 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6278 // Switch the union field if it differs. This happens if we had 6279 // preceding zero-initialization, and we're now initializing a union 6280 // subobject other than the first. 6281 // FIXME: In this case, the values of the other subobjects are 6282 // specified, since zero-initialization sets all padding bits to zero. 6283 if (!Value->hasValue() || 6284 (Value->isUnion() && Value->getUnionField() != FD)) { 6285 if (CD->isUnion()) 6286 *Value = APValue(FD); 6287 else 6288 // FIXME: This immediately starts the lifetime of all members of 6289 // an anonymous struct. It would be preferable to strictly start 6290 // member lifetime in initialization order. 6291 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6292 } 6293 // Store Subobject as its parent before updating it for the last element 6294 // in the chain. 6295 if (C == IndirectFieldChain.back()) 6296 SubobjectParent = Subobject; 6297 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6298 return false; 6299 if (CD->isUnion()) 6300 Value = &Value->getUnionValue(); 6301 else { 6302 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6303 SkipToField(FD, true); 6304 Value = &Value->getStructField(FD->getFieldIndex()); 6305 } 6306 } 6307 } else { 6308 llvm_unreachable("unknown base initializer kind"); 6309 } 6310 6311 // Need to override This for implicit field initializers as in this case 6312 // This refers to innermost anonymous struct/union containing initializer, 6313 // not to currently constructed class. 6314 const Expr *Init = I->getInit(); 6315 if (Init->isValueDependent()) { 6316 if (!EvaluateDependentExpr(Init, Info)) 6317 return false; 6318 } else { 6319 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6320 isa<CXXDefaultInitExpr>(Init)); 6321 FullExpressionRAII InitScope(Info); 6322 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6323 (FD && FD->isBitField() && 6324 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6325 // If we're checking for a potential constant expression, evaluate all 6326 // initializers even if some of them fail. 6327 if (!Info.noteFailure()) 6328 return false; 6329 Success = false; 6330 } 6331 } 6332 6333 // This is the point at which the dynamic type of the object becomes this 6334 // class type. 6335 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6336 EvalObj.finishedConstructingBases(); 6337 } 6338 6339 // Default-initialize any remaining fields. 6340 if (!RD->isUnion()) { 6341 for (; FieldIt != RD->field_end(); ++FieldIt) { 6342 if (!FieldIt->isUnnamedBitfield()) 6343 Success &= getDefaultInitValue( 6344 FieldIt->getType(), 6345 Result.getStructField(FieldIt->getFieldIndex())); 6346 } 6347 } 6348 6349 EvalObj.finishedConstructingFields(); 6350 6351 return Success && 6352 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6353 LifetimeExtendedScope.destroy(); 6354 } 6355 6356 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6357 ArrayRef<const Expr*> Args, 6358 const CXXConstructorDecl *Definition, 6359 EvalInfo &Info, APValue &Result) { 6360 CallScopeRAII CallScope(Info); 6361 CallRef Call = Info.CurrentCall->createCall(Definition); 6362 if (!EvaluateArgs(Args, Call, Info, Definition)) 6363 return false; 6364 6365 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6366 CallScope.destroy(); 6367 } 6368 6369 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6370 const LValue &This, APValue &Value, 6371 QualType T) { 6372 // Objects can only be destroyed while they're within their lifetimes. 6373 // FIXME: We have no representation for whether an object of type nullptr_t 6374 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6375 // as indeterminate instead? 6376 if (Value.isAbsent() && !T->isNullPtrType()) { 6377 APValue Printable; 6378 This.moveInto(Printable); 6379 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6380 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6381 return false; 6382 } 6383 6384 // Invent an expression for location purposes. 6385 // FIXME: We shouldn't need to do this. 6386 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6387 6388 // For arrays, destroy elements right-to-left. 6389 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6390 uint64_t Size = CAT->getSize().getZExtValue(); 6391 QualType ElemT = CAT->getElementType(); 6392 6393 LValue ElemLV = This; 6394 ElemLV.addArray(Info, &LocE, CAT); 6395 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6396 return false; 6397 6398 // Ensure that we have actual array elements available to destroy; the 6399 // destructors might mutate the value, so we can't run them on the array 6400 // filler. 6401 if (Size && Size > Value.getArrayInitializedElts()) 6402 expandArray(Value, Value.getArraySize() - 1); 6403 6404 for (; Size != 0; --Size) { 6405 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6406 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6407 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6408 return false; 6409 } 6410 6411 // End the lifetime of this array now. 6412 Value = APValue(); 6413 return true; 6414 } 6415 6416 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6417 if (!RD) { 6418 if (T.isDestructedType()) { 6419 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6420 return false; 6421 } 6422 6423 Value = APValue(); 6424 return true; 6425 } 6426 6427 if (RD->getNumVBases()) { 6428 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6429 return false; 6430 } 6431 6432 const CXXDestructorDecl *DD = RD->getDestructor(); 6433 if (!DD && !RD->hasTrivialDestructor()) { 6434 Info.FFDiag(CallLoc); 6435 return false; 6436 } 6437 6438 if (!DD || DD->isTrivial() || 6439 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6440 // A trivial destructor just ends the lifetime of the object. Check for 6441 // this case before checking for a body, because we might not bother 6442 // building a body for a trivial destructor. Note that it doesn't matter 6443 // whether the destructor is constexpr in this case; all trivial 6444 // destructors are constexpr. 6445 // 6446 // If an anonymous union would be destroyed, some enclosing destructor must 6447 // have been explicitly defined, and the anonymous union destruction should 6448 // have no effect. 6449 Value = APValue(); 6450 return true; 6451 } 6452 6453 if (!Info.CheckCallLimit(CallLoc)) 6454 return false; 6455 6456 const FunctionDecl *Definition = nullptr; 6457 const Stmt *Body = DD->getBody(Definition); 6458 6459 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6460 return false; 6461 6462 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6463 6464 // We're now in the period of destruction of this object. 6465 unsigned BasesLeft = RD->getNumBases(); 6466 EvalInfo::EvaluatingDestructorRAII EvalObj( 6467 Info, 6468 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6469 if (!EvalObj.DidInsert) { 6470 // C++2a [class.dtor]p19: 6471 // the behavior is undefined if the destructor is invoked for an object 6472 // whose lifetime has ended 6473 // (Note that formally the lifetime ends when the period of destruction 6474 // begins, even though certain uses of the object remain valid until the 6475 // period of destruction ends.) 6476 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6477 return false; 6478 } 6479 6480 // FIXME: Creating an APValue just to hold a nonexistent return value is 6481 // wasteful. 6482 APValue RetVal; 6483 StmtResult Ret = {RetVal, nullptr}; 6484 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6485 return false; 6486 6487 // A union destructor does not implicitly destroy its members. 6488 if (RD->isUnion()) 6489 return true; 6490 6491 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6492 6493 // We don't have a good way to iterate fields in reverse, so collect all the 6494 // fields first and then walk them backwards. 6495 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6496 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6497 if (FD->isUnnamedBitfield()) 6498 continue; 6499 6500 LValue Subobject = This; 6501 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6502 return false; 6503 6504 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6505 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6506 FD->getType())) 6507 return false; 6508 } 6509 6510 if (BasesLeft != 0) 6511 EvalObj.startedDestroyingBases(); 6512 6513 // Destroy base classes in reverse order. 6514 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6515 --BasesLeft; 6516 6517 QualType BaseType = Base.getType(); 6518 LValue Subobject = This; 6519 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6520 BaseType->getAsCXXRecordDecl(), &Layout)) 6521 return false; 6522 6523 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6524 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6525 BaseType)) 6526 return false; 6527 } 6528 assert(BasesLeft == 0 && "NumBases was wrong?"); 6529 6530 // The period of destruction ends now. The object is gone. 6531 Value = APValue(); 6532 return true; 6533 } 6534 6535 namespace { 6536 struct DestroyObjectHandler { 6537 EvalInfo &Info; 6538 const Expr *E; 6539 const LValue &This; 6540 const AccessKinds AccessKind; 6541 6542 typedef bool result_type; 6543 bool failed() { return false; } 6544 bool found(APValue &Subobj, QualType SubobjType) { 6545 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6546 SubobjType); 6547 } 6548 bool found(APSInt &Value, QualType SubobjType) { 6549 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6550 return false; 6551 } 6552 bool found(APFloat &Value, QualType SubobjType) { 6553 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6554 return false; 6555 } 6556 }; 6557 } 6558 6559 /// Perform a destructor or pseudo-destructor call on the given object, which 6560 /// might in general not be a complete object. 6561 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6562 const LValue &This, QualType ThisType) { 6563 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6564 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6565 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6566 } 6567 6568 /// Destroy and end the lifetime of the given complete object. 6569 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6570 APValue::LValueBase LVBase, APValue &Value, 6571 QualType T) { 6572 // If we've had an unmodeled side-effect, we can't rely on mutable state 6573 // (such as the object we're about to destroy) being correct. 6574 if (Info.EvalStatus.HasSideEffects) 6575 return false; 6576 6577 LValue LV; 6578 LV.set({LVBase}); 6579 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6580 } 6581 6582 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6583 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6584 LValue &Result) { 6585 if (Info.checkingPotentialConstantExpression() || 6586 Info.SpeculativeEvaluationDepth) 6587 return false; 6588 6589 // This is permitted only within a call to std::allocator<T>::allocate. 6590 auto Caller = Info.getStdAllocatorCaller("allocate"); 6591 if (!Caller) { 6592 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6593 ? diag::note_constexpr_new_untyped 6594 : diag::note_constexpr_new); 6595 return false; 6596 } 6597 6598 QualType ElemType = Caller.ElemType; 6599 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6600 Info.FFDiag(E->getExprLoc(), 6601 diag::note_constexpr_new_not_complete_object_type) 6602 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6603 return false; 6604 } 6605 6606 APSInt ByteSize; 6607 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6608 return false; 6609 bool IsNothrow = false; 6610 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6611 EvaluateIgnoredValue(Info, E->getArg(I)); 6612 IsNothrow |= E->getType()->isNothrowT(); 6613 } 6614 6615 CharUnits ElemSize; 6616 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6617 return false; 6618 APInt Size, Remainder; 6619 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6620 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6621 if (Remainder != 0) { 6622 // This likely indicates a bug in the implementation of 'std::allocator'. 6623 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6624 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6625 return false; 6626 } 6627 6628 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6629 if (IsNothrow) { 6630 Result.setNull(Info.Ctx, E->getType()); 6631 return true; 6632 } 6633 6634 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6635 return false; 6636 } 6637 6638 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6639 ArrayType::Normal, 0); 6640 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6641 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6642 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6643 return true; 6644 } 6645 6646 static bool hasVirtualDestructor(QualType T) { 6647 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6648 if (CXXDestructorDecl *DD = RD->getDestructor()) 6649 return DD->isVirtual(); 6650 return false; 6651 } 6652 6653 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6654 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6655 if (CXXDestructorDecl *DD = RD->getDestructor()) 6656 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6657 return nullptr; 6658 } 6659 6660 /// Check that the given object is a suitable pointer to a heap allocation that 6661 /// still exists and is of the right kind for the purpose of a deletion. 6662 /// 6663 /// On success, returns the heap allocation to deallocate. On failure, produces 6664 /// a diagnostic and returns None. 6665 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6666 const LValue &Pointer, 6667 DynAlloc::Kind DeallocKind) { 6668 auto PointerAsString = [&] { 6669 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6670 }; 6671 6672 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6673 if (!DA) { 6674 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6675 << PointerAsString(); 6676 if (Pointer.Base) 6677 NoteLValueLocation(Info, Pointer.Base); 6678 return None; 6679 } 6680 6681 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6682 if (!Alloc) { 6683 Info.FFDiag(E, diag::note_constexpr_double_delete); 6684 return None; 6685 } 6686 6687 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6688 if (DeallocKind != (*Alloc)->getKind()) { 6689 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6690 << DeallocKind << (*Alloc)->getKind() << AllocType; 6691 NoteLValueLocation(Info, Pointer.Base); 6692 return None; 6693 } 6694 6695 bool Subobject = false; 6696 if (DeallocKind == DynAlloc::New) { 6697 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6698 Pointer.Designator.isOnePastTheEnd(); 6699 } else { 6700 Subobject = Pointer.Designator.Entries.size() != 1 || 6701 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6702 } 6703 if (Subobject) { 6704 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6705 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6706 return None; 6707 } 6708 6709 return Alloc; 6710 } 6711 6712 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6713 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6714 if (Info.checkingPotentialConstantExpression() || 6715 Info.SpeculativeEvaluationDepth) 6716 return false; 6717 6718 // This is permitted only within a call to std::allocator<T>::deallocate. 6719 if (!Info.getStdAllocatorCaller("deallocate")) { 6720 Info.FFDiag(E->getExprLoc()); 6721 return true; 6722 } 6723 6724 LValue Pointer; 6725 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6726 return false; 6727 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6728 EvaluateIgnoredValue(Info, E->getArg(I)); 6729 6730 if (Pointer.Designator.Invalid) 6731 return false; 6732 6733 // Deleting a null pointer would have no effect, but it's not permitted by 6734 // std::allocator<T>::deallocate's contract. 6735 if (Pointer.isNullPointer()) { 6736 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6737 return true; 6738 } 6739 6740 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6741 return false; 6742 6743 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6744 return true; 6745 } 6746 6747 //===----------------------------------------------------------------------===// 6748 // Generic Evaluation 6749 //===----------------------------------------------------------------------===// 6750 namespace { 6751 6752 class BitCastBuffer { 6753 // FIXME: We're going to need bit-level granularity when we support 6754 // bit-fields. 6755 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6756 // we don't support a host or target where that is the case. Still, we should 6757 // use a more generic type in case we ever do. 6758 SmallVector<Optional<unsigned char>, 32> Bytes; 6759 6760 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6761 "Need at least 8 bit unsigned char"); 6762 6763 bool TargetIsLittleEndian; 6764 6765 public: 6766 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6767 : Bytes(Width.getQuantity()), 6768 TargetIsLittleEndian(TargetIsLittleEndian) {} 6769 6770 LLVM_NODISCARD 6771 bool readObject(CharUnits Offset, CharUnits Width, 6772 SmallVectorImpl<unsigned char> &Output) const { 6773 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6774 // If a byte of an integer is uninitialized, then the whole integer is 6775 // uninitialized. 6776 if (!Bytes[I.getQuantity()]) 6777 return false; 6778 Output.push_back(*Bytes[I.getQuantity()]); 6779 } 6780 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6781 std::reverse(Output.begin(), Output.end()); 6782 return true; 6783 } 6784 6785 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6786 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6787 std::reverse(Input.begin(), Input.end()); 6788 6789 size_t Index = 0; 6790 for (unsigned char Byte : Input) { 6791 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6792 Bytes[Offset.getQuantity() + Index] = Byte; 6793 ++Index; 6794 } 6795 } 6796 6797 size_t size() { return Bytes.size(); } 6798 }; 6799 6800 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6801 /// target would represent the value at runtime. 6802 class APValueToBufferConverter { 6803 EvalInfo &Info; 6804 BitCastBuffer Buffer; 6805 const CastExpr *BCE; 6806 6807 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6808 const CastExpr *BCE) 6809 : Info(Info), 6810 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6811 BCE(BCE) {} 6812 6813 bool visit(const APValue &Val, QualType Ty) { 6814 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6815 } 6816 6817 // Write out Val with type Ty into Buffer starting at Offset. 6818 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6819 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6820 6821 // As a special case, nullptr_t has an indeterminate value. 6822 if (Ty->isNullPtrType()) 6823 return true; 6824 6825 // Dig through Src to find the byte at SrcOffset. 6826 switch (Val.getKind()) { 6827 case APValue::Indeterminate: 6828 case APValue::None: 6829 return true; 6830 6831 case APValue::Int: 6832 return visitInt(Val.getInt(), Ty, Offset); 6833 case APValue::Float: 6834 return visitFloat(Val.getFloat(), Ty, Offset); 6835 case APValue::Array: 6836 return visitArray(Val, Ty, Offset); 6837 case APValue::Struct: 6838 return visitRecord(Val, Ty, Offset); 6839 6840 case APValue::ComplexInt: 6841 case APValue::ComplexFloat: 6842 case APValue::Vector: 6843 case APValue::FixedPoint: 6844 // FIXME: We should support these. 6845 6846 case APValue::Union: 6847 case APValue::MemberPointer: 6848 case APValue::AddrLabelDiff: { 6849 Info.FFDiag(BCE->getBeginLoc(), 6850 diag::note_constexpr_bit_cast_unsupported_type) 6851 << Ty; 6852 return false; 6853 } 6854 6855 case APValue::LValue: 6856 llvm_unreachable("LValue subobject in bit_cast?"); 6857 } 6858 llvm_unreachable("Unhandled APValue::ValueKind"); 6859 } 6860 6861 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6862 const RecordDecl *RD = Ty->getAsRecordDecl(); 6863 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6864 6865 // Visit the base classes. 6866 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6867 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6868 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6869 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6870 6871 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6872 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6873 return false; 6874 } 6875 } 6876 6877 // Visit the fields. 6878 unsigned FieldIdx = 0; 6879 for (FieldDecl *FD : RD->fields()) { 6880 if (FD->isBitField()) { 6881 Info.FFDiag(BCE->getBeginLoc(), 6882 diag::note_constexpr_bit_cast_unsupported_bitfield); 6883 return false; 6884 } 6885 6886 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6887 6888 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6889 "only bit-fields can have sub-char alignment"); 6890 CharUnits FieldOffset = 6891 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6892 QualType FieldTy = FD->getType(); 6893 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6894 return false; 6895 ++FieldIdx; 6896 } 6897 6898 return true; 6899 } 6900 6901 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6902 const auto *CAT = 6903 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6904 if (!CAT) 6905 return false; 6906 6907 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6908 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6909 unsigned ArraySize = Val.getArraySize(); 6910 // First, initialize the initialized elements. 6911 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6912 const APValue &SubObj = Val.getArrayInitializedElt(I); 6913 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6914 return false; 6915 } 6916 6917 // Next, initialize the rest of the array using the filler. 6918 if (Val.hasArrayFiller()) { 6919 const APValue &Filler = Val.getArrayFiller(); 6920 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6921 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6922 return false; 6923 } 6924 } 6925 6926 return true; 6927 } 6928 6929 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6930 APSInt AdjustedVal = Val; 6931 unsigned Width = AdjustedVal.getBitWidth(); 6932 if (Ty->isBooleanType()) { 6933 Width = Info.Ctx.getTypeSize(Ty); 6934 AdjustedVal = AdjustedVal.extend(Width); 6935 } 6936 6937 SmallVector<unsigned char, 8> Bytes(Width / 8); 6938 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6939 Buffer.writeObject(Offset, Bytes); 6940 return true; 6941 } 6942 6943 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6944 APSInt AsInt(Val.bitcastToAPInt()); 6945 return visitInt(AsInt, Ty, Offset); 6946 } 6947 6948 public: 6949 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6950 const CastExpr *BCE) { 6951 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6952 APValueToBufferConverter Converter(Info, DstSize, BCE); 6953 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6954 return None; 6955 return Converter.Buffer; 6956 } 6957 }; 6958 6959 /// Write an BitCastBuffer into an APValue. 6960 class BufferToAPValueConverter { 6961 EvalInfo &Info; 6962 const BitCastBuffer &Buffer; 6963 const CastExpr *BCE; 6964 6965 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6966 const CastExpr *BCE) 6967 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6968 6969 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6970 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6971 // Ideally this will be unreachable. 6972 llvm::NoneType unsupportedType(QualType Ty) { 6973 Info.FFDiag(BCE->getBeginLoc(), 6974 diag::note_constexpr_bit_cast_unsupported_type) 6975 << Ty; 6976 return None; 6977 } 6978 6979 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6980 Info.FFDiag(BCE->getBeginLoc(), 6981 diag::note_constexpr_bit_cast_unrepresentable_value) 6982 << Ty << toString(Val, /*Radix=*/10); 6983 return None; 6984 } 6985 6986 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6987 const EnumType *EnumSugar = nullptr) { 6988 if (T->isNullPtrType()) { 6989 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6990 return APValue((Expr *)nullptr, 6991 /*Offset=*/CharUnits::fromQuantity(NullValue), 6992 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6993 } 6994 6995 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6996 6997 // Work around floating point types that contain unused padding bytes. This 6998 // is really just `long double` on x86, which is the only fundamental type 6999 // with padding bytes. 7000 if (T->isRealFloatingType()) { 7001 const llvm::fltSemantics &Semantics = 7002 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7003 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7004 assert(NumBits % 8 == 0); 7005 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7006 if (NumBytes != SizeOf) 7007 SizeOf = NumBytes; 7008 } 7009 7010 SmallVector<uint8_t, 8> Bytes; 7011 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7012 // If this is std::byte or unsigned char, then its okay to store an 7013 // indeterminate value. 7014 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7015 bool IsUChar = 7016 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7017 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7018 if (!IsStdByte && !IsUChar) { 7019 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7020 Info.FFDiag(BCE->getExprLoc(), 7021 diag::note_constexpr_bit_cast_indet_dest) 7022 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7023 return None; 7024 } 7025 7026 return APValue::IndeterminateValue(); 7027 } 7028 7029 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7030 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7031 7032 if (T->isIntegralOrEnumerationType()) { 7033 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7034 7035 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7036 if (IntWidth != Val.getBitWidth()) { 7037 APSInt Truncated = Val.trunc(IntWidth); 7038 if (Truncated.extend(Val.getBitWidth()) != Val) 7039 return unrepresentableValue(QualType(T, 0), Val); 7040 Val = Truncated; 7041 } 7042 7043 return APValue(Val); 7044 } 7045 7046 if (T->isRealFloatingType()) { 7047 const llvm::fltSemantics &Semantics = 7048 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7049 return APValue(APFloat(Semantics, Val)); 7050 } 7051 7052 return unsupportedType(QualType(T, 0)); 7053 } 7054 7055 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7056 const RecordDecl *RD = RTy->getAsRecordDecl(); 7057 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7058 7059 unsigned NumBases = 0; 7060 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7061 NumBases = CXXRD->getNumBases(); 7062 7063 APValue ResultVal(APValue::UninitStruct(), NumBases, 7064 std::distance(RD->field_begin(), RD->field_end())); 7065 7066 // Visit the base classes. 7067 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7068 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7069 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7070 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7071 if (BaseDecl->isEmpty() || 7072 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7073 continue; 7074 7075 Optional<APValue> SubObj = visitType( 7076 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7077 if (!SubObj) 7078 return None; 7079 ResultVal.getStructBase(I) = *SubObj; 7080 } 7081 } 7082 7083 // Visit the fields. 7084 unsigned FieldIdx = 0; 7085 for (FieldDecl *FD : RD->fields()) { 7086 // FIXME: We don't currently support bit-fields. A lot of the logic for 7087 // this is in CodeGen, so we need to factor it around. 7088 if (FD->isBitField()) { 7089 Info.FFDiag(BCE->getBeginLoc(), 7090 diag::note_constexpr_bit_cast_unsupported_bitfield); 7091 return None; 7092 } 7093 7094 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7095 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7096 7097 CharUnits FieldOffset = 7098 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7099 Offset; 7100 QualType FieldTy = FD->getType(); 7101 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7102 if (!SubObj) 7103 return None; 7104 ResultVal.getStructField(FieldIdx) = *SubObj; 7105 ++FieldIdx; 7106 } 7107 7108 return ResultVal; 7109 } 7110 7111 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7112 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7113 assert(!RepresentationType.isNull() && 7114 "enum forward decl should be caught by Sema"); 7115 const auto *AsBuiltin = 7116 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7117 // Recurse into the underlying type. Treat std::byte transparently as 7118 // unsigned char. 7119 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7120 } 7121 7122 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7123 size_t Size = Ty->getSize().getLimitedValue(); 7124 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7125 7126 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7127 for (size_t I = 0; I != Size; ++I) { 7128 Optional<APValue> ElementValue = 7129 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7130 if (!ElementValue) 7131 return None; 7132 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7133 } 7134 7135 return ArrayValue; 7136 } 7137 7138 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7139 return unsupportedType(QualType(Ty, 0)); 7140 } 7141 7142 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7143 QualType Can = Ty.getCanonicalType(); 7144 7145 switch (Can->getTypeClass()) { 7146 #define TYPE(Class, Base) \ 7147 case Type::Class: \ 7148 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7149 #define ABSTRACT_TYPE(Class, Base) 7150 #define NON_CANONICAL_TYPE(Class, Base) \ 7151 case Type::Class: \ 7152 llvm_unreachable("non-canonical type should be impossible!"); 7153 #define DEPENDENT_TYPE(Class, Base) \ 7154 case Type::Class: \ 7155 llvm_unreachable( \ 7156 "dependent types aren't supported in the constant evaluator!"); 7157 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7158 case Type::Class: \ 7159 llvm_unreachable("either dependent or not canonical!"); 7160 #include "clang/AST/TypeNodes.inc" 7161 } 7162 llvm_unreachable("Unhandled Type::TypeClass"); 7163 } 7164 7165 public: 7166 // Pull out a full value of type DstType. 7167 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7168 const CastExpr *BCE) { 7169 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7170 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7171 } 7172 }; 7173 7174 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7175 QualType Ty, EvalInfo *Info, 7176 const ASTContext &Ctx, 7177 bool CheckingDest) { 7178 Ty = Ty.getCanonicalType(); 7179 7180 auto diag = [&](int Reason) { 7181 if (Info) 7182 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7183 << CheckingDest << (Reason == 4) << Reason; 7184 return false; 7185 }; 7186 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7187 if (Info) 7188 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7189 << NoteTy << Construct << Ty; 7190 return false; 7191 }; 7192 7193 if (Ty->isUnionType()) 7194 return diag(0); 7195 if (Ty->isPointerType()) 7196 return diag(1); 7197 if (Ty->isMemberPointerType()) 7198 return diag(2); 7199 if (Ty.isVolatileQualified()) 7200 return diag(3); 7201 7202 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7203 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7204 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7205 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7206 CheckingDest)) 7207 return note(1, BS.getType(), BS.getBeginLoc()); 7208 } 7209 for (FieldDecl *FD : Record->fields()) { 7210 if (FD->getType()->isReferenceType()) 7211 return diag(4); 7212 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7213 CheckingDest)) 7214 return note(0, FD->getType(), FD->getBeginLoc()); 7215 } 7216 } 7217 7218 if (Ty->isArrayType() && 7219 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7220 Info, Ctx, CheckingDest)) 7221 return false; 7222 7223 return true; 7224 } 7225 7226 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7227 const ASTContext &Ctx, 7228 const CastExpr *BCE) { 7229 bool DestOK = checkBitCastConstexprEligibilityType( 7230 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7231 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7232 BCE->getBeginLoc(), 7233 BCE->getSubExpr()->getType(), Info, Ctx, false); 7234 return SourceOK; 7235 } 7236 7237 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7238 APValue &SourceValue, 7239 const CastExpr *BCE) { 7240 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7241 "no host or target supports non 8-bit chars"); 7242 assert(SourceValue.isLValue() && 7243 "LValueToRValueBitcast requires an lvalue operand!"); 7244 7245 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7246 return false; 7247 7248 LValue SourceLValue; 7249 APValue SourceRValue; 7250 SourceLValue.setFrom(Info.Ctx, SourceValue); 7251 if (!handleLValueToRValueConversion( 7252 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7253 SourceRValue, /*WantObjectRepresentation=*/true)) 7254 return false; 7255 7256 // Read out SourceValue into a char buffer. 7257 Optional<BitCastBuffer> Buffer = 7258 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7259 if (!Buffer) 7260 return false; 7261 7262 // Write out the buffer into a new APValue. 7263 Optional<APValue> MaybeDestValue = 7264 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7265 if (!MaybeDestValue) 7266 return false; 7267 7268 DestValue = std::move(*MaybeDestValue); 7269 return true; 7270 } 7271 7272 template <class Derived> 7273 class ExprEvaluatorBase 7274 : public ConstStmtVisitor<Derived, bool> { 7275 private: 7276 Derived &getDerived() { return static_cast<Derived&>(*this); } 7277 bool DerivedSuccess(const APValue &V, const Expr *E) { 7278 return getDerived().Success(V, E); 7279 } 7280 bool DerivedZeroInitialization(const Expr *E) { 7281 return getDerived().ZeroInitialization(E); 7282 } 7283 7284 // Check whether a conditional operator with a non-constant condition is a 7285 // potential constant expression. If neither arm is a potential constant 7286 // expression, then the conditional operator is not either. 7287 template<typename ConditionalOperator> 7288 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7289 assert(Info.checkingPotentialConstantExpression()); 7290 7291 // Speculatively evaluate both arms. 7292 SmallVector<PartialDiagnosticAt, 8> Diag; 7293 { 7294 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7295 StmtVisitorTy::Visit(E->getFalseExpr()); 7296 if (Diag.empty()) 7297 return; 7298 } 7299 7300 { 7301 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7302 Diag.clear(); 7303 StmtVisitorTy::Visit(E->getTrueExpr()); 7304 if (Diag.empty()) 7305 return; 7306 } 7307 7308 Error(E, diag::note_constexpr_conditional_never_const); 7309 } 7310 7311 7312 template<typename ConditionalOperator> 7313 bool HandleConditionalOperator(const ConditionalOperator *E) { 7314 bool BoolResult; 7315 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7316 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7317 CheckPotentialConstantConditional(E); 7318 return false; 7319 } 7320 if (Info.noteFailure()) { 7321 StmtVisitorTy::Visit(E->getTrueExpr()); 7322 StmtVisitorTy::Visit(E->getFalseExpr()); 7323 } 7324 return false; 7325 } 7326 7327 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7328 return StmtVisitorTy::Visit(EvalExpr); 7329 } 7330 7331 protected: 7332 EvalInfo &Info; 7333 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7334 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7335 7336 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7337 return Info.CCEDiag(E, D); 7338 } 7339 7340 bool ZeroInitialization(const Expr *E) { return Error(E); } 7341 7342 public: 7343 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7344 7345 EvalInfo &getEvalInfo() { return Info; } 7346 7347 /// Report an evaluation error. This should only be called when an error is 7348 /// first discovered. When propagating an error, just return false. 7349 bool Error(const Expr *E, diag::kind D) { 7350 Info.FFDiag(E, D); 7351 return false; 7352 } 7353 bool Error(const Expr *E) { 7354 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7355 } 7356 7357 bool VisitStmt(const Stmt *) { 7358 llvm_unreachable("Expression evaluator should not be called on stmts"); 7359 } 7360 bool VisitExpr(const Expr *E) { 7361 return Error(E); 7362 } 7363 7364 bool VisitConstantExpr(const ConstantExpr *E) { 7365 if (E->hasAPValueResult()) 7366 return DerivedSuccess(E->getAPValueResult(), E); 7367 7368 return StmtVisitorTy::Visit(E->getSubExpr()); 7369 } 7370 7371 bool VisitParenExpr(const ParenExpr *E) 7372 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7373 bool VisitUnaryExtension(const UnaryOperator *E) 7374 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7375 bool VisitUnaryPlus(const UnaryOperator *E) 7376 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7377 bool VisitChooseExpr(const ChooseExpr *E) 7378 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7379 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7380 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7381 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7382 { return StmtVisitorTy::Visit(E->getReplacement()); } 7383 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7384 TempVersionRAII RAII(*Info.CurrentCall); 7385 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7386 return StmtVisitorTy::Visit(E->getExpr()); 7387 } 7388 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7389 TempVersionRAII RAII(*Info.CurrentCall); 7390 // The initializer may not have been parsed yet, or might be erroneous. 7391 if (!E->getExpr()) 7392 return Error(E); 7393 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7394 return StmtVisitorTy::Visit(E->getExpr()); 7395 } 7396 7397 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7398 FullExpressionRAII Scope(Info); 7399 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7400 } 7401 7402 // Temporaries are registered when created, so we don't care about 7403 // CXXBindTemporaryExpr. 7404 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7405 return StmtVisitorTy::Visit(E->getSubExpr()); 7406 } 7407 7408 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7409 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7410 return static_cast<Derived*>(this)->VisitCastExpr(E); 7411 } 7412 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7413 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7414 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7415 return static_cast<Derived*>(this)->VisitCastExpr(E); 7416 } 7417 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7418 return static_cast<Derived*>(this)->VisitCastExpr(E); 7419 } 7420 7421 bool VisitBinaryOperator(const BinaryOperator *E) { 7422 switch (E->getOpcode()) { 7423 default: 7424 return Error(E); 7425 7426 case BO_Comma: 7427 VisitIgnoredValue(E->getLHS()); 7428 return StmtVisitorTy::Visit(E->getRHS()); 7429 7430 case BO_PtrMemD: 7431 case BO_PtrMemI: { 7432 LValue Obj; 7433 if (!HandleMemberPointerAccess(Info, E, Obj)) 7434 return false; 7435 APValue Result; 7436 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7437 return false; 7438 return DerivedSuccess(Result, E); 7439 } 7440 } 7441 } 7442 7443 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7444 return StmtVisitorTy::Visit(E->getSemanticForm()); 7445 } 7446 7447 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7448 // Evaluate and cache the common expression. We treat it as a temporary, 7449 // even though it's not quite the same thing. 7450 LValue CommonLV; 7451 if (!Evaluate(Info.CurrentCall->createTemporary( 7452 E->getOpaqueValue(), 7453 getStorageType(Info.Ctx, E->getOpaqueValue()), 7454 ScopeKind::FullExpression, CommonLV), 7455 Info, E->getCommon())) 7456 return false; 7457 7458 return HandleConditionalOperator(E); 7459 } 7460 7461 bool VisitConditionalOperator(const ConditionalOperator *E) { 7462 bool IsBcpCall = false; 7463 // If the condition (ignoring parens) is a __builtin_constant_p call, 7464 // the result is a constant expression if it can be folded without 7465 // side-effects. This is an important GNU extension. See GCC PR38377 7466 // for discussion. 7467 if (const CallExpr *CallCE = 7468 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7469 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7470 IsBcpCall = true; 7471 7472 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7473 // constant expression; we can't check whether it's potentially foldable. 7474 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7475 // it would return 'false' in this mode. 7476 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7477 return false; 7478 7479 FoldConstant Fold(Info, IsBcpCall); 7480 if (!HandleConditionalOperator(E)) { 7481 Fold.keepDiagnostics(); 7482 return false; 7483 } 7484 7485 return true; 7486 } 7487 7488 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7489 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7490 return DerivedSuccess(*Value, E); 7491 7492 const Expr *Source = E->getSourceExpr(); 7493 if (!Source) 7494 return Error(E); 7495 if (Source == E) { 7496 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7497 return Error(E); 7498 } 7499 return StmtVisitorTy::Visit(Source); 7500 } 7501 7502 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7503 for (const Expr *SemE : E->semantics()) { 7504 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7505 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7506 // result expression: there could be two different LValues that would 7507 // refer to the same object in that case, and we can't model that. 7508 if (SemE == E->getResultExpr()) 7509 return Error(E); 7510 7511 // Unique OVEs get evaluated if and when we encounter them when 7512 // emitting the rest of the semantic form, rather than eagerly. 7513 if (OVE->isUnique()) 7514 continue; 7515 7516 LValue LV; 7517 if (!Evaluate(Info.CurrentCall->createTemporary( 7518 OVE, getStorageType(Info.Ctx, OVE), 7519 ScopeKind::FullExpression, LV), 7520 Info, OVE->getSourceExpr())) 7521 return false; 7522 } else if (SemE == E->getResultExpr()) { 7523 if (!StmtVisitorTy::Visit(SemE)) 7524 return false; 7525 } else { 7526 if (!EvaluateIgnoredValue(Info, SemE)) 7527 return false; 7528 } 7529 } 7530 return true; 7531 } 7532 7533 bool VisitCallExpr(const CallExpr *E) { 7534 APValue Result; 7535 if (!handleCallExpr(E, Result, nullptr)) 7536 return false; 7537 return DerivedSuccess(Result, E); 7538 } 7539 7540 bool handleCallExpr(const CallExpr *E, APValue &Result, 7541 const LValue *ResultSlot) { 7542 CallScopeRAII CallScope(Info); 7543 7544 const Expr *Callee = E->getCallee()->IgnoreParens(); 7545 QualType CalleeType = Callee->getType(); 7546 7547 const FunctionDecl *FD = nullptr; 7548 LValue *This = nullptr, ThisVal; 7549 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7550 bool HasQualifier = false; 7551 7552 CallRef Call; 7553 7554 // Extract function decl and 'this' pointer from the callee. 7555 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7556 const CXXMethodDecl *Member = nullptr; 7557 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7558 // Explicit bound member calls, such as x.f() or p->g(); 7559 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7560 return false; 7561 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7562 if (!Member) 7563 return Error(Callee); 7564 This = &ThisVal; 7565 HasQualifier = ME->hasQualifier(); 7566 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7567 // Indirect bound member calls ('.*' or '->*'). 7568 const ValueDecl *D = 7569 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7570 if (!D) 7571 return false; 7572 Member = dyn_cast<CXXMethodDecl>(D); 7573 if (!Member) 7574 return Error(Callee); 7575 This = &ThisVal; 7576 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7577 if (!Info.getLangOpts().CPlusPlus20) 7578 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7579 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7580 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7581 } else 7582 return Error(Callee); 7583 FD = Member; 7584 } else if (CalleeType->isFunctionPointerType()) { 7585 LValue CalleeLV; 7586 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7587 return false; 7588 7589 if (!CalleeLV.getLValueOffset().isZero()) 7590 return Error(Callee); 7591 FD = dyn_cast_or_null<FunctionDecl>( 7592 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7593 if (!FD) 7594 return Error(Callee); 7595 // Don't call function pointers which have been cast to some other type. 7596 // Per DR (no number yet), the caller and callee can differ in noexcept. 7597 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7598 CalleeType->getPointeeType(), FD->getType())) { 7599 return Error(E); 7600 } 7601 7602 // For an (overloaded) assignment expression, evaluate the RHS before the 7603 // LHS. 7604 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7605 if (OCE && OCE->isAssignmentOp()) { 7606 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7607 Call = Info.CurrentCall->createCall(FD); 7608 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7609 Info, FD, /*RightToLeft=*/true)) 7610 return false; 7611 } 7612 7613 // Overloaded operator calls to member functions are represented as normal 7614 // calls with '*this' as the first argument. 7615 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7616 if (MD && !MD->isStatic()) { 7617 // FIXME: When selecting an implicit conversion for an overloaded 7618 // operator delete, we sometimes try to evaluate calls to conversion 7619 // operators without a 'this' parameter! 7620 if (Args.empty()) 7621 return Error(E); 7622 7623 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7624 return false; 7625 This = &ThisVal; 7626 Args = Args.slice(1); 7627 } else if (MD && MD->isLambdaStaticInvoker()) { 7628 // Map the static invoker for the lambda back to the call operator. 7629 // Conveniently, we don't have to slice out the 'this' argument (as is 7630 // being done for the non-static case), since a static member function 7631 // doesn't have an implicit argument passed in. 7632 const CXXRecordDecl *ClosureClass = MD->getParent(); 7633 assert( 7634 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7635 "Number of captures must be zero for conversion to function-ptr"); 7636 7637 const CXXMethodDecl *LambdaCallOp = 7638 ClosureClass->getLambdaCallOperator(); 7639 7640 // Set 'FD', the function that will be called below, to the call 7641 // operator. If the closure object represents a generic lambda, find 7642 // the corresponding specialization of the call operator. 7643 7644 if (ClosureClass->isGenericLambda()) { 7645 assert(MD->isFunctionTemplateSpecialization() && 7646 "A generic lambda's static-invoker function must be a " 7647 "template specialization"); 7648 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7649 FunctionTemplateDecl *CallOpTemplate = 7650 LambdaCallOp->getDescribedFunctionTemplate(); 7651 void *InsertPos = nullptr; 7652 FunctionDecl *CorrespondingCallOpSpecialization = 7653 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7654 assert(CorrespondingCallOpSpecialization && 7655 "We must always have a function call operator specialization " 7656 "that corresponds to our static invoker specialization"); 7657 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7658 } else 7659 FD = LambdaCallOp; 7660 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7661 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7662 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7663 LValue Ptr; 7664 if (!HandleOperatorNewCall(Info, E, Ptr)) 7665 return false; 7666 Ptr.moveInto(Result); 7667 return CallScope.destroy(); 7668 } else { 7669 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7670 } 7671 } 7672 } else 7673 return Error(E); 7674 7675 // Evaluate the arguments now if we've not already done so. 7676 if (!Call) { 7677 Call = Info.CurrentCall->createCall(FD); 7678 if (!EvaluateArgs(Args, Call, Info, FD)) 7679 return false; 7680 } 7681 7682 SmallVector<QualType, 4> CovariantAdjustmentPath; 7683 if (This) { 7684 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7685 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7686 // Perform virtual dispatch, if necessary. 7687 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7688 CovariantAdjustmentPath); 7689 if (!FD) 7690 return false; 7691 } else { 7692 // Check that the 'this' pointer points to an object of the right type. 7693 // FIXME: If this is an assignment operator call, we may need to change 7694 // the active union member before we check this. 7695 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7696 return false; 7697 } 7698 } 7699 7700 // Destructor calls are different enough that they have their own codepath. 7701 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7702 assert(This && "no 'this' pointer for destructor call"); 7703 return HandleDestruction(Info, E, *This, 7704 Info.Ctx.getRecordType(DD->getParent())) && 7705 CallScope.destroy(); 7706 } 7707 7708 const FunctionDecl *Definition = nullptr; 7709 Stmt *Body = FD->getBody(Definition); 7710 7711 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7712 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7713 Body, Info, Result, ResultSlot)) 7714 return false; 7715 7716 if (!CovariantAdjustmentPath.empty() && 7717 !HandleCovariantReturnAdjustment(Info, E, Result, 7718 CovariantAdjustmentPath)) 7719 return false; 7720 7721 return CallScope.destroy(); 7722 } 7723 7724 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7725 return StmtVisitorTy::Visit(E->getInitializer()); 7726 } 7727 bool VisitInitListExpr(const InitListExpr *E) { 7728 if (E->getNumInits() == 0) 7729 return DerivedZeroInitialization(E); 7730 if (E->getNumInits() == 1) 7731 return StmtVisitorTy::Visit(E->getInit(0)); 7732 return Error(E); 7733 } 7734 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7735 return DerivedZeroInitialization(E); 7736 } 7737 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7738 return DerivedZeroInitialization(E); 7739 } 7740 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7741 return DerivedZeroInitialization(E); 7742 } 7743 7744 /// A member expression where the object is a prvalue is itself a prvalue. 7745 bool VisitMemberExpr(const MemberExpr *E) { 7746 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7747 "missing temporary materialization conversion"); 7748 assert(!E->isArrow() && "missing call to bound member function?"); 7749 7750 APValue Val; 7751 if (!Evaluate(Val, Info, E->getBase())) 7752 return false; 7753 7754 QualType BaseTy = E->getBase()->getType(); 7755 7756 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7757 if (!FD) return Error(E); 7758 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7759 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7760 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7761 7762 // Note: there is no lvalue base here. But this case should only ever 7763 // happen in C or in C++98, where we cannot be evaluating a constexpr 7764 // constructor, which is the only case the base matters. 7765 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7766 SubobjectDesignator Designator(BaseTy); 7767 Designator.addDeclUnchecked(FD); 7768 7769 APValue Result; 7770 return extractSubobject(Info, E, Obj, Designator, Result) && 7771 DerivedSuccess(Result, E); 7772 } 7773 7774 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7775 APValue Val; 7776 if (!Evaluate(Val, Info, E->getBase())) 7777 return false; 7778 7779 if (Val.isVector()) { 7780 SmallVector<uint32_t, 4> Indices; 7781 E->getEncodedElementAccess(Indices); 7782 if (Indices.size() == 1) { 7783 // Return scalar. 7784 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7785 } else { 7786 // Construct new APValue vector. 7787 SmallVector<APValue, 4> Elts; 7788 for (unsigned I = 0; I < Indices.size(); ++I) { 7789 Elts.push_back(Val.getVectorElt(Indices[I])); 7790 } 7791 APValue VecResult(Elts.data(), Indices.size()); 7792 return DerivedSuccess(VecResult, E); 7793 } 7794 } 7795 7796 return false; 7797 } 7798 7799 bool VisitCastExpr(const CastExpr *E) { 7800 switch (E->getCastKind()) { 7801 default: 7802 break; 7803 7804 case CK_AtomicToNonAtomic: { 7805 APValue AtomicVal; 7806 // This does not need to be done in place even for class/array types: 7807 // atomic-to-non-atomic conversion implies copying the object 7808 // representation. 7809 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7810 return false; 7811 return DerivedSuccess(AtomicVal, E); 7812 } 7813 7814 case CK_NoOp: 7815 case CK_UserDefinedConversion: 7816 return StmtVisitorTy::Visit(E->getSubExpr()); 7817 7818 case CK_LValueToRValue: { 7819 LValue LVal; 7820 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7821 return false; 7822 APValue RVal; 7823 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7824 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7825 LVal, RVal)) 7826 return false; 7827 return DerivedSuccess(RVal, E); 7828 } 7829 case CK_LValueToRValueBitCast: { 7830 APValue DestValue, SourceValue; 7831 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7832 return false; 7833 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7834 return false; 7835 return DerivedSuccess(DestValue, E); 7836 } 7837 7838 case CK_AddressSpaceConversion: { 7839 APValue Value; 7840 if (!Evaluate(Value, Info, E->getSubExpr())) 7841 return false; 7842 return DerivedSuccess(Value, E); 7843 } 7844 } 7845 7846 return Error(E); 7847 } 7848 7849 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7850 return VisitUnaryPostIncDec(UO); 7851 } 7852 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7853 return VisitUnaryPostIncDec(UO); 7854 } 7855 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7856 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7857 return Error(UO); 7858 7859 LValue LVal; 7860 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7861 return false; 7862 APValue RVal; 7863 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7864 UO->isIncrementOp(), &RVal)) 7865 return false; 7866 return DerivedSuccess(RVal, UO); 7867 } 7868 7869 bool VisitStmtExpr(const StmtExpr *E) { 7870 // We will have checked the full-expressions inside the statement expression 7871 // when they were completed, and don't need to check them again now. 7872 llvm::SaveAndRestore<bool> NotCheckingForUB( 7873 Info.CheckingForUndefinedBehavior, false); 7874 7875 const CompoundStmt *CS = E->getSubStmt(); 7876 if (CS->body_empty()) 7877 return true; 7878 7879 BlockScopeRAII Scope(Info); 7880 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7881 BE = CS->body_end(); 7882 /**/; ++BI) { 7883 if (BI + 1 == BE) { 7884 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7885 if (!FinalExpr) { 7886 Info.FFDiag((*BI)->getBeginLoc(), 7887 diag::note_constexpr_stmt_expr_unsupported); 7888 return false; 7889 } 7890 return this->Visit(FinalExpr) && Scope.destroy(); 7891 } 7892 7893 APValue ReturnValue; 7894 StmtResult Result = { ReturnValue, nullptr }; 7895 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7896 if (ESR != ESR_Succeeded) { 7897 // FIXME: If the statement-expression terminated due to 'return', 7898 // 'break', or 'continue', it would be nice to propagate that to 7899 // the outer statement evaluation rather than bailing out. 7900 if (ESR != ESR_Failed) 7901 Info.FFDiag((*BI)->getBeginLoc(), 7902 diag::note_constexpr_stmt_expr_unsupported); 7903 return false; 7904 } 7905 } 7906 7907 llvm_unreachable("Return from function from the loop above."); 7908 } 7909 7910 /// Visit a value which is evaluated, but whose value is ignored. 7911 void VisitIgnoredValue(const Expr *E) { 7912 EvaluateIgnoredValue(Info, E); 7913 } 7914 7915 /// Potentially visit a MemberExpr's base expression. 7916 void VisitIgnoredBaseExpression(const Expr *E) { 7917 // While MSVC doesn't evaluate the base expression, it does diagnose the 7918 // presence of side-effecting behavior. 7919 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7920 return; 7921 VisitIgnoredValue(E); 7922 } 7923 }; 7924 7925 } // namespace 7926 7927 //===----------------------------------------------------------------------===// 7928 // Common base class for lvalue and temporary evaluation. 7929 //===----------------------------------------------------------------------===// 7930 namespace { 7931 template<class Derived> 7932 class LValueExprEvaluatorBase 7933 : public ExprEvaluatorBase<Derived> { 7934 protected: 7935 LValue &Result; 7936 bool InvalidBaseOK; 7937 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7938 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7939 7940 bool Success(APValue::LValueBase B) { 7941 Result.set(B); 7942 return true; 7943 } 7944 7945 bool evaluatePointer(const Expr *E, LValue &Result) { 7946 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7947 } 7948 7949 public: 7950 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7951 : ExprEvaluatorBaseTy(Info), Result(Result), 7952 InvalidBaseOK(InvalidBaseOK) {} 7953 7954 bool Success(const APValue &V, const Expr *E) { 7955 Result.setFrom(this->Info.Ctx, V); 7956 return true; 7957 } 7958 7959 bool VisitMemberExpr(const MemberExpr *E) { 7960 // Handle non-static data members. 7961 QualType BaseTy; 7962 bool EvalOK; 7963 if (E->isArrow()) { 7964 EvalOK = evaluatePointer(E->getBase(), Result); 7965 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7966 } else if (E->getBase()->isPRValue()) { 7967 assert(E->getBase()->getType()->isRecordType()); 7968 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7969 BaseTy = E->getBase()->getType(); 7970 } else { 7971 EvalOK = this->Visit(E->getBase()); 7972 BaseTy = E->getBase()->getType(); 7973 } 7974 if (!EvalOK) { 7975 if (!InvalidBaseOK) 7976 return false; 7977 Result.setInvalid(E); 7978 return true; 7979 } 7980 7981 const ValueDecl *MD = E->getMemberDecl(); 7982 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7983 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7984 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7985 (void)BaseTy; 7986 if (!HandleLValueMember(this->Info, E, Result, FD)) 7987 return false; 7988 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7989 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7990 return false; 7991 } else 7992 return this->Error(E); 7993 7994 if (MD->getType()->isReferenceType()) { 7995 APValue RefValue; 7996 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7997 RefValue)) 7998 return false; 7999 return Success(RefValue, E); 8000 } 8001 return true; 8002 } 8003 8004 bool VisitBinaryOperator(const BinaryOperator *E) { 8005 switch (E->getOpcode()) { 8006 default: 8007 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8008 8009 case BO_PtrMemD: 8010 case BO_PtrMemI: 8011 return HandleMemberPointerAccess(this->Info, E, Result); 8012 } 8013 } 8014 8015 bool VisitCastExpr(const CastExpr *E) { 8016 switch (E->getCastKind()) { 8017 default: 8018 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8019 8020 case CK_DerivedToBase: 8021 case CK_UncheckedDerivedToBase: 8022 if (!this->Visit(E->getSubExpr())) 8023 return false; 8024 8025 // Now figure out the necessary offset to add to the base LV to get from 8026 // the derived class to the base class. 8027 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8028 Result); 8029 } 8030 } 8031 }; 8032 } 8033 8034 //===----------------------------------------------------------------------===// 8035 // LValue Evaluation 8036 // 8037 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8038 // function designators (in C), decl references to void objects (in C), and 8039 // temporaries (if building with -Wno-address-of-temporary). 8040 // 8041 // LValue evaluation produces values comprising a base expression of one of the 8042 // following types: 8043 // - Declarations 8044 // * VarDecl 8045 // * FunctionDecl 8046 // - Literals 8047 // * CompoundLiteralExpr in C (and in global scope in C++) 8048 // * StringLiteral 8049 // * PredefinedExpr 8050 // * ObjCStringLiteralExpr 8051 // * ObjCEncodeExpr 8052 // * AddrLabelExpr 8053 // * BlockExpr 8054 // * CallExpr for a MakeStringConstant builtin 8055 // - typeid(T) expressions, as TypeInfoLValues 8056 // - Locals and temporaries 8057 // * MaterializeTemporaryExpr 8058 // * Any Expr, with a CallIndex indicating the function in which the temporary 8059 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8060 // from the AST (FIXME). 8061 // * A MaterializeTemporaryExpr that has static storage duration, with no 8062 // CallIndex, for a lifetime-extended temporary. 8063 // * The ConstantExpr that is currently being evaluated during evaluation of an 8064 // immediate invocation. 8065 // plus an offset in bytes. 8066 //===----------------------------------------------------------------------===// 8067 namespace { 8068 class LValueExprEvaluator 8069 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8070 public: 8071 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8072 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8073 8074 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8075 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8076 8077 bool VisitDeclRefExpr(const DeclRefExpr *E); 8078 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8079 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8080 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8081 bool VisitMemberExpr(const MemberExpr *E); 8082 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8083 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8084 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8085 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8086 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8087 bool VisitUnaryDeref(const UnaryOperator *E); 8088 bool VisitUnaryReal(const UnaryOperator *E); 8089 bool VisitUnaryImag(const UnaryOperator *E); 8090 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8091 return VisitUnaryPreIncDec(UO); 8092 } 8093 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8094 return VisitUnaryPreIncDec(UO); 8095 } 8096 bool VisitBinAssign(const BinaryOperator *BO); 8097 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8098 8099 bool VisitCastExpr(const CastExpr *E) { 8100 switch (E->getCastKind()) { 8101 default: 8102 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8103 8104 case CK_LValueBitCast: 8105 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8106 if (!Visit(E->getSubExpr())) 8107 return false; 8108 Result.Designator.setInvalid(); 8109 return true; 8110 8111 case CK_BaseToDerived: 8112 if (!Visit(E->getSubExpr())) 8113 return false; 8114 return HandleBaseToDerivedCast(Info, E, Result); 8115 8116 case CK_Dynamic: 8117 if (!Visit(E->getSubExpr())) 8118 return false; 8119 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8120 } 8121 } 8122 }; 8123 } // end anonymous namespace 8124 8125 /// Evaluate an expression as an lvalue. This can be legitimately called on 8126 /// expressions which are not glvalues, in three cases: 8127 /// * function designators in C, and 8128 /// * "extern void" objects 8129 /// * @selector() expressions in Objective-C 8130 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8131 bool InvalidBaseOK) { 8132 assert(!E->isValueDependent()); 8133 assert(E->isGLValue() || E->getType()->isFunctionType() || 8134 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8135 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8136 } 8137 8138 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8139 const NamedDecl *D = E->getDecl(); 8140 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8141 return Success(cast<ValueDecl>(D)); 8142 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8143 return VisitVarDecl(E, VD); 8144 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8145 return Visit(BD->getBinding()); 8146 return Error(E); 8147 } 8148 8149 8150 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8151 8152 // If we are within a lambda's call operator, check whether the 'VD' referred 8153 // to within 'E' actually represents a lambda-capture that maps to a 8154 // data-member/field within the closure object, and if so, evaluate to the 8155 // field or what the field refers to. 8156 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8157 isa<DeclRefExpr>(E) && 8158 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8159 // We don't always have a complete capture-map when checking or inferring if 8160 // the function call operator meets the requirements of a constexpr function 8161 // - but we don't need to evaluate the captures to determine constexprness 8162 // (dcl.constexpr C++17). 8163 if (Info.checkingPotentialConstantExpression()) 8164 return false; 8165 8166 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8167 // Start with 'Result' referring to the complete closure object... 8168 Result = *Info.CurrentCall->This; 8169 // ... then update it to refer to the field of the closure object 8170 // that represents the capture. 8171 if (!HandleLValueMember(Info, E, Result, FD)) 8172 return false; 8173 // And if the field is of reference type, update 'Result' to refer to what 8174 // the field refers to. 8175 if (FD->getType()->isReferenceType()) { 8176 APValue RVal; 8177 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8178 RVal)) 8179 return false; 8180 Result.setFrom(Info.Ctx, RVal); 8181 } 8182 return true; 8183 } 8184 } 8185 8186 CallStackFrame *Frame = nullptr; 8187 unsigned Version = 0; 8188 if (VD->hasLocalStorage()) { 8189 // Only if a local variable was declared in the function currently being 8190 // evaluated, do we expect to be able to find its value in the current 8191 // frame. (Otherwise it was likely declared in an enclosing context and 8192 // could either have a valid evaluatable value (for e.g. a constexpr 8193 // variable) or be ill-formed (and trigger an appropriate evaluation 8194 // diagnostic)). 8195 CallStackFrame *CurrFrame = Info.CurrentCall; 8196 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8197 // Function parameters are stored in some caller's frame. (Usually the 8198 // immediate caller, but for an inherited constructor they may be more 8199 // distant.) 8200 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8201 if (CurrFrame->Arguments) { 8202 VD = CurrFrame->Arguments.getOrigParam(PVD); 8203 Frame = 8204 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8205 Version = CurrFrame->Arguments.Version; 8206 } 8207 } else { 8208 Frame = CurrFrame; 8209 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8210 } 8211 } 8212 } 8213 8214 if (!VD->getType()->isReferenceType()) { 8215 if (Frame) { 8216 Result.set({VD, Frame->Index, Version}); 8217 return true; 8218 } 8219 return Success(VD); 8220 } 8221 8222 if (!Info.getLangOpts().CPlusPlus11) { 8223 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8224 << VD << VD->getType(); 8225 Info.Note(VD->getLocation(), diag::note_declared_at); 8226 } 8227 8228 APValue *V; 8229 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8230 return false; 8231 if (!V->hasValue()) { 8232 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8233 // adjust the diagnostic to say that. 8234 if (!Info.checkingPotentialConstantExpression()) 8235 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8236 return false; 8237 } 8238 return Success(*V, E); 8239 } 8240 8241 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8242 const MaterializeTemporaryExpr *E) { 8243 // Walk through the expression to find the materialized temporary itself. 8244 SmallVector<const Expr *, 2> CommaLHSs; 8245 SmallVector<SubobjectAdjustment, 2> Adjustments; 8246 const Expr *Inner = 8247 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8248 8249 // If we passed any comma operators, evaluate their LHSs. 8250 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8251 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8252 return false; 8253 8254 // A materialized temporary with static storage duration can appear within the 8255 // result of a constant expression evaluation, so we need to preserve its 8256 // value for use outside this evaluation. 8257 APValue *Value; 8258 if (E->getStorageDuration() == SD_Static) { 8259 // FIXME: What about SD_Thread? 8260 Value = E->getOrCreateValue(true); 8261 *Value = APValue(); 8262 Result.set(E); 8263 } else { 8264 Value = &Info.CurrentCall->createTemporary( 8265 E, E->getType(), 8266 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8267 : ScopeKind::Block, 8268 Result); 8269 } 8270 8271 QualType Type = Inner->getType(); 8272 8273 // Materialize the temporary itself. 8274 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8275 *Value = APValue(); 8276 return false; 8277 } 8278 8279 // Adjust our lvalue to refer to the desired subobject. 8280 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8281 --I; 8282 switch (Adjustments[I].Kind) { 8283 case SubobjectAdjustment::DerivedToBaseAdjustment: 8284 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8285 Type, Result)) 8286 return false; 8287 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8288 break; 8289 8290 case SubobjectAdjustment::FieldAdjustment: 8291 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8292 return false; 8293 Type = Adjustments[I].Field->getType(); 8294 break; 8295 8296 case SubobjectAdjustment::MemberPointerAdjustment: 8297 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8298 Adjustments[I].Ptr.RHS)) 8299 return false; 8300 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8301 break; 8302 } 8303 } 8304 8305 return true; 8306 } 8307 8308 bool 8309 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8310 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8311 "lvalue compound literal in c++?"); 8312 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8313 // only see this when folding in C, so there's no standard to follow here. 8314 return Success(E); 8315 } 8316 8317 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8318 TypeInfoLValue TypeInfo; 8319 8320 if (!E->isPotentiallyEvaluated()) { 8321 if (E->isTypeOperand()) 8322 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8323 else 8324 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8325 } else { 8326 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8327 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8328 << E->getExprOperand()->getType() 8329 << E->getExprOperand()->getSourceRange(); 8330 } 8331 8332 if (!Visit(E->getExprOperand())) 8333 return false; 8334 8335 Optional<DynamicType> DynType = 8336 ComputeDynamicType(Info, E, Result, AK_TypeId); 8337 if (!DynType) 8338 return false; 8339 8340 TypeInfo = 8341 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8342 } 8343 8344 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8345 } 8346 8347 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8348 return Success(E->getGuidDecl()); 8349 } 8350 8351 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8352 // Handle static data members. 8353 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8354 VisitIgnoredBaseExpression(E->getBase()); 8355 return VisitVarDecl(E, VD); 8356 } 8357 8358 // Handle static member functions. 8359 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8360 if (MD->isStatic()) { 8361 VisitIgnoredBaseExpression(E->getBase()); 8362 return Success(MD); 8363 } 8364 } 8365 8366 // Handle non-static data members. 8367 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8368 } 8369 8370 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8371 // FIXME: Deal with vectors as array subscript bases. 8372 if (E->getBase()->getType()->isVectorType()) 8373 return Error(E); 8374 8375 APSInt Index; 8376 bool Success = true; 8377 8378 // C++17's rules require us to evaluate the LHS first, regardless of which 8379 // side is the base. 8380 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8381 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8382 : !EvaluateInteger(SubExpr, Index, Info)) { 8383 if (!Info.noteFailure()) 8384 return false; 8385 Success = false; 8386 } 8387 } 8388 8389 return Success && 8390 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8391 } 8392 8393 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8394 return evaluatePointer(E->getSubExpr(), Result); 8395 } 8396 8397 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8398 if (!Visit(E->getSubExpr())) 8399 return false; 8400 // __real is a no-op on scalar lvalues. 8401 if (E->getSubExpr()->getType()->isAnyComplexType()) 8402 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8403 return true; 8404 } 8405 8406 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8407 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8408 "lvalue __imag__ on scalar?"); 8409 if (!Visit(E->getSubExpr())) 8410 return false; 8411 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8412 return true; 8413 } 8414 8415 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8416 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8417 return Error(UO); 8418 8419 if (!this->Visit(UO->getSubExpr())) 8420 return false; 8421 8422 return handleIncDec( 8423 this->Info, UO, Result, UO->getSubExpr()->getType(), 8424 UO->isIncrementOp(), nullptr); 8425 } 8426 8427 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8428 const CompoundAssignOperator *CAO) { 8429 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8430 return Error(CAO); 8431 8432 bool Success = true; 8433 8434 // C++17 onwards require that we evaluate the RHS first. 8435 APValue RHS; 8436 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8437 if (!Info.noteFailure()) 8438 return false; 8439 Success = false; 8440 } 8441 8442 // The overall lvalue result is the result of evaluating the LHS. 8443 if (!this->Visit(CAO->getLHS()) || !Success) 8444 return false; 8445 8446 return handleCompoundAssignment( 8447 this->Info, CAO, 8448 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8449 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8450 } 8451 8452 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8453 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8454 return Error(E); 8455 8456 bool Success = true; 8457 8458 // C++17 onwards require that we evaluate the RHS first. 8459 APValue NewVal; 8460 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8461 if (!Info.noteFailure()) 8462 return false; 8463 Success = false; 8464 } 8465 8466 if (!this->Visit(E->getLHS()) || !Success) 8467 return false; 8468 8469 if (Info.getLangOpts().CPlusPlus20 && 8470 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8471 return false; 8472 8473 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8474 NewVal); 8475 } 8476 8477 //===----------------------------------------------------------------------===// 8478 // Pointer Evaluation 8479 //===----------------------------------------------------------------------===// 8480 8481 /// Attempts to compute the number of bytes available at the pointer 8482 /// returned by a function with the alloc_size attribute. Returns true if we 8483 /// were successful. Places an unsigned number into `Result`. 8484 /// 8485 /// This expects the given CallExpr to be a call to a function with an 8486 /// alloc_size attribute. 8487 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8488 const CallExpr *Call, 8489 llvm::APInt &Result) { 8490 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8491 8492 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8493 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8494 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8495 if (Call->getNumArgs() <= SizeArgNo) 8496 return false; 8497 8498 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8499 Expr::EvalResult ExprResult; 8500 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8501 return false; 8502 Into = ExprResult.Val.getInt(); 8503 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8504 return false; 8505 Into = Into.zextOrSelf(BitsInSizeT); 8506 return true; 8507 }; 8508 8509 APSInt SizeOfElem; 8510 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8511 return false; 8512 8513 if (!AllocSize->getNumElemsParam().isValid()) { 8514 Result = std::move(SizeOfElem); 8515 return true; 8516 } 8517 8518 APSInt NumberOfElems; 8519 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8520 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8521 return false; 8522 8523 bool Overflow; 8524 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8525 if (Overflow) 8526 return false; 8527 8528 Result = std::move(BytesAvailable); 8529 return true; 8530 } 8531 8532 /// Convenience function. LVal's base must be a call to an alloc_size 8533 /// function. 8534 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8535 const LValue &LVal, 8536 llvm::APInt &Result) { 8537 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8538 "Can't get the size of a non alloc_size function"); 8539 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8540 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8541 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8542 } 8543 8544 /// Attempts to evaluate the given LValueBase as the result of a call to 8545 /// a function with the alloc_size attribute. If it was possible to do so, this 8546 /// function will return true, make Result's Base point to said function call, 8547 /// and mark Result's Base as invalid. 8548 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8549 LValue &Result) { 8550 if (Base.isNull()) 8551 return false; 8552 8553 // Because we do no form of static analysis, we only support const variables. 8554 // 8555 // Additionally, we can't support parameters, nor can we support static 8556 // variables (in the latter case, use-before-assign isn't UB; in the former, 8557 // we have no clue what they'll be assigned to). 8558 const auto *VD = 8559 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8560 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8561 return false; 8562 8563 const Expr *Init = VD->getAnyInitializer(); 8564 if (!Init) 8565 return false; 8566 8567 const Expr *E = Init->IgnoreParens(); 8568 if (!tryUnwrapAllocSizeCall(E)) 8569 return false; 8570 8571 // Store E instead of E unwrapped so that the type of the LValue's base is 8572 // what the user wanted. 8573 Result.setInvalid(E); 8574 8575 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8576 Result.addUnsizedArray(Info, E, Pointee); 8577 return true; 8578 } 8579 8580 namespace { 8581 class PointerExprEvaluator 8582 : public ExprEvaluatorBase<PointerExprEvaluator> { 8583 LValue &Result; 8584 bool InvalidBaseOK; 8585 8586 bool Success(const Expr *E) { 8587 Result.set(E); 8588 return true; 8589 } 8590 8591 bool evaluateLValue(const Expr *E, LValue &Result) { 8592 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8593 } 8594 8595 bool evaluatePointer(const Expr *E, LValue &Result) { 8596 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8597 } 8598 8599 bool visitNonBuiltinCallExpr(const CallExpr *E); 8600 public: 8601 8602 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8603 : ExprEvaluatorBaseTy(info), Result(Result), 8604 InvalidBaseOK(InvalidBaseOK) {} 8605 8606 bool Success(const APValue &V, const Expr *E) { 8607 Result.setFrom(Info.Ctx, V); 8608 return true; 8609 } 8610 bool ZeroInitialization(const Expr *E) { 8611 Result.setNull(Info.Ctx, E->getType()); 8612 return true; 8613 } 8614 8615 bool VisitBinaryOperator(const BinaryOperator *E); 8616 bool VisitCastExpr(const CastExpr* E); 8617 bool VisitUnaryAddrOf(const UnaryOperator *E); 8618 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8619 { return Success(E); } 8620 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8621 if (E->isExpressibleAsConstantInitializer()) 8622 return Success(E); 8623 if (Info.noteFailure()) 8624 EvaluateIgnoredValue(Info, E->getSubExpr()); 8625 return Error(E); 8626 } 8627 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8628 { return Success(E); } 8629 bool VisitCallExpr(const CallExpr *E); 8630 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8631 bool VisitBlockExpr(const BlockExpr *E) { 8632 if (!E->getBlockDecl()->hasCaptures()) 8633 return Success(E); 8634 return Error(E); 8635 } 8636 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8637 // Can't look at 'this' when checking a potential constant expression. 8638 if (Info.checkingPotentialConstantExpression()) 8639 return false; 8640 if (!Info.CurrentCall->This) { 8641 if (Info.getLangOpts().CPlusPlus11) 8642 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8643 else 8644 Info.FFDiag(E); 8645 return false; 8646 } 8647 Result = *Info.CurrentCall->This; 8648 // If we are inside a lambda's call operator, the 'this' expression refers 8649 // to the enclosing '*this' object (either by value or reference) which is 8650 // either copied into the closure object's field that represents the '*this' 8651 // or refers to '*this'. 8652 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8653 // Ensure we actually have captured 'this'. (an error will have 8654 // been previously reported if not). 8655 if (!Info.CurrentCall->LambdaThisCaptureField) 8656 return false; 8657 8658 // Update 'Result' to refer to the data member/field of the closure object 8659 // that represents the '*this' capture. 8660 if (!HandleLValueMember(Info, E, Result, 8661 Info.CurrentCall->LambdaThisCaptureField)) 8662 return false; 8663 // If we captured '*this' by reference, replace the field with its referent. 8664 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8665 ->isPointerType()) { 8666 APValue RVal; 8667 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8668 RVal)) 8669 return false; 8670 8671 Result.setFrom(Info.Ctx, RVal); 8672 } 8673 } 8674 return true; 8675 } 8676 8677 bool VisitCXXNewExpr(const CXXNewExpr *E); 8678 8679 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8680 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8681 APValue LValResult = E->EvaluateInContext( 8682 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8683 Result.setFrom(Info.Ctx, LValResult); 8684 return true; 8685 } 8686 8687 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8688 std::string ResultStr = E->ComputeName(Info.Ctx); 8689 8690 QualType CharTy = Info.Ctx.CharTy.withConst(); 8691 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8692 ResultStr.size() + 1); 8693 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8694 ArrayType::Normal, 0); 8695 8696 StringLiteral *SL = 8697 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8698 /*Pascal*/ false, ArrayTy, E->getLocation()); 8699 8700 evaluateLValue(SL, Result); 8701 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8702 return true; 8703 } 8704 8705 // FIXME: Missing: @protocol, @selector 8706 }; 8707 } // end anonymous namespace 8708 8709 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8710 bool InvalidBaseOK) { 8711 assert(!E->isValueDependent()); 8712 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8713 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8714 } 8715 8716 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8717 if (E->getOpcode() != BO_Add && 8718 E->getOpcode() != BO_Sub) 8719 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8720 8721 const Expr *PExp = E->getLHS(); 8722 const Expr *IExp = E->getRHS(); 8723 if (IExp->getType()->isPointerType()) 8724 std::swap(PExp, IExp); 8725 8726 bool EvalPtrOK = evaluatePointer(PExp, Result); 8727 if (!EvalPtrOK && !Info.noteFailure()) 8728 return false; 8729 8730 llvm::APSInt Offset; 8731 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8732 return false; 8733 8734 if (E->getOpcode() == BO_Sub) 8735 negateAsSigned(Offset); 8736 8737 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8738 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8739 } 8740 8741 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8742 return evaluateLValue(E->getSubExpr(), Result); 8743 } 8744 8745 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8746 const Expr *SubExpr = E->getSubExpr(); 8747 8748 switch (E->getCastKind()) { 8749 default: 8750 break; 8751 case CK_BitCast: 8752 case CK_CPointerToObjCPointerCast: 8753 case CK_BlockPointerToObjCPointerCast: 8754 case CK_AnyPointerToBlockPointerCast: 8755 case CK_AddressSpaceConversion: 8756 if (!Visit(SubExpr)) 8757 return false; 8758 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8759 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8760 // also static_casts, but we disallow them as a resolution to DR1312. 8761 if (!E->getType()->isVoidPointerType()) { 8762 if (!Result.InvalidBase && !Result.Designator.Invalid && 8763 !Result.IsNullPtr && 8764 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8765 E->getType()->getPointeeType()) && 8766 Info.getStdAllocatorCaller("allocate")) { 8767 // Inside a call to std::allocator::allocate and friends, we permit 8768 // casting from void* back to cv1 T* for a pointer that points to a 8769 // cv2 T. 8770 } else { 8771 Result.Designator.setInvalid(); 8772 if (SubExpr->getType()->isVoidPointerType()) 8773 CCEDiag(E, diag::note_constexpr_invalid_cast) 8774 << 3 << SubExpr->getType(); 8775 else 8776 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8777 } 8778 } 8779 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8780 ZeroInitialization(E); 8781 return true; 8782 8783 case CK_DerivedToBase: 8784 case CK_UncheckedDerivedToBase: 8785 if (!evaluatePointer(E->getSubExpr(), Result)) 8786 return false; 8787 if (!Result.Base && Result.Offset.isZero()) 8788 return true; 8789 8790 // Now figure out the necessary offset to add to the base LV to get from 8791 // the derived class to the base class. 8792 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8793 castAs<PointerType>()->getPointeeType(), 8794 Result); 8795 8796 case CK_BaseToDerived: 8797 if (!Visit(E->getSubExpr())) 8798 return false; 8799 if (!Result.Base && Result.Offset.isZero()) 8800 return true; 8801 return HandleBaseToDerivedCast(Info, E, Result); 8802 8803 case CK_Dynamic: 8804 if (!Visit(E->getSubExpr())) 8805 return false; 8806 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8807 8808 case CK_NullToPointer: 8809 VisitIgnoredValue(E->getSubExpr()); 8810 return ZeroInitialization(E); 8811 8812 case CK_IntegralToPointer: { 8813 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8814 8815 APValue Value; 8816 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8817 break; 8818 8819 if (Value.isInt()) { 8820 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8821 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8822 Result.Base = (Expr*)nullptr; 8823 Result.InvalidBase = false; 8824 Result.Offset = CharUnits::fromQuantity(N); 8825 Result.Designator.setInvalid(); 8826 Result.IsNullPtr = false; 8827 return true; 8828 } else { 8829 // Cast is of an lvalue, no need to change value. 8830 Result.setFrom(Info.Ctx, Value); 8831 return true; 8832 } 8833 } 8834 8835 case CK_ArrayToPointerDecay: { 8836 if (SubExpr->isGLValue()) { 8837 if (!evaluateLValue(SubExpr, Result)) 8838 return false; 8839 } else { 8840 APValue &Value = Info.CurrentCall->createTemporary( 8841 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8842 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8843 return false; 8844 } 8845 // The result is a pointer to the first element of the array. 8846 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8847 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8848 Result.addArray(Info, E, CAT); 8849 else 8850 Result.addUnsizedArray(Info, E, AT->getElementType()); 8851 return true; 8852 } 8853 8854 case CK_FunctionToPointerDecay: 8855 return evaluateLValue(SubExpr, Result); 8856 8857 case CK_LValueToRValue: { 8858 LValue LVal; 8859 if (!evaluateLValue(E->getSubExpr(), LVal)) 8860 return false; 8861 8862 APValue RVal; 8863 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8864 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8865 LVal, RVal)) 8866 return InvalidBaseOK && 8867 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8868 return Success(RVal, E); 8869 } 8870 } 8871 8872 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8873 } 8874 8875 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8876 UnaryExprOrTypeTrait ExprKind) { 8877 // C++ [expr.alignof]p3: 8878 // When alignof is applied to a reference type, the result is the 8879 // alignment of the referenced type. 8880 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8881 T = Ref->getPointeeType(); 8882 8883 if (T.getQualifiers().hasUnaligned()) 8884 return CharUnits::One(); 8885 8886 const bool AlignOfReturnsPreferred = 8887 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8888 8889 // __alignof is defined to return the preferred alignment. 8890 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8891 // as well. 8892 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8893 return Info.Ctx.toCharUnitsFromBits( 8894 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8895 // alignof and _Alignof are defined to return the ABI alignment. 8896 else if (ExprKind == UETT_AlignOf) 8897 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8898 else 8899 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8900 } 8901 8902 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8903 UnaryExprOrTypeTrait ExprKind) { 8904 E = E->IgnoreParens(); 8905 8906 // The kinds of expressions that we have special-case logic here for 8907 // should be kept up to date with the special checks for those 8908 // expressions in Sema. 8909 8910 // alignof decl is always accepted, even if it doesn't make sense: we default 8911 // to 1 in those cases. 8912 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8913 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8914 /*RefAsPointee*/true); 8915 8916 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8917 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8918 /*RefAsPointee*/true); 8919 8920 return GetAlignOfType(Info, E->getType(), ExprKind); 8921 } 8922 8923 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8924 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8925 return Info.Ctx.getDeclAlign(VD); 8926 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8927 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8928 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8929 } 8930 8931 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8932 /// __builtin_is_aligned and __builtin_assume_aligned. 8933 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8934 EvalInfo &Info, APSInt &Alignment) { 8935 if (!EvaluateInteger(E, Alignment, Info)) 8936 return false; 8937 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8938 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8939 return false; 8940 } 8941 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8942 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8943 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8944 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8945 << MaxValue << ForType << Alignment; 8946 return false; 8947 } 8948 // Ensure both alignment and source value have the same bit width so that we 8949 // don't assert when computing the resulting value. 8950 APSInt ExtAlignment = 8951 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8952 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8953 "Alignment should not be changed by ext/trunc"); 8954 Alignment = ExtAlignment; 8955 assert(Alignment.getBitWidth() == SrcWidth); 8956 return true; 8957 } 8958 8959 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8960 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8961 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8962 return true; 8963 8964 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8965 return false; 8966 8967 Result.setInvalid(E); 8968 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8969 Result.addUnsizedArray(Info, E, PointeeTy); 8970 return true; 8971 } 8972 8973 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8974 if (IsConstantCall(E)) 8975 return Success(E); 8976 8977 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8978 return VisitBuiltinCallExpr(E, BuiltinOp); 8979 8980 return visitNonBuiltinCallExpr(E); 8981 } 8982 8983 // Determine if T is a character type for which we guarantee that 8984 // sizeof(T) == 1. 8985 static bool isOneByteCharacterType(QualType T) { 8986 return T->isCharType() || T->isChar8Type(); 8987 } 8988 8989 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8990 unsigned BuiltinOp) { 8991 switch (BuiltinOp) { 8992 case Builtin::BI__builtin_addressof: 8993 return evaluateLValue(E->getArg(0), Result); 8994 case Builtin::BI__builtin_assume_aligned: { 8995 // We need to be very careful here because: if the pointer does not have the 8996 // asserted alignment, then the behavior is undefined, and undefined 8997 // behavior is non-constant. 8998 if (!evaluatePointer(E->getArg(0), Result)) 8999 return false; 9000 9001 LValue OffsetResult(Result); 9002 APSInt Alignment; 9003 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9004 Alignment)) 9005 return false; 9006 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9007 9008 if (E->getNumArgs() > 2) { 9009 APSInt Offset; 9010 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9011 return false; 9012 9013 int64_t AdditionalOffset = -Offset.getZExtValue(); 9014 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9015 } 9016 9017 // If there is a base object, then it must have the correct alignment. 9018 if (OffsetResult.Base) { 9019 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9020 9021 if (BaseAlignment < Align) { 9022 Result.Designator.setInvalid(); 9023 // FIXME: Add support to Diagnostic for long / long long. 9024 CCEDiag(E->getArg(0), 9025 diag::note_constexpr_baa_insufficient_alignment) << 0 9026 << (unsigned)BaseAlignment.getQuantity() 9027 << (unsigned)Align.getQuantity(); 9028 return false; 9029 } 9030 } 9031 9032 // The offset must also have the correct alignment. 9033 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9034 Result.Designator.setInvalid(); 9035 9036 (OffsetResult.Base 9037 ? CCEDiag(E->getArg(0), 9038 diag::note_constexpr_baa_insufficient_alignment) << 1 9039 : CCEDiag(E->getArg(0), 9040 diag::note_constexpr_baa_value_insufficient_alignment)) 9041 << (int)OffsetResult.Offset.getQuantity() 9042 << (unsigned)Align.getQuantity(); 9043 return false; 9044 } 9045 9046 return true; 9047 } 9048 case Builtin::BI__builtin_align_up: 9049 case Builtin::BI__builtin_align_down: { 9050 if (!evaluatePointer(E->getArg(0), Result)) 9051 return false; 9052 APSInt Alignment; 9053 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9054 Alignment)) 9055 return false; 9056 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9057 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9058 // For align_up/align_down, we can return the same value if the alignment 9059 // is known to be greater or equal to the requested value. 9060 if (PtrAlign.getQuantity() >= Alignment) 9061 return true; 9062 9063 // The alignment could be greater than the minimum at run-time, so we cannot 9064 // infer much about the resulting pointer value. One case is possible: 9065 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9066 // can infer the correct index if the requested alignment is smaller than 9067 // the base alignment so we can perform the computation on the offset. 9068 if (BaseAlignment.getQuantity() >= Alignment) { 9069 assert(Alignment.getBitWidth() <= 64 && 9070 "Cannot handle > 64-bit address-space"); 9071 uint64_t Alignment64 = Alignment.getZExtValue(); 9072 CharUnits NewOffset = CharUnits::fromQuantity( 9073 BuiltinOp == Builtin::BI__builtin_align_down 9074 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9075 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9076 Result.adjustOffset(NewOffset - Result.Offset); 9077 // TODO: diagnose out-of-bounds values/only allow for arrays? 9078 return true; 9079 } 9080 // Otherwise, we cannot constant-evaluate the result. 9081 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9082 << Alignment; 9083 return false; 9084 } 9085 case Builtin::BI__builtin_operator_new: 9086 return HandleOperatorNewCall(Info, E, Result); 9087 case Builtin::BI__builtin_launder: 9088 return evaluatePointer(E->getArg(0), Result); 9089 case Builtin::BIstrchr: 9090 case Builtin::BIwcschr: 9091 case Builtin::BImemchr: 9092 case Builtin::BIwmemchr: 9093 if (Info.getLangOpts().CPlusPlus11) 9094 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9095 << /*isConstexpr*/0 << /*isConstructor*/0 9096 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9097 else 9098 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9099 LLVM_FALLTHROUGH; 9100 case Builtin::BI__builtin_strchr: 9101 case Builtin::BI__builtin_wcschr: 9102 case Builtin::BI__builtin_memchr: 9103 case Builtin::BI__builtin_char_memchr: 9104 case Builtin::BI__builtin_wmemchr: { 9105 if (!Visit(E->getArg(0))) 9106 return false; 9107 APSInt Desired; 9108 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9109 return false; 9110 uint64_t MaxLength = uint64_t(-1); 9111 if (BuiltinOp != Builtin::BIstrchr && 9112 BuiltinOp != Builtin::BIwcschr && 9113 BuiltinOp != Builtin::BI__builtin_strchr && 9114 BuiltinOp != Builtin::BI__builtin_wcschr) { 9115 APSInt N; 9116 if (!EvaluateInteger(E->getArg(2), N, Info)) 9117 return false; 9118 MaxLength = N.getExtValue(); 9119 } 9120 // We cannot find the value if there are no candidates to match against. 9121 if (MaxLength == 0u) 9122 return ZeroInitialization(E); 9123 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9124 Result.Designator.Invalid) 9125 return false; 9126 QualType CharTy = Result.Designator.getType(Info.Ctx); 9127 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9128 BuiltinOp == Builtin::BI__builtin_memchr; 9129 assert(IsRawByte || 9130 Info.Ctx.hasSameUnqualifiedType( 9131 CharTy, E->getArg(0)->getType()->getPointeeType())); 9132 // Pointers to const void may point to objects of incomplete type. 9133 if (IsRawByte && CharTy->isIncompleteType()) { 9134 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9135 return false; 9136 } 9137 // Give up on byte-oriented matching against multibyte elements. 9138 // FIXME: We can compare the bytes in the correct order. 9139 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9140 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9141 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9142 << CharTy; 9143 return false; 9144 } 9145 // Figure out what value we're actually looking for (after converting to 9146 // the corresponding unsigned type if necessary). 9147 uint64_t DesiredVal; 9148 bool StopAtNull = false; 9149 switch (BuiltinOp) { 9150 case Builtin::BIstrchr: 9151 case Builtin::BI__builtin_strchr: 9152 // strchr compares directly to the passed integer, and therefore 9153 // always fails if given an int that is not a char. 9154 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9155 E->getArg(1)->getType(), 9156 Desired), 9157 Desired)) 9158 return ZeroInitialization(E); 9159 StopAtNull = true; 9160 LLVM_FALLTHROUGH; 9161 case Builtin::BImemchr: 9162 case Builtin::BI__builtin_memchr: 9163 case Builtin::BI__builtin_char_memchr: 9164 // memchr compares by converting both sides to unsigned char. That's also 9165 // correct for strchr if we get this far (to cope with plain char being 9166 // unsigned in the strchr case). 9167 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9168 break; 9169 9170 case Builtin::BIwcschr: 9171 case Builtin::BI__builtin_wcschr: 9172 StopAtNull = true; 9173 LLVM_FALLTHROUGH; 9174 case Builtin::BIwmemchr: 9175 case Builtin::BI__builtin_wmemchr: 9176 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9177 DesiredVal = Desired.getZExtValue(); 9178 break; 9179 } 9180 9181 for (; MaxLength; --MaxLength) { 9182 APValue Char; 9183 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9184 !Char.isInt()) 9185 return false; 9186 if (Char.getInt().getZExtValue() == DesiredVal) 9187 return true; 9188 if (StopAtNull && !Char.getInt()) 9189 break; 9190 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9191 return false; 9192 } 9193 // Not found: return nullptr. 9194 return ZeroInitialization(E); 9195 } 9196 9197 case Builtin::BImemcpy: 9198 case Builtin::BImemmove: 9199 case Builtin::BIwmemcpy: 9200 case Builtin::BIwmemmove: 9201 if (Info.getLangOpts().CPlusPlus11) 9202 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9203 << /*isConstexpr*/0 << /*isConstructor*/0 9204 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9205 else 9206 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9207 LLVM_FALLTHROUGH; 9208 case Builtin::BI__builtin_memcpy: 9209 case Builtin::BI__builtin_memmove: 9210 case Builtin::BI__builtin_wmemcpy: 9211 case Builtin::BI__builtin_wmemmove: { 9212 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9213 BuiltinOp == Builtin::BIwmemmove || 9214 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9215 BuiltinOp == Builtin::BI__builtin_wmemmove; 9216 bool Move = BuiltinOp == Builtin::BImemmove || 9217 BuiltinOp == Builtin::BIwmemmove || 9218 BuiltinOp == Builtin::BI__builtin_memmove || 9219 BuiltinOp == Builtin::BI__builtin_wmemmove; 9220 9221 // The result of mem* is the first argument. 9222 if (!Visit(E->getArg(0))) 9223 return false; 9224 LValue Dest = Result; 9225 9226 LValue Src; 9227 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9228 return false; 9229 9230 APSInt N; 9231 if (!EvaluateInteger(E->getArg(2), N, Info)) 9232 return false; 9233 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9234 9235 // If the size is zero, we treat this as always being a valid no-op. 9236 // (Even if one of the src and dest pointers is null.) 9237 if (!N) 9238 return true; 9239 9240 // Otherwise, if either of the operands is null, we can't proceed. Don't 9241 // try to determine the type of the copied objects, because there aren't 9242 // any. 9243 if (!Src.Base || !Dest.Base) { 9244 APValue Val; 9245 (!Src.Base ? Src : Dest).moveInto(Val); 9246 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9247 << Move << WChar << !!Src.Base 9248 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9249 return false; 9250 } 9251 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9252 return false; 9253 9254 // We require that Src and Dest are both pointers to arrays of 9255 // trivially-copyable type. (For the wide version, the designator will be 9256 // invalid if the designated object is not a wchar_t.) 9257 QualType T = Dest.Designator.getType(Info.Ctx); 9258 QualType SrcT = Src.Designator.getType(Info.Ctx); 9259 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9260 // FIXME: Consider using our bit_cast implementation to support this. 9261 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9262 return false; 9263 } 9264 if (T->isIncompleteType()) { 9265 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9266 return false; 9267 } 9268 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9269 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9270 return false; 9271 } 9272 9273 // Figure out how many T's we're copying. 9274 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9275 if (!WChar) { 9276 uint64_t Remainder; 9277 llvm::APInt OrigN = N; 9278 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9279 if (Remainder) { 9280 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9281 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9282 << (unsigned)TSize; 9283 return false; 9284 } 9285 } 9286 9287 // Check that the copying will remain within the arrays, just so that we 9288 // can give a more meaningful diagnostic. This implicitly also checks that 9289 // N fits into 64 bits. 9290 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9291 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9292 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9293 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9294 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9295 << toString(N, 10, /*Signed*/false); 9296 return false; 9297 } 9298 uint64_t NElems = N.getZExtValue(); 9299 uint64_t NBytes = NElems * TSize; 9300 9301 // Check for overlap. 9302 int Direction = 1; 9303 if (HasSameBase(Src, Dest)) { 9304 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9305 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9306 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9307 // Dest is inside the source region. 9308 if (!Move) { 9309 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9310 return false; 9311 } 9312 // For memmove and friends, copy backwards. 9313 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9314 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9315 return false; 9316 Direction = -1; 9317 } else if (!Move && SrcOffset >= DestOffset && 9318 SrcOffset - DestOffset < NBytes) { 9319 // Src is inside the destination region for memcpy: invalid. 9320 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9321 return false; 9322 } 9323 } 9324 9325 while (true) { 9326 APValue Val; 9327 // FIXME: Set WantObjectRepresentation to true if we're copying a 9328 // char-like type? 9329 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9330 !handleAssignment(Info, E, Dest, T, Val)) 9331 return false; 9332 // Do not iterate past the last element; if we're copying backwards, that 9333 // might take us off the start of the array. 9334 if (--NElems == 0) 9335 return true; 9336 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9337 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9338 return false; 9339 } 9340 } 9341 9342 default: 9343 break; 9344 } 9345 9346 return visitNonBuiltinCallExpr(E); 9347 } 9348 9349 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9350 APValue &Result, const InitListExpr *ILE, 9351 QualType AllocType); 9352 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9353 APValue &Result, 9354 const CXXConstructExpr *CCE, 9355 QualType AllocType); 9356 9357 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9358 if (!Info.getLangOpts().CPlusPlus20) 9359 Info.CCEDiag(E, diag::note_constexpr_new); 9360 9361 // We cannot speculatively evaluate a delete expression. 9362 if (Info.SpeculativeEvaluationDepth) 9363 return false; 9364 9365 FunctionDecl *OperatorNew = E->getOperatorNew(); 9366 9367 bool IsNothrow = false; 9368 bool IsPlacement = false; 9369 if (OperatorNew->isReservedGlobalPlacementOperator() && 9370 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9371 // FIXME Support array placement new. 9372 assert(E->getNumPlacementArgs() == 1); 9373 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9374 return false; 9375 if (Result.Designator.Invalid) 9376 return false; 9377 IsPlacement = true; 9378 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9379 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9380 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9381 return false; 9382 } else if (E->getNumPlacementArgs()) { 9383 // The only new-placement list we support is of the form (std::nothrow). 9384 // 9385 // FIXME: There is no restriction on this, but it's not clear that any 9386 // other form makes any sense. We get here for cases such as: 9387 // 9388 // new (std::align_val_t{N}) X(int) 9389 // 9390 // (which should presumably be valid only if N is a multiple of 9391 // alignof(int), and in any case can't be deallocated unless N is 9392 // alignof(X) and X has new-extended alignment). 9393 if (E->getNumPlacementArgs() != 1 || 9394 !E->getPlacementArg(0)->getType()->isNothrowT()) 9395 return Error(E, diag::note_constexpr_new_placement); 9396 9397 LValue Nothrow; 9398 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9399 return false; 9400 IsNothrow = true; 9401 } 9402 9403 const Expr *Init = E->getInitializer(); 9404 const InitListExpr *ResizedArrayILE = nullptr; 9405 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9406 bool ValueInit = false; 9407 9408 QualType AllocType = E->getAllocatedType(); 9409 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9410 const Expr *Stripped = *ArraySize; 9411 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9412 Stripped = ICE->getSubExpr()) 9413 if (ICE->getCastKind() != CK_NoOp && 9414 ICE->getCastKind() != CK_IntegralCast) 9415 break; 9416 9417 llvm::APSInt ArrayBound; 9418 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9419 return false; 9420 9421 // C++ [expr.new]p9: 9422 // The expression is erroneous if: 9423 // -- [...] its value before converting to size_t [or] applying the 9424 // second standard conversion sequence is less than zero 9425 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9426 if (IsNothrow) 9427 return ZeroInitialization(E); 9428 9429 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9430 << ArrayBound << (*ArraySize)->getSourceRange(); 9431 return false; 9432 } 9433 9434 // -- its value is such that the size of the allocated object would 9435 // exceed the implementation-defined limit 9436 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9437 ArrayBound) > 9438 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9439 if (IsNothrow) 9440 return ZeroInitialization(E); 9441 9442 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9443 << ArrayBound << (*ArraySize)->getSourceRange(); 9444 return false; 9445 } 9446 9447 // -- the new-initializer is a braced-init-list and the number of 9448 // array elements for which initializers are provided [...] 9449 // exceeds the number of elements to initialize 9450 if (!Init) { 9451 // No initialization is performed. 9452 } else if (isa<CXXScalarValueInitExpr>(Init) || 9453 isa<ImplicitValueInitExpr>(Init)) { 9454 ValueInit = true; 9455 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9456 ResizedArrayCCE = CCE; 9457 } else { 9458 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9459 assert(CAT && "unexpected type for array initializer"); 9460 9461 unsigned Bits = 9462 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9463 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9464 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9465 if (InitBound.ugt(AllocBound)) { 9466 if (IsNothrow) 9467 return ZeroInitialization(E); 9468 9469 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9470 << toString(AllocBound, 10, /*Signed=*/false) 9471 << toString(InitBound, 10, /*Signed=*/false) 9472 << (*ArraySize)->getSourceRange(); 9473 return false; 9474 } 9475 9476 // If the sizes differ, we must have an initializer list, and we need 9477 // special handling for this case when we initialize. 9478 if (InitBound != AllocBound) 9479 ResizedArrayILE = cast<InitListExpr>(Init); 9480 } 9481 9482 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9483 ArrayType::Normal, 0); 9484 } else { 9485 assert(!AllocType->isArrayType() && 9486 "array allocation with non-array new"); 9487 } 9488 9489 APValue *Val; 9490 if (IsPlacement) { 9491 AccessKinds AK = AK_Construct; 9492 struct FindObjectHandler { 9493 EvalInfo &Info; 9494 const Expr *E; 9495 QualType AllocType; 9496 const AccessKinds AccessKind; 9497 APValue *Value; 9498 9499 typedef bool result_type; 9500 bool failed() { return false; } 9501 bool found(APValue &Subobj, QualType SubobjType) { 9502 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9503 // old name of the object to be used to name the new object. 9504 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9505 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9506 SubobjType << AllocType; 9507 return false; 9508 } 9509 Value = &Subobj; 9510 return true; 9511 } 9512 bool found(APSInt &Value, QualType SubobjType) { 9513 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9514 return false; 9515 } 9516 bool found(APFloat &Value, QualType SubobjType) { 9517 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9518 return false; 9519 } 9520 } Handler = {Info, E, AllocType, AK, nullptr}; 9521 9522 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9523 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9524 return false; 9525 9526 Val = Handler.Value; 9527 9528 // [basic.life]p1: 9529 // The lifetime of an object o of type T ends when [...] the storage 9530 // which the object occupies is [...] reused by an object that is not 9531 // nested within o (6.6.2). 9532 *Val = APValue(); 9533 } else { 9534 // Perform the allocation and obtain a pointer to the resulting object. 9535 Val = Info.createHeapAlloc(E, AllocType, Result); 9536 if (!Val) 9537 return false; 9538 } 9539 9540 if (ValueInit) { 9541 ImplicitValueInitExpr VIE(AllocType); 9542 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9543 return false; 9544 } else if (ResizedArrayILE) { 9545 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9546 AllocType)) 9547 return false; 9548 } else if (ResizedArrayCCE) { 9549 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9550 AllocType)) 9551 return false; 9552 } else if (Init) { 9553 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9554 return false; 9555 } else if (!getDefaultInitValue(AllocType, *Val)) { 9556 return false; 9557 } 9558 9559 // Array new returns a pointer to the first element, not a pointer to the 9560 // array. 9561 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9562 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9563 9564 return true; 9565 } 9566 //===----------------------------------------------------------------------===// 9567 // Member Pointer Evaluation 9568 //===----------------------------------------------------------------------===// 9569 9570 namespace { 9571 class MemberPointerExprEvaluator 9572 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9573 MemberPtr &Result; 9574 9575 bool Success(const ValueDecl *D) { 9576 Result = MemberPtr(D); 9577 return true; 9578 } 9579 public: 9580 9581 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9582 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9583 9584 bool Success(const APValue &V, const Expr *E) { 9585 Result.setFrom(V); 9586 return true; 9587 } 9588 bool ZeroInitialization(const Expr *E) { 9589 return Success((const ValueDecl*)nullptr); 9590 } 9591 9592 bool VisitCastExpr(const CastExpr *E); 9593 bool VisitUnaryAddrOf(const UnaryOperator *E); 9594 }; 9595 } // end anonymous namespace 9596 9597 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9598 EvalInfo &Info) { 9599 assert(!E->isValueDependent()); 9600 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9601 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9602 } 9603 9604 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9605 switch (E->getCastKind()) { 9606 default: 9607 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9608 9609 case CK_NullToMemberPointer: 9610 VisitIgnoredValue(E->getSubExpr()); 9611 return ZeroInitialization(E); 9612 9613 case CK_BaseToDerivedMemberPointer: { 9614 if (!Visit(E->getSubExpr())) 9615 return false; 9616 if (E->path_empty()) 9617 return true; 9618 // Base-to-derived member pointer casts store the path in derived-to-base 9619 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9620 // the wrong end of the derived->base arc, so stagger the path by one class. 9621 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9622 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9623 PathI != PathE; ++PathI) { 9624 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9625 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9626 if (!Result.castToDerived(Derived)) 9627 return Error(E); 9628 } 9629 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9630 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9631 return Error(E); 9632 return true; 9633 } 9634 9635 case CK_DerivedToBaseMemberPointer: 9636 if (!Visit(E->getSubExpr())) 9637 return false; 9638 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9639 PathE = E->path_end(); PathI != PathE; ++PathI) { 9640 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9641 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9642 if (!Result.castToBase(Base)) 9643 return Error(E); 9644 } 9645 return true; 9646 } 9647 } 9648 9649 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9650 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9651 // member can be formed. 9652 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9653 } 9654 9655 //===----------------------------------------------------------------------===// 9656 // Record Evaluation 9657 //===----------------------------------------------------------------------===// 9658 9659 namespace { 9660 class RecordExprEvaluator 9661 : public ExprEvaluatorBase<RecordExprEvaluator> { 9662 const LValue &This; 9663 APValue &Result; 9664 public: 9665 9666 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9667 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9668 9669 bool Success(const APValue &V, const Expr *E) { 9670 Result = V; 9671 return true; 9672 } 9673 bool ZeroInitialization(const Expr *E) { 9674 return ZeroInitialization(E, E->getType()); 9675 } 9676 bool ZeroInitialization(const Expr *E, QualType T); 9677 9678 bool VisitCallExpr(const CallExpr *E) { 9679 return handleCallExpr(E, Result, &This); 9680 } 9681 bool VisitCastExpr(const CastExpr *E); 9682 bool VisitInitListExpr(const InitListExpr *E); 9683 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9684 return VisitCXXConstructExpr(E, E->getType()); 9685 } 9686 bool VisitLambdaExpr(const LambdaExpr *E); 9687 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9688 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9689 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9690 bool VisitBinCmp(const BinaryOperator *E); 9691 }; 9692 } 9693 9694 /// Perform zero-initialization on an object of non-union class type. 9695 /// C++11 [dcl.init]p5: 9696 /// To zero-initialize an object or reference of type T means: 9697 /// [...] 9698 /// -- if T is a (possibly cv-qualified) non-union class type, 9699 /// each non-static data member and each base-class subobject is 9700 /// zero-initialized 9701 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9702 const RecordDecl *RD, 9703 const LValue &This, APValue &Result) { 9704 assert(!RD->isUnion() && "Expected non-union class type"); 9705 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9706 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9707 std::distance(RD->field_begin(), RD->field_end())); 9708 9709 if (RD->isInvalidDecl()) return false; 9710 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9711 9712 if (CD) { 9713 unsigned Index = 0; 9714 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9715 End = CD->bases_end(); I != End; ++I, ++Index) { 9716 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9717 LValue Subobject = This; 9718 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9719 return false; 9720 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9721 Result.getStructBase(Index))) 9722 return false; 9723 } 9724 } 9725 9726 for (const auto *I : RD->fields()) { 9727 // -- if T is a reference type, no initialization is performed. 9728 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9729 continue; 9730 9731 LValue Subobject = This; 9732 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9733 return false; 9734 9735 ImplicitValueInitExpr VIE(I->getType()); 9736 if (!EvaluateInPlace( 9737 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9738 return false; 9739 } 9740 9741 return true; 9742 } 9743 9744 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9745 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9746 if (RD->isInvalidDecl()) return false; 9747 if (RD->isUnion()) { 9748 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9749 // object's first non-static named data member is zero-initialized 9750 RecordDecl::field_iterator I = RD->field_begin(); 9751 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9752 ++I; 9753 if (I == RD->field_end()) { 9754 Result = APValue((const FieldDecl*)nullptr); 9755 return true; 9756 } 9757 9758 LValue Subobject = This; 9759 if (!HandleLValueMember(Info, E, Subobject, *I)) 9760 return false; 9761 Result = APValue(*I); 9762 ImplicitValueInitExpr VIE(I->getType()); 9763 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9764 } 9765 9766 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9767 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9768 return false; 9769 } 9770 9771 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9772 } 9773 9774 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9775 switch (E->getCastKind()) { 9776 default: 9777 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9778 9779 case CK_ConstructorConversion: 9780 return Visit(E->getSubExpr()); 9781 9782 case CK_DerivedToBase: 9783 case CK_UncheckedDerivedToBase: { 9784 APValue DerivedObject; 9785 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9786 return false; 9787 if (!DerivedObject.isStruct()) 9788 return Error(E->getSubExpr()); 9789 9790 // Derived-to-base rvalue conversion: just slice off the derived part. 9791 APValue *Value = &DerivedObject; 9792 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9793 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9794 PathE = E->path_end(); PathI != PathE; ++PathI) { 9795 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9796 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9797 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9798 RD = Base; 9799 } 9800 Result = *Value; 9801 return true; 9802 } 9803 } 9804 } 9805 9806 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9807 if (E->isTransparent()) 9808 return Visit(E->getInit(0)); 9809 9810 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9811 if (RD->isInvalidDecl()) return false; 9812 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9813 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9814 9815 EvalInfo::EvaluatingConstructorRAII EvalObj( 9816 Info, 9817 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9818 CXXRD && CXXRD->getNumBases()); 9819 9820 if (RD->isUnion()) { 9821 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9822 Result = APValue(Field); 9823 if (!Field) 9824 return true; 9825 9826 // If the initializer list for a union does not contain any elements, the 9827 // first element of the union is value-initialized. 9828 // FIXME: The element should be initialized from an initializer list. 9829 // Is this difference ever observable for initializer lists which 9830 // we don't build? 9831 ImplicitValueInitExpr VIE(Field->getType()); 9832 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9833 9834 LValue Subobject = This; 9835 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9836 return false; 9837 9838 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9839 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9840 isa<CXXDefaultInitExpr>(InitExpr)); 9841 9842 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9843 if (Field->isBitField()) 9844 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9845 Field); 9846 return true; 9847 } 9848 9849 return false; 9850 } 9851 9852 if (!Result.hasValue()) 9853 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9854 std::distance(RD->field_begin(), RD->field_end())); 9855 unsigned ElementNo = 0; 9856 bool Success = true; 9857 9858 // Initialize base classes. 9859 if (CXXRD && CXXRD->getNumBases()) { 9860 for (const auto &Base : CXXRD->bases()) { 9861 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9862 const Expr *Init = E->getInit(ElementNo); 9863 9864 LValue Subobject = This; 9865 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9866 return false; 9867 9868 APValue &FieldVal = Result.getStructBase(ElementNo); 9869 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9870 if (!Info.noteFailure()) 9871 return false; 9872 Success = false; 9873 } 9874 ++ElementNo; 9875 } 9876 9877 EvalObj.finishedConstructingBases(); 9878 } 9879 9880 // Initialize members. 9881 for (const auto *Field : RD->fields()) { 9882 // Anonymous bit-fields are not considered members of the class for 9883 // purposes of aggregate initialization. 9884 if (Field->isUnnamedBitfield()) 9885 continue; 9886 9887 LValue Subobject = This; 9888 9889 bool HaveInit = ElementNo < E->getNumInits(); 9890 9891 // FIXME: Diagnostics here should point to the end of the initializer 9892 // list, not the start. 9893 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9894 Subobject, Field, &Layout)) 9895 return false; 9896 9897 // Perform an implicit value-initialization for members beyond the end of 9898 // the initializer list. 9899 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9900 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9901 9902 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9903 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9904 isa<CXXDefaultInitExpr>(Init)); 9905 9906 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9907 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9908 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9909 FieldVal, Field))) { 9910 if (!Info.noteFailure()) 9911 return false; 9912 Success = false; 9913 } 9914 } 9915 9916 EvalObj.finishedConstructingFields(); 9917 9918 return Success; 9919 } 9920 9921 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9922 QualType T) { 9923 // Note that E's type is not necessarily the type of our class here; we might 9924 // be initializing an array element instead. 9925 const CXXConstructorDecl *FD = E->getConstructor(); 9926 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9927 9928 bool ZeroInit = E->requiresZeroInitialization(); 9929 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9930 // If we've already performed zero-initialization, we're already done. 9931 if (Result.hasValue()) 9932 return true; 9933 9934 if (ZeroInit) 9935 return ZeroInitialization(E, T); 9936 9937 return getDefaultInitValue(T, Result); 9938 } 9939 9940 const FunctionDecl *Definition = nullptr; 9941 auto Body = FD->getBody(Definition); 9942 9943 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9944 return false; 9945 9946 // Avoid materializing a temporary for an elidable copy/move constructor. 9947 if (E->isElidable() && !ZeroInit) { 9948 // FIXME: This only handles the simplest case, where the source object 9949 // is passed directly as the first argument to the constructor. 9950 // This should also handle stepping though implicit casts and 9951 // and conversion sequences which involve two steps, with a 9952 // conversion operator followed by a converting constructor. 9953 const Expr *SrcObj = E->getArg(0); 9954 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 9955 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 9956 if (const MaterializeTemporaryExpr *ME = 9957 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 9958 return Visit(ME->getSubExpr()); 9959 } 9960 9961 if (ZeroInit && !ZeroInitialization(E, T)) 9962 return false; 9963 9964 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9965 return HandleConstructorCall(E, This, Args, 9966 cast<CXXConstructorDecl>(Definition), Info, 9967 Result); 9968 } 9969 9970 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9971 const CXXInheritedCtorInitExpr *E) { 9972 if (!Info.CurrentCall) { 9973 assert(Info.checkingPotentialConstantExpression()); 9974 return false; 9975 } 9976 9977 const CXXConstructorDecl *FD = E->getConstructor(); 9978 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9979 return false; 9980 9981 const FunctionDecl *Definition = nullptr; 9982 auto Body = FD->getBody(Definition); 9983 9984 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9985 return false; 9986 9987 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9988 cast<CXXConstructorDecl>(Definition), Info, 9989 Result); 9990 } 9991 9992 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9993 const CXXStdInitializerListExpr *E) { 9994 const ConstantArrayType *ArrayType = 9995 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9996 9997 LValue Array; 9998 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9999 return false; 10000 10001 // Get a pointer to the first element of the array. 10002 Array.addArray(Info, E, ArrayType); 10003 10004 auto InvalidType = [&] { 10005 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10006 << E->getType(); 10007 return false; 10008 }; 10009 10010 // FIXME: Perform the checks on the field types in SemaInit. 10011 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10012 RecordDecl::field_iterator Field = Record->field_begin(); 10013 if (Field == Record->field_end()) 10014 return InvalidType(); 10015 10016 // Start pointer. 10017 if (!Field->getType()->isPointerType() || 10018 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10019 ArrayType->getElementType())) 10020 return InvalidType(); 10021 10022 // FIXME: What if the initializer_list type has base classes, etc? 10023 Result = APValue(APValue::UninitStruct(), 0, 2); 10024 Array.moveInto(Result.getStructField(0)); 10025 10026 if (++Field == Record->field_end()) 10027 return InvalidType(); 10028 10029 if (Field->getType()->isPointerType() && 10030 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10031 ArrayType->getElementType())) { 10032 // End pointer. 10033 if (!HandleLValueArrayAdjustment(Info, E, Array, 10034 ArrayType->getElementType(), 10035 ArrayType->getSize().getZExtValue())) 10036 return false; 10037 Array.moveInto(Result.getStructField(1)); 10038 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10039 // Length. 10040 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10041 else 10042 return InvalidType(); 10043 10044 if (++Field != Record->field_end()) 10045 return InvalidType(); 10046 10047 return true; 10048 } 10049 10050 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10051 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10052 if (ClosureClass->isInvalidDecl()) 10053 return false; 10054 10055 const size_t NumFields = 10056 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10057 10058 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10059 E->capture_init_end()) && 10060 "The number of lambda capture initializers should equal the number of " 10061 "fields within the closure type"); 10062 10063 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10064 // Iterate through all the lambda's closure object's fields and initialize 10065 // them. 10066 auto *CaptureInitIt = E->capture_init_begin(); 10067 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10068 bool Success = true; 10069 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10070 for (const auto *Field : ClosureClass->fields()) { 10071 assert(CaptureInitIt != E->capture_init_end()); 10072 // Get the initializer for this field 10073 Expr *const CurFieldInit = *CaptureInitIt++; 10074 10075 // If there is no initializer, either this is a VLA or an error has 10076 // occurred. 10077 if (!CurFieldInit) 10078 return Error(E); 10079 10080 LValue Subobject = This; 10081 10082 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10083 return false; 10084 10085 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10086 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10087 if (!Info.keepEvaluatingAfterFailure()) 10088 return false; 10089 Success = false; 10090 } 10091 ++CaptureIt; 10092 } 10093 return Success; 10094 } 10095 10096 static bool EvaluateRecord(const Expr *E, const LValue &This, 10097 APValue &Result, EvalInfo &Info) { 10098 assert(!E->isValueDependent()); 10099 assert(E->isPRValue() && E->getType()->isRecordType() && 10100 "can't evaluate expression as a record rvalue"); 10101 return RecordExprEvaluator(Info, This, Result).Visit(E); 10102 } 10103 10104 //===----------------------------------------------------------------------===// 10105 // Temporary Evaluation 10106 // 10107 // Temporaries are represented in the AST as rvalues, but generally behave like 10108 // lvalues. The full-object of which the temporary is a subobject is implicitly 10109 // materialized so that a reference can bind to it. 10110 //===----------------------------------------------------------------------===// 10111 namespace { 10112 class TemporaryExprEvaluator 10113 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10114 public: 10115 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10116 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10117 10118 /// Visit an expression which constructs the value of this temporary. 10119 bool VisitConstructExpr(const Expr *E) { 10120 APValue &Value = Info.CurrentCall->createTemporary( 10121 E, E->getType(), ScopeKind::FullExpression, Result); 10122 return EvaluateInPlace(Value, Info, Result, E); 10123 } 10124 10125 bool VisitCastExpr(const CastExpr *E) { 10126 switch (E->getCastKind()) { 10127 default: 10128 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10129 10130 case CK_ConstructorConversion: 10131 return VisitConstructExpr(E->getSubExpr()); 10132 } 10133 } 10134 bool VisitInitListExpr(const InitListExpr *E) { 10135 return VisitConstructExpr(E); 10136 } 10137 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10138 return VisitConstructExpr(E); 10139 } 10140 bool VisitCallExpr(const CallExpr *E) { 10141 return VisitConstructExpr(E); 10142 } 10143 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10144 return VisitConstructExpr(E); 10145 } 10146 bool VisitLambdaExpr(const LambdaExpr *E) { 10147 return VisitConstructExpr(E); 10148 } 10149 }; 10150 } // end anonymous namespace 10151 10152 /// Evaluate an expression of record type as a temporary. 10153 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10154 assert(!E->isValueDependent()); 10155 assert(E->isPRValue() && E->getType()->isRecordType()); 10156 return TemporaryExprEvaluator(Info, Result).Visit(E); 10157 } 10158 10159 //===----------------------------------------------------------------------===// 10160 // Vector Evaluation 10161 //===----------------------------------------------------------------------===// 10162 10163 namespace { 10164 class VectorExprEvaluator 10165 : public ExprEvaluatorBase<VectorExprEvaluator> { 10166 APValue &Result; 10167 public: 10168 10169 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10170 : ExprEvaluatorBaseTy(info), Result(Result) {} 10171 10172 bool Success(ArrayRef<APValue> V, const Expr *E) { 10173 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10174 // FIXME: remove this APValue copy. 10175 Result = APValue(V.data(), V.size()); 10176 return true; 10177 } 10178 bool Success(const APValue &V, const Expr *E) { 10179 assert(V.isVector()); 10180 Result = V; 10181 return true; 10182 } 10183 bool ZeroInitialization(const Expr *E); 10184 10185 bool VisitUnaryReal(const UnaryOperator *E) 10186 { return Visit(E->getSubExpr()); } 10187 bool VisitCastExpr(const CastExpr* E); 10188 bool VisitInitListExpr(const InitListExpr *E); 10189 bool VisitUnaryImag(const UnaryOperator *E); 10190 bool VisitBinaryOperator(const BinaryOperator *E); 10191 bool VisitUnaryOperator(const UnaryOperator *E); 10192 // FIXME: Missing: conditional operator (for GNU 10193 // conditional select), shufflevector, ExtVectorElementExpr 10194 }; 10195 } // end anonymous namespace 10196 10197 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10198 assert(E->isPRValue() && E->getType()->isVectorType() && 10199 "not a vector prvalue"); 10200 return VectorExprEvaluator(Info, Result).Visit(E); 10201 } 10202 10203 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10204 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10205 unsigned NElts = VTy->getNumElements(); 10206 10207 const Expr *SE = E->getSubExpr(); 10208 QualType SETy = SE->getType(); 10209 10210 switch (E->getCastKind()) { 10211 case CK_VectorSplat: { 10212 APValue Val = APValue(); 10213 if (SETy->isIntegerType()) { 10214 APSInt IntResult; 10215 if (!EvaluateInteger(SE, IntResult, Info)) 10216 return false; 10217 Val = APValue(std::move(IntResult)); 10218 } else if (SETy->isRealFloatingType()) { 10219 APFloat FloatResult(0.0); 10220 if (!EvaluateFloat(SE, FloatResult, Info)) 10221 return false; 10222 Val = APValue(std::move(FloatResult)); 10223 } else { 10224 return Error(E); 10225 } 10226 10227 // Splat and create vector APValue. 10228 SmallVector<APValue, 4> Elts(NElts, Val); 10229 return Success(Elts, E); 10230 } 10231 case CK_BitCast: { 10232 // Evaluate the operand into an APInt we can extract from. 10233 llvm::APInt SValInt; 10234 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10235 return false; 10236 // Extract the elements 10237 QualType EltTy = VTy->getElementType(); 10238 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10239 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10240 SmallVector<APValue, 4> Elts; 10241 if (EltTy->isRealFloatingType()) { 10242 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10243 unsigned FloatEltSize = EltSize; 10244 if (&Sem == &APFloat::x87DoubleExtended()) 10245 FloatEltSize = 80; 10246 for (unsigned i = 0; i < NElts; i++) { 10247 llvm::APInt Elt; 10248 if (BigEndian) 10249 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10250 else 10251 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10252 Elts.push_back(APValue(APFloat(Sem, Elt))); 10253 } 10254 } else if (EltTy->isIntegerType()) { 10255 for (unsigned i = 0; i < NElts; i++) { 10256 llvm::APInt Elt; 10257 if (BigEndian) 10258 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10259 else 10260 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10261 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10262 } 10263 } else { 10264 return Error(E); 10265 } 10266 return Success(Elts, E); 10267 } 10268 default: 10269 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10270 } 10271 } 10272 10273 bool 10274 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10275 const VectorType *VT = E->getType()->castAs<VectorType>(); 10276 unsigned NumInits = E->getNumInits(); 10277 unsigned NumElements = VT->getNumElements(); 10278 10279 QualType EltTy = VT->getElementType(); 10280 SmallVector<APValue, 4> Elements; 10281 10282 // The number of initializers can be less than the number of 10283 // vector elements. For OpenCL, this can be due to nested vector 10284 // initialization. For GCC compatibility, missing trailing elements 10285 // should be initialized with zeroes. 10286 unsigned CountInits = 0, CountElts = 0; 10287 while (CountElts < NumElements) { 10288 // Handle nested vector initialization. 10289 if (CountInits < NumInits 10290 && E->getInit(CountInits)->getType()->isVectorType()) { 10291 APValue v; 10292 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10293 return Error(E); 10294 unsigned vlen = v.getVectorLength(); 10295 for (unsigned j = 0; j < vlen; j++) 10296 Elements.push_back(v.getVectorElt(j)); 10297 CountElts += vlen; 10298 } else if (EltTy->isIntegerType()) { 10299 llvm::APSInt sInt(32); 10300 if (CountInits < NumInits) { 10301 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10302 return false; 10303 } else // trailing integer zero. 10304 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10305 Elements.push_back(APValue(sInt)); 10306 CountElts++; 10307 } else { 10308 llvm::APFloat f(0.0); 10309 if (CountInits < NumInits) { 10310 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10311 return false; 10312 } else // trailing float zero. 10313 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10314 Elements.push_back(APValue(f)); 10315 CountElts++; 10316 } 10317 CountInits++; 10318 } 10319 return Success(Elements, E); 10320 } 10321 10322 bool 10323 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10324 const auto *VT = E->getType()->castAs<VectorType>(); 10325 QualType EltTy = VT->getElementType(); 10326 APValue ZeroElement; 10327 if (EltTy->isIntegerType()) 10328 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10329 else 10330 ZeroElement = 10331 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10332 10333 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10334 return Success(Elements, E); 10335 } 10336 10337 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10338 VisitIgnoredValue(E->getSubExpr()); 10339 return ZeroInitialization(E); 10340 } 10341 10342 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10343 BinaryOperatorKind Op = E->getOpcode(); 10344 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10345 "Operation not supported on vector types"); 10346 10347 if (Op == BO_Comma) 10348 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10349 10350 Expr *LHS = E->getLHS(); 10351 Expr *RHS = E->getRHS(); 10352 10353 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10354 "Must both be vector types"); 10355 // Checking JUST the types are the same would be fine, except shifts don't 10356 // need to have their types be the same (since you always shift by an int). 10357 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10358 E->getType()->castAs<VectorType>()->getNumElements() && 10359 RHS->getType()->castAs<VectorType>()->getNumElements() == 10360 E->getType()->castAs<VectorType>()->getNumElements() && 10361 "All operands must be the same size."); 10362 10363 APValue LHSValue; 10364 APValue RHSValue; 10365 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10366 if (!LHSOK && !Info.noteFailure()) 10367 return false; 10368 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10369 return false; 10370 10371 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10372 return false; 10373 10374 return Success(LHSValue, E); 10375 } 10376 10377 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10378 QualType ResultTy, 10379 UnaryOperatorKind Op, 10380 APValue Elt) { 10381 switch (Op) { 10382 case UO_Plus: 10383 // Nothing to do here. 10384 return Elt; 10385 case UO_Minus: 10386 if (Elt.getKind() == APValue::Int) { 10387 Elt.getInt().negate(); 10388 } else { 10389 assert(Elt.getKind() == APValue::Float && 10390 "Vector can only be int or float type"); 10391 Elt.getFloat().changeSign(); 10392 } 10393 return Elt; 10394 case UO_Not: 10395 // This is only valid for integral types anyway, so we don't have to handle 10396 // float here. 10397 assert(Elt.getKind() == APValue::Int && 10398 "Vector operator ~ can only be int"); 10399 Elt.getInt().flipAllBits(); 10400 return Elt; 10401 case UO_LNot: { 10402 if (Elt.getKind() == APValue::Int) { 10403 Elt.getInt() = !Elt.getInt(); 10404 // operator ! on vectors returns -1 for 'truth', so negate it. 10405 Elt.getInt().negate(); 10406 return Elt; 10407 } 10408 assert(Elt.getKind() == APValue::Float && 10409 "Vector can only be int or float type"); 10410 // Float types result in an int of the same size, but -1 for true, or 0 for 10411 // false. 10412 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10413 ResultTy->isUnsignedIntegerType()}; 10414 if (Elt.getFloat().isZero()) 10415 EltResult.setAllBits(); 10416 else 10417 EltResult.clearAllBits(); 10418 10419 return APValue{EltResult}; 10420 } 10421 default: 10422 // FIXME: Implement the rest of the unary operators. 10423 return llvm::None; 10424 } 10425 } 10426 10427 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10428 Expr *SubExpr = E->getSubExpr(); 10429 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10430 // This result element type differs in the case of negating a floating point 10431 // vector, since the result type is the a vector of the equivilant sized 10432 // integer. 10433 const QualType ResultEltTy = VD->getElementType(); 10434 UnaryOperatorKind Op = E->getOpcode(); 10435 10436 APValue SubExprValue; 10437 if (!Evaluate(SubExprValue, Info, SubExpr)) 10438 return false; 10439 10440 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10441 "Vector length doesn't match type?"); 10442 10443 SmallVector<APValue, 4> ResultElements; 10444 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10445 llvm::Optional<APValue> Elt = handleVectorUnaryOperator( 10446 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10447 if (!Elt) 10448 return false; 10449 ResultElements.push_back(*Elt); 10450 } 10451 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10452 } 10453 10454 //===----------------------------------------------------------------------===// 10455 // Array Evaluation 10456 //===----------------------------------------------------------------------===// 10457 10458 namespace { 10459 class ArrayExprEvaluator 10460 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10461 const LValue &This; 10462 APValue &Result; 10463 public: 10464 10465 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10466 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10467 10468 bool Success(const APValue &V, const Expr *E) { 10469 assert(V.isArray() && "expected array"); 10470 Result = V; 10471 return true; 10472 } 10473 10474 bool ZeroInitialization(const Expr *E) { 10475 const ConstantArrayType *CAT = 10476 Info.Ctx.getAsConstantArrayType(E->getType()); 10477 if (!CAT) { 10478 if (E->getType()->isIncompleteArrayType()) { 10479 // We can be asked to zero-initialize a flexible array member; this 10480 // is represented as an ImplicitValueInitExpr of incomplete array 10481 // type. In this case, the array has zero elements. 10482 Result = APValue(APValue::UninitArray(), 0, 0); 10483 return true; 10484 } 10485 // FIXME: We could handle VLAs here. 10486 return Error(E); 10487 } 10488 10489 Result = APValue(APValue::UninitArray(), 0, 10490 CAT->getSize().getZExtValue()); 10491 if (!Result.hasArrayFiller()) 10492 return true; 10493 10494 // Zero-initialize all elements. 10495 LValue Subobject = This; 10496 Subobject.addArray(Info, E, CAT); 10497 ImplicitValueInitExpr VIE(CAT->getElementType()); 10498 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10499 } 10500 10501 bool VisitCallExpr(const CallExpr *E) { 10502 return handleCallExpr(E, Result, &This); 10503 } 10504 bool VisitInitListExpr(const InitListExpr *E, 10505 QualType AllocType = QualType()); 10506 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10507 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10508 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10509 const LValue &Subobject, 10510 APValue *Value, QualType Type); 10511 bool VisitStringLiteral(const StringLiteral *E, 10512 QualType AllocType = QualType()) { 10513 expandStringLiteral(Info, E, Result, AllocType); 10514 return true; 10515 } 10516 }; 10517 } // end anonymous namespace 10518 10519 static bool EvaluateArray(const Expr *E, const LValue &This, 10520 APValue &Result, EvalInfo &Info) { 10521 assert(!E->isValueDependent()); 10522 assert(E->isPRValue() && E->getType()->isArrayType() && 10523 "not an array prvalue"); 10524 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10525 } 10526 10527 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10528 APValue &Result, const InitListExpr *ILE, 10529 QualType AllocType) { 10530 assert(!ILE->isValueDependent()); 10531 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10532 "not an array prvalue"); 10533 return ArrayExprEvaluator(Info, This, Result) 10534 .VisitInitListExpr(ILE, AllocType); 10535 } 10536 10537 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10538 APValue &Result, 10539 const CXXConstructExpr *CCE, 10540 QualType AllocType) { 10541 assert(!CCE->isValueDependent()); 10542 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10543 "not an array prvalue"); 10544 return ArrayExprEvaluator(Info, This, Result) 10545 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10546 } 10547 10548 // Return true iff the given array filler may depend on the element index. 10549 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10550 // For now, just allow non-class value-initialization and initialization 10551 // lists comprised of them. 10552 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10553 return false; 10554 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10555 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10556 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10557 return true; 10558 } 10559 return false; 10560 } 10561 return true; 10562 } 10563 10564 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10565 QualType AllocType) { 10566 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10567 AllocType.isNull() ? E->getType() : AllocType); 10568 if (!CAT) 10569 return Error(E); 10570 10571 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10572 // an appropriately-typed string literal enclosed in braces. 10573 if (E->isStringLiteralInit()) { 10574 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10575 // FIXME: Support ObjCEncodeExpr here once we support it in 10576 // ArrayExprEvaluator generally. 10577 if (!SL) 10578 return Error(E); 10579 return VisitStringLiteral(SL, AllocType); 10580 } 10581 // Any other transparent list init will need proper handling of the 10582 // AllocType; we can't just recurse to the inner initializer. 10583 assert(!E->isTransparent() && 10584 "transparent array list initialization is not string literal init?"); 10585 10586 bool Success = true; 10587 10588 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10589 "zero-initialized array shouldn't have any initialized elts"); 10590 APValue Filler; 10591 if (Result.isArray() && Result.hasArrayFiller()) 10592 Filler = Result.getArrayFiller(); 10593 10594 unsigned NumEltsToInit = E->getNumInits(); 10595 unsigned NumElts = CAT->getSize().getZExtValue(); 10596 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10597 10598 // If the initializer might depend on the array index, run it for each 10599 // array element. 10600 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10601 NumEltsToInit = NumElts; 10602 10603 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10604 << NumEltsToInit << ".\n"); 10605 10606 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10607 10608 // If the array was previously zero-initialized, preserve the 10609 // zero-initialized values. 10610 if (Filler.hasValue()) { 10611 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10612 Result.getArrayInitializedElt(I) = Filler; 10613 if (Result.hasArrayFiller()) 10614 Result.getArrayFiller() = Filler; 10615 } 10616 10617 LValue Subobject = This; 10618 Subobject.addArray(Info, E, CAT); 10619 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10620 const Expr *Init = 10621 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10622 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10623 Info, Subobject, Init) || 10624 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10625 CAT->getElementType(), 1)) { 10626 if (!Info.noteFailure()) 10627 return false; 10628 Success = false; 10629 } 10630 } 10631 10632 if (!Result.hasArrayFiller()) 10633 return Success; 10634 10635 // If we get here, we have a trivial filler, which we can just evaluate 10636 // once and splat over the rest of the array elements. 10637 assert(FillerExpr && "no array filler for incomplete init list"); 10638 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10639 FillerExpr) && Success; 10640 } 10641 10642 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10643 LValue CommonLV; 10644 if (E->getCommonExpr() && 10645 !Evaluate(Info.CurrentCall->createTemporary( 10646 E->getCommonExpr(), 10647 getStorageType(Info.Ctx, E->getCommonExpr()), 10648 ScopeKind::FullExpression, CommonLV), 10649 Info, E->getCommonExpr()->getSourceExpr())) 10650 return false; 10651 10652 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10653 10654 uint64_t Elements = CAT->getSize().getZExtValue(); 10655 Result = APValue(APValue::UninitArray(), Elements, Elements); 10656 10657 LValue Subobject = This; 10658 Subobject.addArray(Info, E, CAT); 10659 10660 bool Success = true; 10661 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10662 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10663 Info, Subobject, E->getSubExpr()) || 10664 !HandleLValueArrayAdjustment(Info, E, Subobject, 10665 CAT->getElementType(), 1)) { 10666 if (!Info.noteFailure()) 10667 return false; 10668 Success = false; 10669 } 10670 } 10671 10672 return Success; 10673 } 10674 10675 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10676 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10677 } 10678 10679 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10680 const LValue &Subobject, 10681 APValue *Value, 10682 QualType Type) { 10683 bool HadZeroInit = Value->hasValue(); 10684 10685 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10686 unsigned N = CAT->getSize().getZExtValue(); 10687 10688 // Preserve the array filler if we had prior zero-initialization. 10689 APValue Filler = 10690 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10691 : APValue(); 10692 10693 *Value = APValue(APValue::UninitArray(), N, N); 10694 10695 if (HadZeroInit) 10696 for (unsigned I = 0; I != N; ++I) 10697 Value->getArrayInitializedElt(I) = Filler; 10698 10699 // Initialize the elements. 10700 LValue ArrayElt = Subobject; 10701 ArrayElt.addArray(Info, E, CAT); 10702 for (unsigned I = 0; I != N; ++I) 10703 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10704 CAT->getElementType()) || 10705 !HandleLValueArrayAdjustment(Info, E, ArrayElt, CAT->getElementType(), 10706 1)) 10707 return false; 10708 10709 return true; 10710 } 10711 10712 if (!Type->isRecordType()) 10713 return Error(E); 10714 10715 return RecordExprEvaluator(Info, Subobject, *Value) 10716 .VisitCXXConstructExpr(E, Type); 10717 } 10718 10719 //===----------------------------------------------------------------------===// 10720 // Integer Evaluation 10721 // 10722 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10723 // types and back in constant folding. Integer values are thus represented 10724 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10725 //===----------------------------------------------------------------------===// 10726 10727 namespace { 10728 class IntExprEvaluator 10729 : public ExprEvaluatorBase<IntExprEvaluator> { 10730 APValue &Result; 10731 public: 10732 IntExprEvaluator(EvalInfo &info, APValue &result) 10733 : ExprEvaluatorBaseTy(info), Result(result) {} 10734 10735 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10736 assert(E->getType()->isIntegralOrEnumerationType() && 10737 "Invalid evaluation result."); 10738 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10739 "Invalid evaluation result."); 10740 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10741 "Invalid evaluation result."); 10742 Result = APValue(SI); 10743 return true; 10744 } 10745 bool Success(const llvm::APSInt &SI, const Expr *E) { 10746 return Success(SI, E, Result); 10747 } 10748 10749 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10750 assert(E->getType()->isIntegralOrEnumerationType() && 10751 "Invalid evaluation result."); 10752 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10753 "Invalid evaluation result."); 10754 Result = APValue(APSInt(I)); 10755 Result.getInt().setIsUnsigned( 10756 E->getType()->isUnsignedIntegerOrEnumerationType()); 10757 return true; 10758 } 10759 bool Success(const llvm::APInt &I, const Expr *E) { 10760 return Success(I, E, Result); 10761 } 10762 10763 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10764 assert(E->getType()->isIntegralOrEnumerationType() && 10765 "Invalid evaluation result."); 10766 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10767 return true; 10768 } 10769 bool Success(uint64_t Value, const Expr *E) { 10770 return Success(Value, E, Result); 10771 } 10772 10773 bool Success(CharUnits Size, const Expr *E) { 10774 return Success(Size.getQuantity(), E); 10775 } 10776 10777 bool Success(const APValue &V, const Expr *E) { 10778 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10779 Result = V; 10780 return true; 10781 } 10782 return Success(V.getInt(), E); 10783 } 10784 10785 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10786 10787 //===--------------------------------------------------------------------===// 10788 // Visitor Methods 10789 //===--------------------------------------------------------------------===// 10790 10791 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10792 return Success(E->getValue(), E); 10793 } 10794 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10795 return Success(E->getValue(), E); 10796 } 10797 10798 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10799 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10800 if (CheckReferencedDecl(E, E->getDecl())) 10801 return true; 10802 10803 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10804 } 10805 bool VisitMemberExpr(const MemberExpr *E) { 10806 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10807 VisitIgnoredBaseExpression(E->getBase()); 10808 return true; 10809 } 10810 10811 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10812 } 10813 10814 bool VisitCallExpr(const CallExpr *E); 10815 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10816 bool VisitBinaryOperator(const BinaryOperator *E); 10817 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10818 bool VisitUnaryOperator(const UnaryOperator *E); 10819 10820 bool VisitCastExpr(const CastExpr* E); 10821 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10822 10823 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10824 return Success(E->getValue(), E); 10825 } 10826 10827 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10828 return Success(E->getValue(), E); 10829 } 10830 10831 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10832 if (Info.ArrayInitIndex == uint64_t(-1)) { 10833 // We were asked to evaluate this subexpression independent of the 10834 // enclosing ArrayInitLoopExpr. We can't do that. 10835 Info.FFDiag(E); 10836 return false; 10837 } 10838 return Success(Info.ArrayInitIndex, E); 10839 } 10840 10841 // Note, GNU defines __null as an integer, not a pointer. 10842 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10843 return ZeroInitialization(E); 10844 } 10845 10846 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10847 return Success(E->getValue(), E); 10848 } 10849 10850 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10851 return Success(E->getValue(), E); 10852 } 10853 10854 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10855 return Success(E->getValue(), E); 10856 } 10857 10858 bool VisitUnaryReal(const UnaryOperator *E); 10859 bool VisitUnaryImag(const UnaryOperator *E); 10860 10861 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10862 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10863 bool VisitSourceLocExpr(const SourceLocExpr *E); 10864 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10865 bool VisitRequiresExpr(const RequiresExpr *E); 10866 // FIXME: Missing: array subscript of vector, member of vector 10867 }; 10868 10869 class FixedPointExprEvaluator 10870 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10871 APValue &Result; 10872 10873 public: 10874 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10875 : ExprEvaluatorBaseTy(info), Result(result) {} 10876 10877 bool Success(const llvm::APInt &I, const Expr *E) { 10878 return Success( 10879 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10880 } 10881 10882 bool Success(uint64_t Value, const Expr *E) { 10883 return Success( 10884 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10885 } 10886 10887 bool Success(const APValue &V, const Expr *E) { 10888 return Success(V.getFixedPoint(), E); 10889 } 10890 10891 bool Success(const APFixedPoint &V, const Expr *E) { 10892 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10893 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10894 "Invalid evaluation result."); 10895 Result = APValue(V); 10896 return true; 10897 } 10898 10899 //===--------------------------------------------------------------------===// 10900 // Visitor Methods 10901 //===--------------------------------------------------------------------===// 10902 10903 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10904 return Success(E->getValue(), E); 10905 } 10906 10907 bool VisitCastExpr(const CastExpr *E); 10908 bool VisitUnaryOperator(const UnaryOperator *E); 10909 bool VisitBinaryOperator(const BinaryOperator *E); 10910 }; 10911 } // end anonymous namespace 10912 10913 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10914 /// produce either the integer value or a pointer. 10915 /// 10916 /// GCC has a heinous extension which folds casts between pointer types and 10917 /// pointer-sized integral types. We support this by allowing the evaluation of 10918 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10919 /// Some simple arithmetic on such values is supported (they are treated much 10920 /// like char*). 10921 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10922 EvalInfo &Info) { 10923 assert(!E->isValueDependent()); 10924 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 10925 return IntExprEvaluator(Info, Result).Visit(E); 10926 } 10927 10928 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10929 assert(!E->isValueDependent()); 10930 APValue Val; 10931 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10932 return false; 10933 if (!Val.isInt()) { 10934 // FIXME: It would be better to produce the diagnostic for casting 10935 // a pointer to an integer. 10936 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10937 return false; 10938 } 10939 Result = Val.getInt(); 10940 return true; 10941 } 10942 10943 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10944 APValue Evaluated = E->EvaluateInContext( 10945 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10946 return Success(Evaluated, E); 10947 } 10948 10949 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10950 EvalInfo &Info) { 10951 assert(!E->isValueDependent()); 10952 if (E->getType()->isFixedPointType()) { 10953 APValue Val; 10954 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10955 return false; 10956 if (!Val.isFixedPoint()) 10957 return false; 10958 10959 Result = Val.getFixedPoint(); 10960 return true; 10961 } 10962 return false; 10963 } 10964 10965 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10966 EvalInfo &Info) { 10967 assert(!E->isValueDependent()); 10968 if (E->getType()->isIntegerType()) { 10969 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10970 APSInt Val; 10971 if (!EvaluateInteger(E, Val, Info)) 10972 return false; 10973 Result = APFixedPoint(Val, FXSema); 10974 return true; 10975 } else if (E->getType()->isFixedPointType()) { 10976 return EvaluateFixedPoint(E, Result, Info); 10977 } 10978 return false; 10979 } 10980 10981 /// Check whether the given declaration can be directly converted to an integral 10982 /// rvalue. If not, no diagnostic is produced; there are other things we can 10983 /// try. 10984 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10985 // Enums are integer constant exprs. 10986 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10987 // Check for signedness/width mismatches between E type and ECD value. 10988 bool SameSign = (ECD->getInitVal().isSigned() 10989 == E->getType()->isSignedIntegerOrEnumerationType()); 10990 bool SameWidth = (ECD->getInitVal().getBitWidth() 10991 == Info.Ctx.getIntWidth(E->getType())); 10992 if (SameSign && SameWidth) 10993 return Success(ECD->getInitVal(), E); 10994 else { 10995 // Get rid of mismatch (otherwise Success assertions will fail) 10996 // by computing a new value matching the type of E. 10997 llvm::APSInt Val = ECD->getInitVal(); 10998 if (!SameSign) 10999 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11000 if (!SameWidth) 11001 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11002 return Success(Val, E); 11003 } 11004 } 11005 return false; 11006 } 11007 11008 /// Values returned by __builtin_classify_type, chosen to match the values 11009 /// produced by GCC's builtin. 11010 enum class GCCTypeClass { 11011 None = -1, 11012 Void = 0, 11013 Integer = 1, 11014 // GCC reserves 2 for character types, but instead classifies them as 11015 // integers. 11016 Enum = 3, 11017 Bool = 4, 11018 Pointer = 5, 11019 // GCC reserves 6 for references, but appears to never use it (because 11020 // expressions never have reference type, presumably). 11021 PointerToDataMember = 7, 11022 RealFloat = 8, 11023 Complex = 9, 11024 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11025 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11026 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11027 // uses 12 for that purpose, same as for a class or struct. Maybe it 11028 // internally implements a pointer to member as a struct? Who knows. 11029 PointerToMemberFunction = 12, // Not a bug, see above. 11030 ClassOrStruct = 12, 11031 Union = 13, 11032 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11033 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11034 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11035 // literals. 11036 }; 11037 11038 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11039 /// as GCC. 11040 static GCCTypeClass 11041 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11042 assert(!T->isDependentType() && "unexpected dependent type"); 11043 11044 QualType CanTy = T.getCanonicalType(); 11045 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 11046 11047 switch (CanTy->getTypeClass()) { 11048 #define TYPE(ID, BASE) 11049 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11050 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11051 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11052 #include "clang/AST/TypeNodes.inc" 11053 case Type::Auto: 11054 case Type::DeducedTemplateSpecialization: 11055 llvm_unreachable("unexpected non-canonical or dependent type"); 11056 11057 case Type::Builtin: 11058 switch (BT->getKind()) { 11059 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11060 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11061 case BuiltinType::ID: return GCCTypeClass::Integer; 11062 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11063 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11064 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11065 case BuiltinType::ID: break; 11066 #include "clang/AST/BuiltinTypes.def" 11067 case BuiltinType::Void: 11068 return GCCTypeClass::Void; 11069 11070 case BuiltinType::Bool: 11071 return GCCTypeClass::Bool; 11072 11073 case BuiltinType::Char_U: 11074 case BuiltinType::UChar: 11075 case BuiltinType::WChar_U: 11076 case BuiltinType::Char8: 11077 case BuiltinType::Char16: 11078 case BuiltinType::Char32: 11079 case BuiltinType::UShort: 11080 case BuiltinType::UInt: 11081 case BuiltinType::ULong: 11082 case BuiltinType::ULongLong: 11083 case BuiltinType::UInt128: 11084 return GCCTypeClass::Integer; 11085 11086 case BuiltinType::UShortAccum: 11087 case BuiltinType::UAccum: 11088 case BuiltinType::ULongAccum: 11089 case BuiltinType::UShortFract: 11090 case BuiltinType::UFract: 11091 case BuiltinType::ULongFract: 11092 case BuiltinType::SatUShortAccum: 11093 case BuiltinType::SatUAccum: 11094 case BuiltinType::SatULongAccum: 11095 case BuiltinType::SatUShortFract: 11096 case BuiltinType::SatUFract: 11097 case BuiltinType::SatULongFract: 11098 return GCCTypeClass::None; 11099 11100 case BuiltinType::NullPtr: 11101 11102 case BuiltinType::ObjCId: 11103 case BuiltinType::ObjCClass: 11104 case BuiltinType::ObjCSel: 11105 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11106 case BuiltinType::Id: 11107 #include "clang/Basic/OpenCLImageTypes.def" 11108 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11109 case BuiltinType::Id: 11110 #include "clang/Basic/OpenCLExtensionTypes.def" 11111 case BuiltinType::OCLSampler: 11112 case BuiltinType::OCLEvent: 11113 case BuiltinType::OCLClkEvent: 11114 case BuiltinType::OCLQueue: 11115 case BuiltinType::OCLReserveID: 11116 #define SVE_TYPE(Name, Id, SingletonId) \ 11117 case BuiltinType::Id: 11118 #include "clang/Basic/AArch64SVEACLETypes.def" 11119 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11120 case BuiltinType::Id: 11121 #include "clang/Basic/PPCTypes.def" 11122 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11123 #include "clang/Basic/RISCVVTypes.def" 11124 return GCCTypeClass::None; 11125 11126 case BuiltinType::Dependent: 11127 llvm_unreachable("unexpected dependent type"); 11128 }; 11129 llvm_unreachable("unexpected placeholder type"); 11130 11131 case Type::Enum: 11132 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11133 11134 case Type::Pointer: 11135 case Type::ConstantArray: 11136 case Type::VariableArray: 11137 case Type::IncompleteArray: 11138 case Type::FunctionNoProto: 11139 case Type::FunctionProto: 11140 return GCCTypeClass::Pointer; 11141 11142 case Type::MemberPointer: 11143 return CanTy->isMemberDataPointerType() 11144 ? GCCTypeClass::PointerToDataMember 11145 : GCCTypeClass::PointerToMemberFunction; 11146 11147 case Type::Complex: 11148 return GCCTypeClass::Complex; 11149 11150 case Type::Record: 11151 return CanTy->isUnionType() ? GCCTypeClass::Union 11152 : GCCTypeClass::ClassOrStruct; 11153 11154 case Type::Atomic: 11155 // GCC classifies _Atomic T the same as T. 11156 return EvaluateBuiltinClassifyType( 11157 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11158 11159 case Type::BlockPointer: 11160 case Type::Vector: 11161 case Type::ExtVector: 11162 case Type::ConstantMatrix: 11163 case Type::ObjCObject: 11164 case Type::ObjCInterface: 11165 case Type::ObjCObjectPointer: 11166 case Type::Pipe: 11167 case Type::BitInt: 11168 // GCC classifies vectors as None. We follow its lead and classify all 11169 // other types that don't fit into the regular classification the same way. 11170 return GCCTypeClass::None; 11171 11172 case Type::LValueReference: 11173 case Type::RValueReference: 11174 llvm_unreachable("invalid type for expression"); 11175 } 11176 11177 llvm_unreachable("unexpected type class"); 11178 } 11179 11180 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11181 /// as GCC. 11182 static GCCTypeClass 11183 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11184 // If no argument was supplied, default to None. This isn't 11185 // ideal, however it is what gcc does. 11186 if (E->getNumArgs() == 0) 11187 return GCCTypeClass::None; 11188 11189 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11190 // being an ICE, but still folds it to a constant using the type of the first 11191 // argument. 11192 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11193 } 11194 11195 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11196 /// __builtin_constant_p when applied to the given pointer. 11197 /// 11198 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11199 /// or it points to the first character of a string literal. 11200 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11201 APValue::LValueBase Base = LV.getLValueBase(); 11202 if (Base.isNull()) { 11203 // A null base is acceptable. 11204 return true; 11205 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11206 if (!isa<StringLiteral>(E)) 11207 return false; 11208 return LV.getLValueOffset().isZero(); 11209 } else if (Base.is<TypeInfoLValue>()) { 11210 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11211 // evaluate to true. 11212 return true; 11213 } else { 11214 // Any other base is not constant enough for GCC. 11215 return false; 11216 } 11217 } 11218 11219 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11220 /// GCC as we can manage. 11221 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11222 // This evaluation is not permitted to have side-effects, so evaluate it in 11223 // a speculative evaluation context. 11224 SpeculativeEvaluationRAII SpeculativeEval(Info); 11225 11226 // Constant-folding is always enabled for the operand of __builtin_constant_p 11227 // (even when the enclosing evaluation context otherwise requires a strict 11228 // language-specific constant expression). 11229 FoldConstant Fold(Info, true); 11230 11231 QualType ArgType = Arg->getType(); 11232 11233 // __builtin_constant_p always has one operand. The rules which gcc follows 11234 // are not precisely documented, but are as follows: 11235 // 11236 // - If the operand is of integral, floating, complex or enumeration type, 11237 // and can be folded to a known value of that type, it returns 1. 11238 // - If the operand can be folded to a pointer to the first character 11239 // of a string literal (or such a pointer cast to an integral type) 11240 // or to a null pointer or an integer cast to a pointer, it returns 1. 11241 // 11242 // Otherwise, it returns 0. 11243 // 11244 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11245 // its support for this did not work prior to GCC 9 and is not yet well 11246 // understood. 11247 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11248 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11249 ArgType->isNullPtrType()) { 11250 APValue V; 11251 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11252 Fold.keepDiagnostics(); 11253 return false; 11254 } 11255 11256 // For a pointer (possibly cast to integer), there are special rules. 11257 if (V.getKind() == APValue::LValue) 11258 return EvaluateBuiltinConstantPForLValue(V); 11259 11260 // Otherwise, any constant value is good enough. 11261 return V.hasValue(); 11262 } 11263 11264 // Anything else isn't considered to be sufficiently constant. 11265 return false; 11266 } 11267 11268 /// Retrieves the "underlying object type" of the given expression, 11269 /// as used by __builtin_object_size. 11270 static QualType getObjectType(APValue::LValueBase B) { 11271 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11272 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11273 return VD->getType(); 11274 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11275 if (isa<CompoundLiteralExpr>(E)) 11276 return E->getType(); 11277 } else if (B.is<TypeInfoLValue>()) { 11278 return B.getTypeInfoType(); 11279 } else if (B.is<DynamicAllocLValue>()) { 11280 return B.getDynamicAllocType(); 11281 } 11282 11283 return QualType(); 11284 } 11285 11286 /// A more selective version of E->IgnoreParenCasts for 11287 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11288 /// to change the type of E. 11289 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11290 /// 11291 /// Always returns an RValue with a pointer representation. 11292 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11293 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11294 11295 auto *NoParens = E->IgnoreParens(); 11296 auto *Cast = dyn_cast<CastExpr>(NoParens); 11297 if (Cast == nullptr) 11298 return NoParens; 11299 11300 // We only conservatively allow a few kinds of casts, because this code is 11301 // inherently a simple solution that seeks to support the common case. 11302 auto CastKind = Cast->getCastKind(); 11303 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11304 CastKind != CK_AddressSpaceConversion) 11305 return NoParens; 11306 11307 auto *SubExpr = Cast->getSubExpr(); 11308 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11309 return NoParens; 11310 return ignorePointerCastsAndParens(SubExpr); 11311 } 11312 11313 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11314 /// record layout. e.g. 11315 /// struct { struct { int a, b; } fst, snd; } obj; 11316 /// obj.fst // no 11317 /// obj.snd // yes 11318 /// obj.fst.a // no 11319 /// obj.fst.b // no 11320 /// obj.snd.a // no 11321 /// obj.snd.b // yes 11322 /// 11323 /// Please note: this function is specialized for how __builtin_object_size 11324 /// views "objects". 11325 /// 11326 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11327 /// correct result, it will always return true. 11328 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11329 assert(!LVal.Designator.Invalid); 11330 11331 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11332 const RecordDecl *Parent = FD->getParent(); 11333 Invalid = Parent->isInvalidDecl(); 11334 if (Invalid || Parent->isUnion()) 11335 return true; 11336 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11337 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11338 }; 11339 11340 auto &Base = LVal.getLValueBase(); 11341 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11342 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11343 bool Invalid; 11344 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11345 return Invalid; 11346 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11347 for (auto *FD : IFD->chain()) { 11348 bool Invalid; 11349 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11350 return Invalid; 11351 } 11352 } 11353 } 11354 11355 unsigned I = 0; 11356 QualType BaseType = getType(Base); 11357 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11358 // If we don't know the array bound, conservatively assume we're looking at 11359 // the final array element. 11360 ++I; 11361 if (BaseType->isIncompleteArrayType()) 11362 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11363 else 11364 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11365 } 11366 11367 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11368 const auto &Entry = LVal.Designator.Entries[I]; 11369 if (BaseType->isArrayType()) { 11370 // Because __builtin_object_size treats arrays as objects, we can ignore 11371 // the index iff this is the last array in the Designator. 11372 if (I + 1 == E) 11373 return true; 11374 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11375 uint64_t Index = Entry.getAsArrayIndex(); 11376 if (Index + 1 != CAT->getSize()) 11377 return false; 11378 BaseType = CAT->getElementType(); 11379 } else if (BaseType->isAnyComplexType()) { 11380 const auto *CT = BaseType->castAs<ComplexType>(); 11381 uint64_t Index = Entry.getAsArrayIndex(); 11382 if (Index != 1) 11383 return false; 11384 BaseType = CT->getElementType(); 11385 } else if (auto *FD = getAsField(Entry)) { 11386 bool Invalid; 11387 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11388 return Invalid; 11389 BaseType = FD->getType(); 11390 } else { 11391 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11392 return false; 11393 } 11394 } 11395 return true; 11396 } 11397 11398 /// Tests to see if the LValue has a user-specified designator (that isn't 11399 /// necessarily valid). Note that this always returns 'true' if the LValue has 11400 /// an unsized array as its first designator entry, because there's currently no 11401 /// way to tell if the user typed *foo or foo[0]. 11402 static bool refersToCompleteObject(const LValue &LVal) { 11403 if (LVal.Designator.Invalid) 11404 return false; 11405 11406 if (!LVal.Designator.Entries.empty()) 11407 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11408 11409 if (!LVal.InvalidBase) 11410 return true; 11411 11412 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11413 // the LValueBase. 11414 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11415 return !E || !isa<MemberExpr>(E); 11416 } 11417 11418 /// Attempts to detect a user writing into a piece of memory that's impossible 11419 /// to figure out the size of by just using types. 11420 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11421 const SubobjectDesignator &Designator = LVal.Designator; 11422 // Notes: 11423 // - Users can only write off of the end when we have an invalid base. Invalid 11424 // bases imply we don't know where the memory came from. 11425 // - We used to be a bit more aggressive here; we'd only be conservative if 11426 // the array at the end was flexible, or if it had 0 or 1 elements. This 11427 // broke some common standard library extensions (PR30346), but was 11428 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11429 // with some sort of list. OTOH, it seems that GCC is always 11430 // conservative with the last element in structs (if it's an array), so our 11431 // current behavior is more compatible than an explicit list approach would 11432 // be. 11433 return LVal.InvalidBase && 11434 Designator.Entries.size() == Designator.MostDerivedPathLength && 11435 Designator.MostDerivedIsArrayElement && 11436 isDesignatorAtObjectEnd(Ctx, LVal); 11437 } 11438 11439 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11440 /// Fails if the conversion would cause loss of precision. 11441 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11442 CharUnits &Result) { 11443 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11444 if (Int.ugt(CharUnitsMax)) 11445 return false; 11446 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11447 return true; 11448 } 11449 11450 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11451 /// determine how many bytes exist from the beginning of the object to either 11452 /// the end of the current subobject, or the end of the object itself, depending 11453 /// on what the LValue looks like + the value of Type. 11454 /// 11455 /// If this returns false, the value of Result is undefined. 11456 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11457 unsigned Type, const LValue &LVal, 11458 CharUnits &EndOffset) { 11459 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11460 11461 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11462 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11463 return false; 11464 return HandleSizeof(Info, ExprLoc, Ty, Result); 11465 }; 11466 11467 // We want to evaluate the size of the entire object. This is a valid fallback 11468 // for when Type=1 and the designator is invalid, because we're asked for an 11469 // upper-bound. 11470 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11471 // Type=3 wants a lower bound, so we can't fall back to this. 11472 if (Type == 3 && !DetermineForCompleteObject) 11473 return false; 11474 11475 llvm::APInt APEndOffset; 11476 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11477 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11478 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11479 11480 if (LVal.InvalidBase) 11481 return false; 11482 11483 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11484 return CheckedHandleSizeof(BaseTy, EndOffset); 11485 } 11486 11487 // We want to evaluate the size of a subobject. 11488 const SubobjectDesignator &Designator = LVal.Designator; 11489 11490 // The following is a moderately common idiom in C: 11491 // 11492 // struct Foo { int a; char c[1]; }; 11493 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11494 // strcpy(&F->c[0], Bar); 11495 // 11496 // In order to not break too much legacy code, we need to support it. 11497 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11498 // If we can resolve this to an alloc_size call, we can hand that back, 11499 // because we know for certain how many bytes there are to write to. 11500 llvm::APInt APEndOffset; 11501 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11502 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11503 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11504 11505 // If we cannot determine the size of the initial allocation, then we can't 11506 // given an accurate upper-bound. However, we are still able to give 11507 // conservative lower-bounds for Type=3. 11508 if (Type == 1) 11509 return false; 11510 } 11511 11512 CharUnits BytesPerElem; 11513 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11514 return false; 11515 11516 // According to the GCC documentation, we want the size of the subobject 11517 // denoted by the pointer. But that's not quite right -- what we actually 11518 // want is the size of the immediately-enclosing array, if there is one. 11519 int64_t ElemsRemaining; 11520 if (Designator.MostDerivedIsArrayElement && 11521 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11522 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11523 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11524 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11525 } else { 11526 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11527 } 11528 11529 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11530 return true; 11531 } 11532 11533 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11534 /// returns true and stores the result in @p Size. 11535 /// 11536 /// If @p WasError is non-null, this will report whether the failure to evaluate 11537 /// is to be treated as an Error in IntExprEvaluator. 11538 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11539 EvalInfo &Info, uint64_t &Size) { 11540 // Determine the denoted object. 11541 LValue LVal; 11542 { 11543 // The operand of __builtin_object_size is never evaluated for side-effects. 11544 // If there are any, but we can determine the pointed-to object anyway, then 11545 // ignore the side-effects. 11546 SpeculativeEvaluationRAII SpeculativeEval(Info); 11547 IgnoreSideEffectsRAII Fold(Info); 11548 11549 if (E->isGLValue()) { 11550 // It's possible for us to be given GLValues if we're called via 11551 // Expr::tryEvaluateObjectSize. 11552 APValue RVal; 11553 if (!EvaluateAsRValue(Info, E, RVal)) 11554 return false; 11555 LVal.setFrom(Info.Ctx, RVal); 11556 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11557 /*InvalidBaseOK=*/true)) 11558 return false; 11559 } 11560 11561 // If we point to before the start of the object, there are no accessible 11562 // bytes. 11563 if (LVal.getLValueOffset().isNegative()) { 11564 Size = 0; 11565 return true; 11566 } 11567 11568 CharUnits EndOffset; 11569 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11570 return false; 11571 11572 // If we've fallen outside of the end offset, just pretend there's nothing to 11573 // write to/read from. 11574 if (EndOffset <= LVal.getLValueOffset()) 11575 Size = 0; 11576 else 11577 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11578 return true; 11579 } 11580 11581 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11582 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11583 return VisitBuiltinCallExpr(E, BuiltinOp); 11584 11585 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11586 } 11587 11588 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11589 APValue &Val, APSInt &Alignment) { 11590 QualType SrcTy = E->getArg(0)->getType(); 11591 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11592 return false; 11593 // Even though we are evaluating integer expressions we could get a pointer 11594 // argument for the __builtin_is_aligned() case. 11595 if (SrcTy->isPointerType()) { 11596 LValue Ptr; 11597 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11598 return false; 11599 Ptr.moveInto(Val); 11600 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11601 Info.FFDiag(E->getArg(0)); 11602 return false; 11603 } else { 11604 APSInt SrcInt; 11605 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11606 return false; 11607 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11608 "Bit widths must be the same"); 11609 Val = APValue(SrcInt); 11610 } 11611 assert(Val.hasValue()); 11612 return true; 11613 } 11614 11615 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11616 unsigned BuiltinOp) { 11617 switch (BuiltinOp) { 11618 default: 11619 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11620 11621 case Builtin::BI__builtin_dynamic_object_size: 11622 case Builtin::BI__builtin_object_size: { 11623 // The type was checked when we built the expression. 11624 unsigned Type = 11625 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11626 assert(Type <= 3 && "unexpected type"); 11627 11628 uint64_t Size; 11629 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11630 return Success(Size, E); 11631 11632 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11633 return Success((Type & 2) ? 0 : -1, E); 11634 11635 // Expression had no side effects, but we couldn't statically determine the 11636 // size of the referenced object. 11637 switch (Info.EvalMode) { 11638 case EvalInfo::EM_ConstantExpression: 11639 case EvalInfo::EM_ConstantFold: 11640 case EvalInfo::EM_IgnoreSideEffects: 11641 // Leave it to IR generation. 11642 return Error(E); 11643 case EvalInfo::EM_ConstantExpressionUnevaluated: 11644 // Reduce it to a constant now. 11645 return Success((Type & 2) ? 0 : -1, E); 11646 } 11647 11648 llvm_unreachable("unexpected EvalMode"); 11649 } 11650 11651 case Builtin::BI__builtin_os_log_format_buffer_size: { 11652 analyze_os_log::OSLogBufferLayout Layout; 11653 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11654 return Success(Layout.size().getQuantity(), E); 11655 } 11656 11657 case Builtin::BI__builtin_is_aligned: { 11658 APValue Src; 11659 APSInt Alignment; 11660 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11661 return false; 11662 if (Src.isLValue()) { 11663 // If we evaluated a pointer, check the minimum known alignment. 11664 LValue Ptr; 11665 Ptr.setFrom(Info.Ctx, Src); 11666 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11667 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11668 // We can return true if the known alignment at the computed offset is 11669 // greater than the requested alignment. 11670 assert(PtrAlign.isPowerOfTwo()); 11671 assert(Alignment.isPowerOf2()); 11672 if (PtrAlign.getQuantity() >= Alignment) 11673 return Success(1, E); 11674 // If the alignment is not known to be sufficient, some cases could still 11675 // be aligned at run time. However, if the requested alignment is less or 11676 // equal to the base alignment and the offset is not aligned, we know that 11677 // the run-time value can never be aligned. 11678 if (BaseAlignment.getQuantity() >= Alignment && 11679 PtrAlign.getQuantity() < Alignment) 11680 return Success(0, E); 11681 // Otherwise we can't infer whether the value is sufficiently aligned. 11682 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11683 // in cases where we can't fully evaluate the pointer. 11684 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11685 << Alignment; 11686 return false; 11687 } 11688 assert(Src.isInt()); 11689 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11690 } 11691 case Builtin::BI__builtin_align_up: { 11692 APValue Src; 11693 APSInt Alignment; 11694 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11695 return false; 11696 if (!Src.isInt()) 11697 return Error(E); 11698 APSInt AlignedVal = 11699 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11700 Src.getInt().isUnsigned()); 11701 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11702 return Success(AlignedVal, E); 11703 } 11704 case Builtin::BI__builtin_align_down: { 11705 APValue Src; 11706 APSInt Alignment; 11707 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11708 return false; 11709 if (!Src.isInt()) 11710 return Error(E); 11711 APSInt AlignedVal = 11712 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11713 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11714 return Success(AlignedVal, E); 11715 } 11716 11717 case Builtin::BI__builtin_bitreverse8: 11718 case Builtin::BI__builtin_bitreverse16: 11719 case Builtin::BI__builtin_bitreverse32: 11720 case Builtin::BI__builtin_bitreverse64: { 11721 APSInt Val; 11722 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11723 return false; 11724 11725 return Success(Val.reverseBits(), E); 11726 } 11727 11728 case Builtin::BI__builtin_bswap16: 11729 case Builtin::BI__builtin_bswap32: 11730 case Builtin::BI__builtin_bswap64: { 11731 APSInt Val; 11732 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11733 return false; 11734 11735 return Success(Val.byteSwap(), E); 11736 } 11737 11738 case Builtin::BI__builtin_classify_type: 11739 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11740 11741 case Builtin::BI__builtin_clrsb: 11742 case Builtin::BI__builtin_clrsbl: 11743 case Builtin::BI__builtin_clrsbll: { 11744 APSInt Val; 11745 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11746 return false; 11747 11748 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11749 } 11750 11751 case Builtin::BI__builtin_clz: 11752 case Builtin::BI__builtin_clzl: 11753 case Builtin::BI__builtin_clzll: 11754 case Builtin::BI__builtin_clzs: { 11755 APSInt Val; 11756 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11757 return false; 11758 if (!Val) 11759 return Error(E); 11760 11761 return Success(Val.countLeadingZeros(), E); 11762 } 11763 11764 case Builtin::BI__builtin_constant_p: { 11765 const Expr *Arg = E->getArg(0); 11766 if (EvaluateBuiltinConstantP(Info, Arg)) 11767 return Success(true, E); 11768 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11769 // Outside a constant context, eagerly evaluate to false in the presence 11770 // of side-effects in order to avoid -Wunsequenced false-positives in 11771 // a branch on __builtin_constant_p(expr). 11772 return Success(false, E); 11773 } 11774 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11775 return false; 11776 } 11777 11778 case Builtin::BI__builtin_is_constant_evaluated: { 11779 const auto *Callee = Info.CurrentCall->getCallee(); 11780 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11781 (Info.CallStackDepth == 1 || 11782 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11783 Callee->getIdentifier() && 11784 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11785 // FIXME: Find a better way to avoid duplicated diagnostics. 11786 if (Info.EvalStatus.Diag) 11787 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11788 : Info.CurrentCall->CallLoc, 11789 diag::warn_is_constant_evaluated_always_true_constexpr) 11790 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11791 : "std::is_constant_evaluated"); 11792 } 11793 11794 return Success(Info.InConstantContext, E); 11795 } 11796 11797 case Builtin::BI__builtin_ctz: 11798 case Builtin::BI__builtin_ctzl: 11799 case Builtin::BI__builtin_ctzll: 11800 case Builtin::BI__builtin_ctzs: { 11801 APSInt Val; 11802 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11803 return false; 11804 if (!Val) 11805 return Error(E); 11806 11807 return Success(Val.countTrailingZeros(), E); 11808 } 11809 11810 case Builtin::BI__builtin_eh_return_data_regno: { 11811 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11812 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11813 return Success(Operand, E); 11814 } 11815 11816 case Builtin::BI__builtin_expect: 11817 case Builtin::BI__builtin_expect_with_probability: 11818 return Visit(E->getArg(0)); 11819 11820 case Builtin::BI__builtin_ffs: 11821 case Builtin::BI__builtin_ffsl: 11822 case Builtin::BI__builtin_ffsll: { 11823 APSInt Val; 11824 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11825 return false; 11826 11827 unsigned N = Val.countTrailingZeros(); 11828 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11829 } 11830 11831 case Builtin::BI__builtin_fpclassify: { 11832 APFloat Val(0.0); 11833 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11834 return false; 11835 unsigned Arg; 11836 switch (Val.getCategory()) { 11837 case APFloat::fcNaN: Arg = 0; break; 11838 case APFloat::fcInfinity: Arg = 1; break; 11839 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11840 case APFloat::fcZero: Arg = 4; break; 11841 } 11842 return Visit(E->getArg(Arg)); 11843 } 11844 11845 case Builtin::BI__builtin_isinf_sign: { 11846 APFloat Val(0.0); 11847 return EvaluateFloat(E->getArg(0), Val, Info) && 11848 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11849 } 11850 11851 case Builtin::BI__builtin_isinf: { 11852 APFloat Val(0.0); 11853 return EvaluateFloat(E->getArg(0), Val, Info) && 11854 Success(Val.isInfinity() ? 1 : 0, E); 11855 } 11856 11857 case Builtin::BI__builtin_isfinite: { 11858 APFloat Val(0.0); 11859 return EvaluateFloat(E->getArg(0), Val, Info) && 11860 Success(Val.isFinite() ? 1 : 0, E); 11861 } 11862 11863 case Builtin::BI__builtin_isnan: { 11864 APFloat Val(0.0); 11865 return EvaluateFloat(E->getArg(0), Val, Info) && 11866 Success(Val.isNaN() ? 1 : 0, E); 11867 } 11868 11869 case Builtin::BI__builtin_isnormal: { 11870 APFloat Val(0.0); 11871 return EvaluateFloat(E->getArg(0), Val, Info) && 11872 Success(Val.isNormal() ? 1 : 0, E); 11873 } 11874 11875 case Builtin::BI__builtin_parity: 11876 case Builtin::BI__builtin_parityl: 11877 case Builtin::BI__builtin_parityll: { 11878 APSInt Val; 11879 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11880 return false; 11881 11882 return Success(Val.countPopulation() % 2, E); 11883 } 11884 11885 case Builtin::BI__builtin_popcount: 11886 case Builtin::BI__builtin_popcountl: 11887 case Builtin::BI__builtin_popcountll: { 11888 APSInt Val; 11889 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11890 return false; 11891 11892 return Success(Val.countPopulation(), E); 11893 } 11894 11895 case Builtin::BI__builtin_rotateleft8: 11896 case Builtin::BI__builtin_rotateleft16: 11897 case Builtin::BI__builtin_rotateleft32: 11898 case Builtin::BI__builtin_rotateleft64: 11899 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11900 case Builtin::BI_rotl16: 11901 case Builtin::BI_rotl: 11902 case Builtin::BI_lrotl: 11903 case Builtin::BI_rotl64: { 11904 APSInt Val, Amt; 11905 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11906 !EvaluateInteger(E->getArg(1), Amt, Info)) 11907 return false; 11908 11909 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11910 } 11911 11912 case Builtin::BI__builtin_rotateright8: 11913 case Builtin::BI__builtin_rotateright16: 11914 case Builtin::BI__builtin_rotateright32: 11915 case Builtin::BI__builtin_rotateright64: 11916 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11917 case Builtin::BI_rotr16: 11918 case Builtin::BI_rotr: 11919 case Builtin::BI_lrotr: 11920 case Builtin::BI_rotr64: { 11921 APSInt Val, Amt; 11922 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11923 !EvaluateInteger(E->getArg(1), Amt, Info)) 11924 return false; 11925 11926 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11927 } 11928 11929 case Builtin::BIstrlen: 11930 case Builtin::BIwcslen: 11931 // A call to strlen is not a constant expression. 11932 if (Info.getLangOpts().CPlusPlus11) 11933 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11934 << /*isConstexpr*/0 << /*isConstructor*/0 11935 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11936 else 11937 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11938 LLVM_FALLTHROUGH; 11939 case Builtin::BI__builtin_strlen: 11940 case Builtin::BI__builtin_wcslen: { 11941 // As an extension, we support __builtin_strlen() as a constant expression, 11942 // and support folding strlen() to a constant. 11943 uint64_t StrLen; 11944 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 11945 return Success(StrLen, E); 11946 return false; 11947 } 11948 11949 case Builtin::BIstrcmp: 11950 case Builtin::BIwcscmp: 11951 case Builtin::BIstrncmp: 11952 case Builtin::BIwcsncmp: 11953 case Builtin::BImemcmp: 11954 case Builtin::BIbcmp: 11955 case Builtin::BIwmemcmp: 11956 // A call to strlen is not a constant expression. 11957 if (Info.getLangOpts().CPlusPlus11) 11958 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11959 << /*isConstexpr*/0 << /*isConstructor*/0 11960 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11961 else 11962 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11963 LLVM_FALLTHROUGH; 11964 case Builtin::BI__builtin_strcmp: 11965 case Builtin::BI__builtin_wcscmp: 11966 case Builtin::BI__builtin_strncmp: 11967 case Builtin::BI__builtin_wcsncmp: 11968 case Builtin::BI__builtin_memcmp: 11969 case Builtin::BI__builtin_bcmp: 11970 case Builtin::BI__builtin_wmemcmp: { 11971 LValue String1, String2; 11972 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11973 !EvaluatePointer(E->getArg(1), String2, Info)) 11974 return false; 11975 11976 uint64_t MaxLength = uint64_t(-1); 11977 if (BuiltinOp != Builtin::BIstrcmp && 11978 BuiltinOp != Builtin::BIwcscmp && 11979 BuiltinOp != Builtin::BI__builtin_strcmp && 11980 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11981 APSInt N; 11982 if (!EvaluateInteger(E->getArg(2), N, Info)) 11983 return false; 11984 MaxLength = N.getExtValue(); 11985 } 11986 11987 // Empty substrings compare equal by definition. 11988 if (MaxLength == 0u) 11989 return Success(0, E); 11990 11991 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11992 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11993 String1.Designator.Invalid || String2.Designator.Invalid) 11994 return false; 11995 11996 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11997 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11998 11999 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12000 BuiltinOp == Builtin::BIbcmp || 12001 BuiltinOp == Builtin::BI__builtin_memcmp || 12002 BuiltinOp == Builtin::BI__builtin_bcmp; 12003 12004 assert(IsRawByte || 12005 (Info.Ctx.hasSameUnqualifiedType( 12006 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12007 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12008 12009 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12010 // 'char8_t', but no other types. 12011 if (IsRawByte && 12012 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12013 // FIXME: Consider using our bit_cast implementation to support this. 12014 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12015 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 12016 << CharTy1 << CharTy2; 12017 return false; 12018 } 12019 12020 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12021 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12022 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12023 Char1.isInt() && Char2.isInt(); 12024 }; 12025 const auto &AdvanceElems = [&] { 12026 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12027 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12028 }; 12029 12030 bool StopAtNull = 12031 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12032 BuiltinOp != Builtin::BIwmemcmp && 12033 BuiltinOp != Builtin::BI__builtin_memcmp && 12034 BuiltinOp != Builtin::BI__builtin_bcmp && 12035 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12036 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12037 BuiltinOp == Builtin::BIwcsncmp || 12038 BuiltinOp == Builtin::BIwmemcmp || 12039 BuiltinOp == Builtin::BI__builtin_wcscmp || 12040 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12041 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12042 12043 for (; MaxLength; --MaxLength) { 12044 APValue Char1, Char2; 12045 if (!ReadCurElems(Char1, Char2)) 12046 return false; 12047 if (Char1.getInt().ne(Char2.getInt())) { 12048 if (IsWide) // wmemcmp compares with wchar_t signedness. 12049 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12050 // memcmp always compares unsigned chars. 12051 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12052 } 12053 if (StopAtNull && !Char1.getInt()) 12054 return Success(0, E); 12055 assert(!(StopAtNull && !Char2.getInt())); 12056 if (!AdvanceElems()) 12057 return false; 12058 } 12059 // We hit the strncmp / memcmp limit. 12060 return Success(0, E); 12061 } 12062 12063 case Builtin::BI__atomic_always_lock_free: 12064 case Builtin::BI__atomic_is_lock_free: 12065 case Builtin::BI__c11_atomic_is_lock_free: { 12066 APSInt SizeVal; 12067 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12068 return false; 12069 12070 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12071 // of two less than or equal to the maximum inline atomic width, we know it 12072 // is lock-free. If the size isn't a power of two, or greater than the 12073 // maximum alignment where we promote atomics, we know it is not lock-free 12074 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12075 // the answer can only be determined at runtime; for example, 16-byte 12076 // atomics have lock-free implementations on some, but not all, 12077 // x86-64 processors. 12078 12079 // Check power-of-two. 12080 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12081 if (Size.isPowerOfTwo()) { 12082 // Check against inlining width. 12083 unsigned InlineWidthBits = 12084 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12085 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12086 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12087 Size == CharUnits::One() || 12088 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12089 Expr::NPC_NeverValueDependent)) 12090 // OK, we will inline appropriately-aligned operations of this size, 12091 // and _Atomic(T) is appropriately-aligned. 12092 return Success(1, E); 12093 12094 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12095 castAs<PointerType>()->getPointeeType(); 12096 if (!PointeeType->isIncompleteType() && 12097 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12098 // OK, we will inline operations on this object. 12099 return Success(1, E); 12100 } 12101 } 12102 } 12103 12104 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12105 Success(0, E) : Error(E); 12106 } 12107 case Builtin::BI__builtin_add_overflow: 12108 case Builtin::BI__builtin_sub_overflow: 12109 case Builtin::BI__builtin_mul_overflow: 12110 case Builtin::BI__builtin_sadd_overflow: 12111 case Builtin::BI__builtin_uadd_overflow: 12112 case Builtin::BI__builtin_uaddl_overflow: 12113 case Builtin::BI__builtin_uaddll_overflow: 12114 case Builtin::BI__builtin_usub_overflow: 12115 case Builtin::BI__builtin_usubl_overflow: 12116 case Builtin::BI__builtin_usubll_overflow: 12117 case Builtin::BI__builtin_umul_overflow: 12118 case Builtin::BI__builtin_umull_overflow: 12119 case Builtin::BI__builtin_umulll_overflow: 12120 case Builtin::BI__builtin_saddl_overflow: 12121 case Builtin::BI__builtin_saddll_overflow: 12122 case Builtin::BI__builtin_ssub_overflow: 12123 case Builtin::BI__builtin_ssubl_overflow: 12124 case Builtin::BI__builtin_ssubll_overflow: 12125 case Builtin::BI__builtin_smul_overflow: 12126 case Builtin::BI__builtin_smull_overflow: 12127 case Builtin::BI__builtin_smulll_overflow: { 12128 LValue ResultLValue; 12129 APSInt LHS, RHS; 12130 12131 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12132 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12133 !EvaluateInteger(E->getArg(1), RHS, Info) || 12134 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12135 return false; 12136 12137 APSInt Result; 12138 bool DidOverflow = false; 12139 12140 // If the types don't have to match, enlarge all 3 to the largest of them. 12141 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12142 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12143 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12144 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12145 ResultType->isSignedIntegerOrEnumerationType(); 12146 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12147 ResultType->isSignedIntegerOrEnumerationType(); 12148 uint64_t LHSSize = LHS.getBitWidth(); 12149 uint64_t RHSSize = RHS.getBitWidth(); 12150 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12151 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12152 12153 // Add an additional bit if the signedness isn't uniformly agreed to. We 12154 // could do this ONLY if there is a signed and an unsigned that both have 12155 // MaxBits, but the code to check that is pretty nasty. The issue will be 12156 // caught in the shrink-to-result later anyway. 12157 if (IsSigned && !AllSigned) 12158 ++MaxBits; 12159 12160 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12161 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12162 Result = APSInt(MaxBits, !IsSigned); 12163 } 12164 12165 // Find largest int. 12166 switch (BuiltinOp) { 12167 default: 12168 llvm_unreachable("Invalid value for BuiltinOp"); 12169 case Builtin::BI__builtin_add_overflow: 12170 case Builtin::BI__builtin_sadd_overflow: 12171 case Builtin::BI__builtin_saddl_overflow: 12172 case Builtin::BI__builtin_saddll_overflow: 12173 case Builtin::BI__builtin_uadd_overflow: 12174 case Builtin::BI__builtin_uaddl_overflow: 12175 case Builtin::BI__builtin_uaddll_overflow: 12176 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12177 : LHS.uadd_ov(RHS, DidOverflow); 12178 break; 12179 case Builtin::BI__builtin_sub_overflow: 12180 case Builtin::BI__builtin_ssub_overflow: 12181 case Builtin::BI__builtin_ssubl_overflow: 12182 case Builtin::BI__builtin_ssubll_overflow: 12183 case Builtin::BI__builtin_usub_overflow: 12184 case Builtin::BI__builtin_usubl_overflow: 12185 case Builtin::BI__builtin_usubll_overflow: 12186 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12187 : LHS.usub_ov(RHS, DidOverflow); 12188 break; 12189 case Builtin::BI__builtin_mul_overflow: 12190 case Builtin::BI__builtin_smul_overflow: 12191 case Builtin::BI__builtin_smull_overflow: 12192 case Builtin::BI__builtin_smulll_overflow: 12193 case Builtin::BI__builtin_umul_overflow: 12194 case Builtin::BI__builtin_umull_overflow: 12195 case Builtin::BI__builtin_umulll_overflow: 12196 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12197 : LHS.umul_ov(RHS, DidOverflow); 12198 break; 12199 } 12200 12201 // In the case where multiple sizes are allowed, truncate and see if 12202 // the values are the same. 12203 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12204 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12205 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12206 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12207 // since it will give us the behavior of a TruncOrSelf in the case where 12208 // its parameter <= its size. We previously set Result to be at least the 12209 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12210 // will work exactly like TruncOrSelf. 12211 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12212 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12213 12214 if (!APSInt::isSameValue(Temp, Result)) 12215 DidOverflow = true; 12216 Result = Temp; 12217 } 12218 12219 APValue APV{Result}; 12220 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12221 return false; 12222 return Success(DidOverflow, E); 12223 } 12224 } 12225 } 12226 12227 /// Determine whether this is a pointer past the end of the complete 12228 /// object referred to by the lvalue. 12229 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12230 const LValue &LV) { 12231 // A null pointer can be viewed as being "past the end" but we don't 12232 // choose to look at it that way here. 12233 if (!LV.getLValueBase()) 12234 return false; 12235 12236 // If the designator is valid and refers to a subobject, we're not pointing 12237 // past the end. 12238 if (!LV.getLValueDesignator().Invalid && 12239 !LV.getLValueDesignator().isOnePastTheEnd()) 12240 return false; 12241 12242 // A pointer to an incomplete type might be past-the-end if the type's size is 12243 // zero. We cannot tell because the type is incomplete. 12244 QualType Ty = getType(LV.getLValueBase()); 12245 if (Ty->isIncompleteType()) 12246 return true; 12247 12248 // We're a past-the-end pointer if we point to the byte after the object, 12249 // no matter what our type or path is. 12250 auto Size = Ctx.getTypeSizeInChars(Ty); 12251 return LV.getLValueOffset() == Size; 12252 } 12253 12254 namespace { 12255 12256 /// Data recursive integer evaluator of certain binary operators. 12257 /// 12258 /// We use a data recursive algorithm for binary operators so that we are able 12259 /// to handle extreme cases of chained binary operators without causing stack 12260 /// overflow. 12261 class DataRecursiveIntBinOpEvaluator { 12262 struct EvalResult { 12263 APValue Val; 12264 bool Failed; 12265 12266 EvalResult() : Failed(false) { } 12267 12268 void swap(EvalResult &RHS) { 12269 Val.swap(RHS.Val); 12270 Failed = RHS.Failed; 12271 RHS.Failed = false; 12272 } 12273 }; 12274 12275 struct Job { 12276 const Expr *E; 12277 EvalResult LHSResult; // meaningful only for binary operator expression. 12278 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12279 12280 Job() = default; 12281 Job(Job &&) = default; 12282 12283 void startSpeculativeEval(EvalInfo &Info) { 12284 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12285 } 12286 12287 private: 12288 SpeculativeEvaluationRAII SpecEvalRAII; 12289 }; 12290 12291 SmallVector<Job, 16> Queue; 12292 12293 IntExprEvaluator &IntEval; 12294 EvalInfo &Info; 12295 APValue &FinalResult; 12296 12297 public: 12298 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12299 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12300 12301 /// True if \param E is a binary operator that we are going to handle 12302 /// data recursively. 12303 /// We handle binary operators that are comma, logical, or that have operands 12304 /// with integral or enumeration type. 12305 static bool shouldEnqueue(const BinaryOperator *E) { 12306 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12307 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12308 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12309 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12310 } 12311 12312 bool Traverse(const BinaryOperator *E) { 12313 enqueue(E); 12314 EvalResult PrevResult; 12315 while (!Queue.empty()) 12316 process(PrevResult); 12317 12318 if (PrevResult.Failed) return false; 12319 12320 FinalResult.swap(PrevResult.Val); 12321 return true; 12322 } 12323 12324 private: 12325 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12326 return IntEval.Success(Value, E, Result); 12327 } 12328 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12329 return IntEval.Success(Value, E, Result); 12330 } 12331 bool Error(const Expr *E) { 12332 return IntEval.Error(E); 12333 } 12334 bool Error(const Expr *E, diag::kind D) { 12335 return IntEval.Error(E, D); 12336 } 12337 12338 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12339 return Info.CCEDiag(E, D); 12340 } 12341 12342 // Returns true if visiting the RHS is necessary, false otherwise. 12343 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12344 bool &SuppressRHSDiags); 12345 12346 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12347 const BinaryOperator *E, APValue &Result); 12348 12349 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12350 Result.Failed = !Evaluate(Result.Val, Info, E); 12351 if (Result.Failed) 12352 Result.Val = APValue(); 12353 } 12354 12355 void process(EvalResult &Result); 12356 12357 void enqueue(const Expr *E) { 12358 E = E->IgnoreParens(); 12359 Queue.resize(Queue.size()+1); 12360 Queue.back().E = E; 12361 Queue.back().Kind = Job::AnyExprKind; 12362 } 12363 }; 12364 12365 } 12366 12367 bool DataRecursiveIntBinOpEvaluator:: 12368 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12369 bool &SuppressRHSDiags) { 12370 if (E->getOpcode() == BO_Comma) { 12371 // Ignore LHS but note if we could not evaluate it. 12372 if (LHSResult.Failed) 12373 return Info.noteSideEffect(); 12374 return true; 12375 } 12376 12377 if (E->isLogicalOp()) { 12378 bool LHSAsBool; 12379 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12380 // We were able to evaluate the LHS, see if we can get away with not 12381 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12382 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12383 Success(LHSAsBool, E, LHSResult.Val); 12384 return false; // Ignore RHS 12385 } 12386 } else { 12387 LHSResult.Failed = true; 12388 12389 // Since we weren't able to evaluate the left hand side, it 12390 // might have had side effects. 12391 if (!Info.noteSideEffect()) 12392 return false; 12393 12394 // We can't evaluate the LHS; however, sometimes the result 12395 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12396 // Don't ignore RHS and suppress diagnostics from this arm. 12397 SuppressRHSDiags = true; 12398 } 12399 12400 return true; 12401 } 12402 12403 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12404 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12405 12406 if (LHSResult.Failed && !Info.noteFailure()) 12407 return false; // Ignore RHS; 12408 12409 return true; 12410 } 12411 12412 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12413 bool IsSub) { 12414 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12415 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12416 // offsets. 12417 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12418 CharUnits &Offset = LVal.getLValueOffset(); 12419 uint64_t Offset64 = Offset.getQuantity(); 12420 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12421 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12422 : Offset64 + Index64); 12423 } 12424 12425 bool DataRecursiveIntBinOpEvaluator:: 12426 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12427 const BinaryOperator *E, APValue &Result) { 12428 if (E->getOpcode() == BO_Comma) { 12429 if (RHSResult.Failed) 12430 return false; 12431 Result = RHSResult.Val; 12432 return true; 12433 } 12434 12435 if (E->isLogicalOp()) { 12436 bool lhsResult, rhsResult; 12437 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12438 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12439 12440 if (LHSIsOK) { 12441 if (RHSIsOK) { 12442 if (E->getOpcode() == BO_LOr) 12443 return Success(lhsResult || rhsResult, E, Result); 12444 else 12445 return Success(lhsResult && rhsResult, E, Result); 12446 } 12447 } else { 12448 if (RHSIsOK) { 12449 // We can't evaluate the LHS; however, sometimes the result 12450 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12451 if (rhsResult == (E->getOpcode() == BO_LOr)) 12452 return Success(rhsResult, E, Result); 12453 } 12454 } 12455 12456 return false; 12457 } 12458 12459 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12460 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12461 12462 if (LHSResult.Failed || RHSResult.Failed) 12463 return false; 12464 12465 const APValue &LHSVal = LHSResult.Val; 12466 const APValue &RHSVal = RHSResult.Val; 12467 12468 // Handle cases like (unsigned long)&a + 4. 12469 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12470 Result = LHSVal; 12471 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12472 return true; 12473 } 12474 12475 // Handle cases like 4 + (unsigned long)&a 12476 if (E->getOpcode() == BO_Add && 12477 RHSVal.isLValue() && LHSVal.isInt()) { 12478 Result = RHSVal; 12479 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12480 return true; 12481 } 12482 12483 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12484 // Handle (intptr_t)&&A - (intptr_t)&&B. 12485 if (!LHSVal.getLValueOffset().isZero() || 12486 !RHSVal.getLValueOffset().isZero()) 12487 return false; 12488 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12489 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12490 if (!LHSExpr || !RHSExpr) 12491 return false; 12492 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12493 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12494 if (!LHSAddrExpr || !RHSAddrExpr) 12495 return false; 12496 // Make sure both labels come from the same function. 12497 if (LHSAddrExpr->getLabel()->getDeclContext() != 12498 RHSAddrExpr->getLabel()->getDeclContext()) 12499 return false; 12500 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12501 return true; 12502 } 12503 12504 // All the remaining cases expect both operands to be an integer 12505 if (!LHSVal.isInt() || !RHSVal.isInt()) 12506 return Error(E); 12507 12508 // Set up the width and signedness manually, in case it can't be deduced 12509 // from the operation we're performing. 12510 // FIXME: Don't do this in the cases where we can deduce it. 12511 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12512 E->getType()->isUnsignedIntegerOrEnumerationType()); 12513 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12514 RHSVal.getInt(), Value)) 12515 return false; 12516 return Success(Value, E, Result); 12517 } 12518 12519 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12520 Job &job = Queue.back(); 12521 12522 switch (job.Kind) { 12523 case Job::AnyExprKind: { 12524 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12525 if (shouldEnqueue(Bop)) { 12526 job.Kind = Job::BinOpKind; 12527 enqueue(Bop->getLHS()); 12528 return; 12529 } 12530 } 12531 12532 EvaluateExpr(job.E, Result); 12533 Queue.pop_back(); 12534 return; 12535 } 12536 12537 case Job::BinOpKind: { 12538 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12539 bool SuppressRHSDiags = false; 12540 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12541 Queue.pop_back(); 12542 return; 12543 } 12544 if (SuppressRHSDiags) 12545 job.startSpeculativeEval(Info); 12546 job.LHSResult.swap(Result); 12547 job.Kind = Job::BinOpVisitedLHSKind; 12548 enqueue(Bop->getRHS()); 12549 return; 12550 } 12551 12552 case Job::BinOpVisitedLHSKind: { 12553 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12554 EvalResult RHS; 12555 RHS.swap(Result); 12556 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12557 Queue.pop_back(); 12558 return; 12559 } 12560 } 12561 12562 llvm_unreachable("Invalid Job::Kind!"); 12563 } 12564 12565 namespace { 12566 enum class CmpResult { 12567 Unequal, 12568 Less, 12569 Equal, 12570 Greater, 12571 Unordered, 12572 }; 12573 } 12574 12575 template <class SuccessCB, class AfterCB> 12576 static bool 12577 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12578 SuccessCB &&Success, AfterCB &&DoAfter) { 12579 assert(!E->isValueDependent()); 12580 assert(E->isComparisonOp() && "expected comparison operator"); 12581 assert((E->getOpcode() == BO_Cmp || 12582 E->getType()->isIntegralOrEnumerationType()) && 12583 "unsupported binary expression evaluation"); 12584 auto Error = [&](const Expr *E) { 12585 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12586 return false; 12587 }; 12588 12589 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12590 bool IsEquality = E->isEqualityOp(); 12591 12592 QualType LHSTy = E->getLHS()->getType(); 12593 QualType RHSTy = E->getRHS()->getType(); 12594 12595 if (LHSTy->isIntegralOrEnumerationType() && 12596 RHSTy->isIntegralOrEnumerationType()) { 12597 APSInt LHS, RHS; 12598 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12599 if (!LHSOK && !Info.noteFailure()) 12600 return false; 12601 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12602 return false; 12603 if (LHS < RHS) 12604 return Success(CmpResult::Less, E); 12605 if (LHS > RHS) 12606 return Success(CmpResult::Greater, E); 12607 return Success(CmpResult::Equal, E); 12608 } 12609 12610 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12611 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12612 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12613 12614 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12615 if (!LHSOK && !Info.noteFailure()) 12616 return false; 12617 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12618 return false; 12619 if (LHSFX < RHSFX) 12620 return Success(CmpResult::Less, E); 12621 if (LHSFX > RHSFX) 12622 return Success(CmpResult::Greater, E); 12623 return Success(CmpResult::Equal, E); 12624 } 12625 12626 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12627 ComplexValue LHS, RHS; 12628 bool LHSOK; 12629 if (E->isAssignmentOp()) { 12630 LValue LV; 12631 EvaluateLValue(E->getLHS(), LV, Info); 12632 LHSOK = false; 12633 } else if (LHSTy->isRealFloatingType()) { 12634 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12635 if (LHSOK) { 12636 LHS.makeComplexFloat(); 12637 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12638 } 12639 } else { 12640 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12641 } 12642 if (!LHSOK && !Info.noteFailure()) 12643 return false; 12644 12645 if (E->getRHS()->getType()->isRealFloatingType()) { 12646 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12647 return false; 12648 RHS.makeComplexFloat(); 12649 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12650 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12651 return false; 12652 12653 if (LHS.isComplexFloat()) { 12654 APFloat::cmpResult CR_r = 12655 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12656 APFloat::cmpResult CR_i = 12657 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12658 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12659 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12660 } else { 12661 assert(IsEquality && "invalid complex comparison"); 12662 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12663 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12664 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12665 } 12666 } 12667 12668 if (LHSTy->isRealFloatingType() && 12669 RHSTy->isRealFloatingType()) { 12670 APFloat RHS(0.0), LHS(0.0); 12671 12672 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12673 if (!LHSOK && !Info.noteFailure()) 12674 return false; 12675 12676 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12677 return false; 12678 12679 assert(E->isComparisonOp() && "Invalid binary operator!"); 12680 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12681 if (!Info.InConstantContext && 12682 APFloatCmpResult == APFloat::cmpUnordered && 12683 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12684 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12685 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12686 return false; 12687 } 12688 auto GetCmpRes = [&]() { 12689 switch (APFloatCmpResult) { 12690 case APFloat::cmpEqual: 12691 return CmpResult::Equal; 12692 case APFloat::cmpLessThan: 12693 return CmpResult::Less; 12694 case APFloat::cmpGreaterThan: 12695 return CmpResult::Greater; 12696 case APFloat::cmpUnordered: 12697 return CmpResult::Unordered; 12698 } 12699 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12700 }; 12701 return Success(GetCmpRes(), E); 12702 } 12703 12704 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12705 LValue LHSValue, RHSValue; 12706 12707 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12708 if (!LHSOK && !Info.noteFailure()) 12709 return false; 12710 12711 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12712 return false; 12713 12714 // Reject differing bases from the normal codepath; we special-case 12715 // comparisons to null. 12716 if (!HasSameBase(LHSValue, RHSValue)) { 12717 // Inequalities and subtractions between unrelated pointers have 12718 // unspecified or undefined behavior. 12719 if (!IsEquality) { 12720 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12721 return false; 12722 } 12723 // A constant address may compare equal to the address of a symbol. 12724 // The one exception is that address of an object cannot compare equal 12725 // to a null pointer constant. 12726 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12727 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12728 return Error(E); 12729 // It's implementation-defined whether distinct literals will have 12730 // distinct addresses. In clang, the result of such a comparison is 12731 // unspecified, so it is not a constant expression. However, we do know 12732 // that the address of a literal will be non-null. 12733 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12734 LHSValue.Base && RHSValue.Base) 12735 return Error(E); 12736 // We can't tell whether weak symbols will end up pointing to the same 12737 // object. 12738 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12739 return Error(E); 12740 // We can't compare the address of the start of one object with the 12741 // past-the-end address of another object, per C++ DR1652. 12742 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12743 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12744 (RHSValue.Base && RHSValue.Offset.isZero() && 12745 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12746 return Error(E); 12747 // We can't tell whether an object is at the same address as another 12748 // zero sized object. 12749 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12750 (LHSValue.Base && isZeroSized(RHSValue))) 12751 return Error(E); 12752 return Success(CmpResult::Unequal, E); 12753 } 12754 12755 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12756 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12757 12758 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12759 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12760 12761 // C++11 [expr.rel]p3: 12762 // Pointers to void (after pointer conversions) can be compared, with a 12763 // result defined as follows: If both pointers represent the same 12764 // address or are both the null pointer value, the result is true if the 12765 // operator is <= or >= and false otherwise; otherwise the result is 12766 // unspecified. 12767 // We interpret this as applying to pointers to *cv* void. 12768 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12769 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12770 12771 // C++11 [expr.rel]p2: 12772 // - If two pointers point to non-static data members of the same object, 12773 // or to subobjects or array elements fo such members, recursively, the 12774 // pointer to the later declared member compares greater provided the 12775 // two members have the same access control and provided their class is 12776 // not a union. 12777 // [...] 12778 // - Otherwise pointer comparisons are unspecified. 12779 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12780 bool WasArrayIndex; 12781 unsigned Mismatch = FindDesignatorMismatch( 12782 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12783 // At the point where the designators diverge, the comparison has a 12784 // specified value if: 12785 // - we are comparing array indices 12786 // - we are comparing fields of a union, or fields with the same access 12787 // Otherwise, the result is unspecified and thus the comparison is not a 12788 // constant expression. 12789 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12790 Mismatch < RHSDesignator.Entries.size()) { 12791 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12792 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12793 if (!LF && !RF) 12794 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12795 else if (!LF) 12796 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12797 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12798 << RF->getParent() << RF; 12799 else if (!RF) 12800 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12801 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12802 << LF->getParent() << LF; 12803 else if (!LF->getParent()->isUnion() && 12804 LF->getAccess() != RF->getAccess()) 12805 Info.CCEDiag(E, 12806 diag::note_constexpr_pointer_comparison_differing_access) 12807 << LF << LF->getAccess() << RF << RF->getAccess() 12808 << LF->getParent(); 12809 } 12810 } 12811 12812 // The comparison here must be unsigned, and performed with the same 12813 // width as the pointer. 12814 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12815 uint64_t CompareLHS = LHSOffset.getQuantity(); 12816 uint64_t CompareRHS = RHSOffset.getQuantity(); 12817 assert(PtrSize <= 64 && "Unexpected pointer width"); 12818 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12819 CompareLHS &= Mask; 12820 CompareRHS &= Mask; 12821 12822 // If there is a base and this is a relational operator, we can only 12823 // compare pointers within the object in question; otherwise, the result 12824 // depends on where the object is located in memory. 12825 if (!LHSValue.Base.isNull() && IsRelational) { 12826 QualType BaseTy = getType(LHSValue.Base); 12827 if (BaseTy->isIncompleteType()) 12828 return Error(E); 12829 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12830 uint64_t OffsetLimit = Size.getQuantity(); 12831 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12832 return Error(E); 12833 } 12834 12835 if (CompareLHS < CompareRHS) 12836 return Success(CmpResult::Less, E); 12837 if (CompareLHS > CompareRHS) 12838 return Success(CmpResult::Greater, E); 12839 return Success(CmpResult::Equal, E); 12840 } 12841 12842 if (LHSTy->isMemberPointerType()) { 12843 assert(IsEquality && "unexpected member pointer operation"); 12844 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12845 12846 MemberPtr LHSValue, RHSValue; 12847 12848 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12849 if (!LHSOK && !Info.noteFailure()) 12850 return false; 12851 12852 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12853 return false; 12854 12855 // C++11 [expr.eq]p2: 12856 // If both operands are null, they compare equal. Otherwise if only one is 12857 // null, they compare unequal. 12858 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12859 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12860 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12861 } 12862 12863 // Otherwise if either is a pointer to a virtual member function, the 12864 // result is unspecified. 12865 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12866 if (MD->isVirtual()) 12867 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12868 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12869 if (MD->isVirtual()) 12870 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12871 12872 // Otherwise they compare equal if and only if they would refer to the 12873 // same member of the same most derived object or the same subobject if 12874 // they were dereferenced with a hypothetical object of the associated 12875 // class type. 12876 bool Equal = LHSValue == RHSValue; 12877 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12878 } 12879 12880 if (LHSTy->isNullPtrType()) { 12881 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12882 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12883 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12884 // are compared, the result is true of the operator is <=, >= or ==, and 12885 // false otherwise. 12886 return Success(CmpResult::Equal, E); 12887 } 12888 12889 return DoAfter(); 12890 } 12891 12892 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12893 if (!CheckLiteralType(Info, E)) 12894 return false; 12895 12896 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12897 ComparisonCategoryResult CCR; 12898 switch (CR) { 12899 case CmpResult::Unequal: 12900 llvm_unreachable("should never produce Unequal for three-way comparison"); 12901 case CmpResult::Less: 12902 CCR = ComparisonCategoryResult::Less; 12903 break; 12904 case CmpResult::Equal: 12905 CCR = ComparisonCategoryResult::Equal; 12906 break; 12907 case CmpResult::Greater: 12908 CCR = ComparisonCategoryResult::Greater; 12909 break; 12910 case CmpResult::Unordered: 12911 CCR = ComparisonCategoryResult::Unordered; 12912 break; 12913 } 12914 // Evaluation succeeded. Lookup the information for the comparison category 12915 // type and fetch the VarDecl for the result. 12916 const ComparisonCategoryInfo &CmpInfo = 12917 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12918 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12919 // Check and evaluate the result as a constant expression. 12920 LValue LV; 12921 LV.set(VD); 12922 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12923 return false; 12924 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12925 ConstantExprKind::Normal); 12926 }; 12927 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12928 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12929 }); 12930 } 12931 12932 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12933 // We don't support assignment in C. C++ assignments don't get here because 12934 // assignment is an lvalue in C++. 12935 if (E->isAssignmentOp()) { 12936 Error(E); 12937 if (!Info.noteFailure()) 12938 return false; 12939 } 12940 12941 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12942 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12943 12944 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12945 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12946 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12947 12948 if (E->isComparisonOp()) { 12949 // Evaluate builtin binary comparisons by evaluating them as three-way 12950 // comparisons and then translating the result. 12951 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12952 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12953 "should only produce Unequal for equality comparisons"); 12954 bool IsEqual = CR == CmpResult::Equal, 12955 IsLess = CR == CmpResult::Less, 12956 IsGreater = CR == CmpResult::Greater; 12957 auto Op = E->getOpcode(); 12958 switch (Op) { 12959 default: 12960 llvm_unreachable("unsupported binary operator"); 12961 case BO_EQ: 12962 case BO_NE: 12963 return Success(IsEqual == (Op == BO_EQ), E); 12964 case BO_LT: 12965 return Success(IsLess, E); 12966 case BO_GT: 12967 return Success(IsGreater, E); 12968 case BO_LE: 12969 return Success(IsEqual || IsLess, E); 12970 case BO_GE: 12971 return Success(IsEqual || IsGreater, E); 12972 } 12973 }; 12974 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12975 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12976 }); 12977 } 12978 12979 QualType LHSTy = E->getLHS()->getType(); 12980 QualType RHSTy = E->getRHS()->getType(); 12981 12982 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12983 E->getOpcode() == BO_Sub) { 12984 LValue LHSValue, RHSValue; 12985 12986 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12987 if (!LHSOK && !Info.noteFailure()) 12988 return false; 12989 12990 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12991 return false; 12992 12993 // Reject differing bases from the normal codepath; we special-case 12994 // comparisons to null. 12995 if (!HasSameBase(LHSValue, RHSValue)) { 12996 // Handle &&A - &&B. 12997 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12998 return Error(E); 12999 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13000 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13001 if (!LHSExpr || !RHSExpr) 13002 return Error(E); 13003 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13004 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13005 if (!LHSAddrExpr || !RHSAddrExpr) 13006 return Error(E); 13007 // Make sure both labels come from the same function. 13008 if (LHSAddrExpr->getLabel()->getDeclContext() != 13009 RHSAddrExpr->getLabel()->getDeclContext()) 13010 return Error(E); 13011 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13012 } 13013 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13014 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13015 13016 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13017 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13018 13019 // C++11 [expr.add]p6: 13020 // Unless both pointers point to elements of the same array object, or 13021 // one past the last element of the array object, the behavior is 13022 // undefined. 13023 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13024 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13025 RHSDesignator)) 13026 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13027 13028 QualType Type = E->getLHS()->getType(); 13029 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13030 13031 CharUnits ElementSize; 13032 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13033 return false; 13034 13035 // As an extension, a type may have zero size (empty struct or union in 13036 // C, array of zero length). Pointer subtraction in such cases has 13037 // undefined behavior, so is not constant. 13038 if (ElementSize.isZero()) { 13039 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13040 << ElementType; 13041 return false; 13042 } 13043 13044 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13045 // and produce incorrect results when it overflows. Such behavior 13046 // appears to be non-conforming, but is common, so perhaps we should 13047 // assume the standard intended for such cases to be undefined behavior 13048 // and check for them. 13049 13050 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13051 // overflow in the final conversion to ptrdiff_t. 13052 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13053 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13054 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13055 false); 13056 APSInt TrueResult = (LHS - RHS) / ElemSize; 13057 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13058 13059 if (Result.extend(65) != TrueResult && 13060 !HandleOverflow(Info, E, TrueResult, E->getType())) 13061 return false; 13062 return Success(Result, E); 13063 } 13064 13065 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13066 } 13067 13068 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13069 /// a result as the expression's type. 13070 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13071 const UnaryExprOrTypeTraitExpr *E) { 13072 switch(E->getKind()) { 13073 case UETT_PreferredAlignOf: 13074 case UETT_AlignOf: { 13075 if (E->isArgumentType()) 13076 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13077 E); 13078 else 13079 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13080 E); 13081 } 13082 13083 case UETT_VecStep: { 13084 QualType Ty = E->getTypeOfArgument(); 13085 13086 if (Ty->isVectorType()) { 13087 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13088 13089 // The vec_step built-in functions that take a 3-component 13090 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13091 if (n == 3) 13092 n = 4; 13093 13094 return Success(n, E); 13095 } else 13096 return Success(1, E); 13097 } 13098 13099 case UETT_SizeOf: { 13100 QualType SrcTy = E->getTypeOfArgument(); 13101 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13102 // the result is the size of the referenced type." 13103 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13104 SrcTy = Ref->getPointeeType(); 13105 13106 CharUnits Sizeof; 13107 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13108 return false; 13109 return Success(Sizeof, E); 13110 } 13111 case UETT_OpenMPRequiredSimdAlign: 13112 assert(E->isArgumentType()); 13113 return Success( 13114 Info.Ctx.toCharUnitsFromBits( 13115 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13116 .getQuantity(), 13117 E); 13118 } 13119 13120 llvm_unreachable("unknown expr/type trait"); 13121 } 13122 13123 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13124 CharUnits Result; 13125 unsigned n = OOE->getNumComponents(); 13126 if (n == 0) 13127 return Error(OOE); 13128 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13129 for (unsigned i = 0; i != n; ++i) { 13130 OffsetOfNode ON = OOE->getComponent(i); 13131 switch (ON.getKind()) { 13132 case OffsetOfNode::Array: { 13133 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13134 APSInt IdxResult; 13135 if (!EvaluateInteger(Idx, IdxResult, Info)) 13136 return false; 13137 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13138 if (!AT) 13139 return Error(OOE); 13140 CurrentType = AT->getElementType(); 13141 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13142 Result += IdxResult.getSExtValue() * ElementSize; 13143 break; 13144 } 13145 13146 case OffsetOfNode::Field: { 13147 FieldDecl *MemberDecl = ON.getField(); 13148 const RecordType *RT = CurrentType->getAs<RecordType>(); 13149 if (!RT) 13150 return Error(OOE); 13151 RecordDecl *RD = RT->getDecl(); 13152 if (RD->isInvalidDecl()) return false; 13153 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13154 unsigned i = MemberDecl->getFieldIndex(); 13155 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13156 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13157 CurrentType = MemberDecl->getType().getNonReferenceType(); 13158 break; 13159 } 13160 13161 case OffsetOfNode::Identifier: 13162 llvm_unreachable("dependent __builtin_offsetof"); 13163 13164 case OffsetOfNode::Base: { 13165 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13166 if (BaseSpec->isVirtual()) 13167 return Error(OOE); 13168 13169 // Find the layout of the class whose base we are looking into. 13170 const RecordType *RT = CurrentType->getAs<RecordType>(); 13171 if (!RT) 13172 return Error(OOE); 13173 RecordDecl *RD = RT->getDecl(); 13174 if (RD->isInvalidDecl()) return false; 13175 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13176 13177 // Find the base class itself. 13178 CurrentType = BaseSpec->getType(); 13179 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13180 if (!BaseRT) 13181 return Error(OOE); 13182 13183 // Add the offset to the base. 13184 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13185 break; 13186 } 13187 } 13188 } 13189 return Success(Result, OOE); 13190 } 13191 13192 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13193 switch (E->getOpcode()) { 13194 default: 13195 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13196 // See C99 6.6p3. 13197 return Error(E); 13198 case UO_Extension: 13199 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13200 // If so, we could clear the diagnostic ID. 13201 return Visit(E->getSubExpr()); 13202 case UO_Plus: 13203 // The result is just the value. 13204 return Visit(E->getSubExpr()); 13205 case UO_Minus: { 13206 if (!Visit(E->getSubExpr())) 13207 return false; 13208 if (!Result.isInt()) return Error(E); 13209 const APSInt &Value = Result.getInt(); 13210 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13211 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13212 E->getType())) 13213 return false; 13214 return Success(-Value, E); 13215 } 13216 case UO_Not: { 13217 if (!Visit(E->getSubExpr())) 13218 return false; 13219 if (!Result.isInt()) return Error(E); 13220 return Success(~Result.getInt(), E); 13221 } 13222 case UO_LNot: { 13223 bool bres; 13224 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13225 return false; 13226 return Success(!bres, E); 13227 } 13228 } 13229 } 13230 13231 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13232 /// result type is integer. 13233 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13234 const Expr *SubExpr = E->getSubExpr(); 13235 QualType DestType = E->getType(); 13236 QualType SrcType = SubExpr->getType(); 13237 13238 switch (E->getCastKind()) { 13239 case CK_BaseToDerived: 13240 case CK_DerivedToBase: 13241 case CK_UncheckedDerivedToBase: 13242 case CK_Dynamic: 13243 case CK_ToUnion: 13244 case CK_ArrayToPointerDecay: 13245 case CK_FunctionToPointerDecay: 13246 case CK_NullToPointer: 13247 case CK_NullToMemberPointer: 13248 case CK_BaseToDerivedMemberPointer: 13249 case CK_DerivedToBaseMemberPointer: 13250 case CK_ReinterpretMemberPointer: 13251 case CK_ConstructorConversion: 13252 case CK_IntegralToPointer: 13253 case CK_ToVoid: 13254 case CK_VectorSplat: 13255 case CK_IntegralToFloating: 13256 case CK_FloatingCast: 13257 case CK_CPointerToObjCPointerCast: 13258 case CK_BlockPointerToObjCPointerCast: 13259 case CK_AnyPointerToBlockPointerCast: 13260 case CK_ObjCObjectLValueCast: 13261 case CK_FloatingRealToComplex: 13262 case CK_FloatingComplexToReal: 13263 case CK_FloatingComplexCast: 13264 case CK_FloatingComplexToIntegralComplex: 13265 case CK_IntegralRealToComplex: 13266 case CK_IntegralComplexCast: 13267 case CK_IntegralComplexToFloatingComplex: 13268 case CK_BuiltinFnToFnPtr: 13269 case CK_ZeroToOCLOpaqueType: 13270 case CK_NonAtomicToAtomic: 13271 case CK_AddressSpaceConversion: 13272 case CK_IntToOCLSampler: 13273 case CK_FloatingToFixedPoint: 13274 case CK_FixedPointToFloating: 13275 case CK_FixedPointCast: 13276 case CK_IntegralToFixedPoint: 13277 case CK_MatrixCast: 13278 llvm_unreachable("invalid cast kind for integral value"); 13279 13280 case CK_BitCast: 13281 case CK_Dependent: 13282 case CK_LValueBitCast: 13283 case CK_ARCProduceObject: 13284 case CK_ARCConsumeObject: 13285 case CK_ARCReclaimReturnedObject: 13286 case CK_ARCExtendBlockObject: 13287 case CK_CopyAndAutoreleaseBlockObject: 13288 return Error(E); 13289 13290 case CK_UserDefinedConversion: 13291 case CK_LValueToRValue: 13292 case CK_AtomicToNonAtomic: 13293 case CK_NoOp: 13294 case CK_LValueToRValueBitCast: 13295 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13296 13297 case CK_MemberPointerToBoolean: 13298 case CK_PointerToBoolean: 13299 case CK_IntegralToBoolean: 13300 case CK_FloatingToBoolean: 13301 case CK_BooleanToSignedIntegral: 13302 case CK_FloatingComplexToBoolean: 13303 case CK_IntegralComplexToBoolean: { 13304 bool BoolResult; 13305 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13306 return false; 13307 uint64_t IntResult = BoolResult; 13308 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13309 IntResult = (uint64_t)-1; 13310 return Success(IntResult, E); 13311 } 13312 13313 case CK_FixedPointToIntegral: { 13314 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13315 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13316 return false; 13317 bool Overflowed; 13318 llvm::APSInt Result = Src.convertToInt( 13319 Info.Ctx.getIntWidth(DestType), 13320 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13321 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13322 return false; 13323 return Success(Result, E); 13324 } 13325 13326 case CK_FixedPointToBoolean: { 13327 // Unsigned padding does not affect this. 13328 APValue Val; 13329 if (!Evaluate(Val, Info, SubExpr)) 13330 return false; 13331 return Success(Val.getFixedPoint().getBoolValue(), E); 13332 } 13333 13334 case CK_IntegralCast: { 13335 if (!Visit(SubExpr)) 13336 return false; 13337 13338 if (!Result.isInt()) { 13339 // Allow casts of address-of-label differences if they are no-ops 13340 // or narrowing. (The narrowing case isn't actually guaranteed to 13341 // be constant-evaluatable except in some narrow cases which are hard 13342 // to detect here. We let it through on the assumption the user knows 13343 // what they are doing.) 13344 if (Result.isAddrLabelDiff()) 13345 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13346 // Only allow casts of lvalues if they are lossless. 13347 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13348 } 13349 13350 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13351 Result.getInt()), E); 13352 } 13353 13354 case CK_PointerToIntegral: { 13355 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13356 13357 LValue LV; 13358 if (!EvaluatePointer(SubExpr, LV, Info)) 13359 return false; 13360 13361 if (LV.getLValueBase()) { 13362 // Only allow based lvalue casts if they are lossless. 13363 // FIXME: Allow a larger integer size than the pointer size, and allow 13364 // narrowing back down to pointer width in subsequent integral casts. 13365 // FIXME: Check integer type's active bits, not its type size. 13366 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13367 return Error(E); 13368 13369 LV.Designator.setInvalid(); 13370 LV.moveInto(Result); 13371 return true; 13372 } 13373 13374 APSInt AsInt; 13375 APValue V; 13376 LV.moveInto(V); 13377 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13378 llvm_unreachable("Can't cast this!"); 13379 13380 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13381 } 13382 13383 case CK_IntegralComplexToReal: { 13384 ComplexValue C; 13385 if (!EvaluateComplex(SubExpr, C, Info)) 13386 return false; 13387 return Success(C.getComplexIntReal(), E); 13388 } 13389 13390 case CK_FloatingToIntegral: { 13391 APFloat F(0.0); 13392 if (!EvaluateFloat(SubExpr, F, Info)) 13393 return false; 13394 13395 APSInt Value; 13396 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13397 return false; 13398 return Success(Value, E); 13399 } 13400 } 13401 13402 llvm_unreachable("unknown cast resulting in integral value"); 13403 } 13404 13405 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13406 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13407 ComplexValue LV; 13408 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13409 return false; 13410 if (!LV.isComplexInt()) 13411 return Error(E); 13412 return Success(LV.getComplexIntReal(), E); 13413 } 13414 13415 return Visit(E->getSubExpr()); 13416 } 13417 13418 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13419 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13420 ComplexValue LV; 13421 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13422 return false; 13423 if (!LV.isComplexInt()) 13424 return Error(E); 13425 return Success(LV.getComplexIntImag(), E); 13426 } 13427 13428 VisitIgnoredValue(E->getSubExpr()); 13429 return Success(0, E); 13430 } 13431 13432 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13433 return Success(E->getPackLength(), E); 13434 } 13435 13436 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13437 return Success(E->getValue(), E); 13438 } 13439 13440 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13441 const ConceptSpecializationExpr *E) { 13442 return Success(E->isSatisfied(), E); 13443 } 13444 13445 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13446 return Success(E->isSatisfied(), E); 13447 } 13448 13449 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13450 switch (E->getOpcode()) { 13451 default: 13452 // Invalid unary operators 13453 return Error(E); 13454 case UO_Plus: 13455 // The result is just the value. 13456 return Visit(E->getSubExpr()); 13457 case UO_Minus: { 13458 if (!Visit(E->getSubExpr())) return false; 13459 if (!Result.isFixedPoint()) 13460 return Error(E); 13461 bool Overflowed; 13462 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13463 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13464 return false; 13465 return Success(Negated, E); 13466 } 13467 case UO_LNot: { 13468 bool bres; 13469 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13470 return false; 13471 return Success(!bres, E); 13472 } 13473 } 13474 } 13475 13476 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13477 const Expr *SubExpr = E->getSubExpr(); 13478 QualType DestType = E->getType(); 13479 assert(DestType->isFixedPointType() && 13480 "Expected destination type to be a fixed point type"); 13481 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13482 13483 switch (E->getCastKind()) { 13484 case CK_FixedPointCast: { 13485 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13486 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13487 return false; 13488 bool Overflowed; 13489 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13490 if (Overflowed) { 13491 if (Info.checkingForUndefinedBehavior()) 13492 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13493 diag::warn_fixedpoint_constant_overflow) 13494 << Result.toString() << E->getType(); 13495 if (!HandleOverflow(Info, E, Result, E->getType())) 13496 return false; 13497 } 13498 return Success(Result, E); 13499 } 13500 case CK_IntegralToFixedPoint: { 13501 APSInt Src; 13502 if (!EvaluateInteger(SubExpr, Src, Info)) 13503 return false; 13504 13505 bool Overflowed; 13506 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13507 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13508 13509 if (Overflowed) { 13510 if (Info.checkingForUndefinedBehavior()) 13511 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13512 diag::warn_fixedpoint_constant_overflow) 13513 << IntResult.toString() << E->getType(); 13514 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13515 return false; 13516 } 13517 13518 return Success(IntResult, E); 13519 } 13520 case CK_FloatingToFixedPoint: { 13521 APFloat Src(0.0); 13522 if (!EvaluateFloat(SubExpr, Src, Info)) 13523 return false; 13524 13525 bool Overflowed; 13526 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13527 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13528 13529 if (Overflowed) { 13530 if (Info.checkingForUndefinedBehavior()) 13531 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13532 diag::warn_fixedpoint_constant_overflow) 13533 << Result.toString() << E->getType(); 13534 if (!HandleOverflow(Info, E, Result, E->getType())) 13535 return false; 13536 } 13537 13538 return Success(Result, E); 13539 } 13540 case CK_NoOp: 13541 case CK_LValueToRValue: 13542 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13543 default: 13544 return Error(E); 13545 } 13546 } 13547 13548 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13549 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13550 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13551 13552 const Expr *LHS = E->getLHS(); 13553 const Expr *RHS = E->getRHS(); 13554 FixedPointSemantics ResultFXSema = 13555 Info.Ctx.getFixedPointSemantics(E->getType()); 13556 13557 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13558 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13559 return false; 13560 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13561 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13562 return false; 13563 13564 bool OpOverflow = false, ConversionOverflow = false; 13565 APFixedPoint Result(LHSFX.getSemantics()); 13566 switch (E->getOpcode()) { 13567 case BO_Add: { 13568 Result = LHSFX.add(RHSFX, &OpOverflow) 13569 .convert(ResultFXSema, &ConversionOverflow); 13570 break; 13571 } 13572 case BO_Sub: { 13573 Result = LHSFX.sub(RHSFX, &OpOverflow) 13574 .convert(ResultFXSema, &ConversionOverflow); 13575 break; 13576 } 13577 case BO_Mul: { 13578 Result = LHSFX.mul(RHSFX, &OpOverflow) 13579 .convert(ResultFXSema, &ConversionOverflow); 13580 break; 13581 } 13582 case BO_Div: { 13583 if (RHSFX.getValue() == 0) { 13584 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13585 return false; 13586 } 13587 Result = LHSFX.div(RHSFX, &OpOverflow) 13588 .convert(ResultFXSema, &ConversionOverflow); 13589 break; 13590 } 13591 case BO_Shl: 13592 case BO_Shr: { 13593 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13594 llvm::APSInt RHSVal = RHSFX.getValue(); 13595 13596 unsigned ShiftBW = 13597 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13598 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13599 // Embedded-C 4.1.6.2.2: 13600 // The right operand must be nonnegative and less than the total number 13601 // of (nonpadding) bits of the fixed-point operand ... 13602 if (RHSVal.isNegative()) 13603 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13604 else if (Amt != RHSVal) 13605 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13606 << RHSVal << E->getType() << ShiftBW; 13607 13608 if (E->getOpcode() == BO_Shl) 13609 Result = LHSFX.shl(Amt, &OpOverflow); 13610 else 13611 Result = LHSFX.shr(Amt, &OpOverflow); 13612 break; 13613 } 13614 default: 13615 return false; 13616 } 13617 if (OpOverflow || ConversionOverflow) { 13618 if (Info.checkingForUndefinedBehavior()) 13619 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13620 diag::warn_fixedpoint_constant_overflow) 13621 << Result.toString() << E->getType(); 13622 if (!HandleOverflow(Info, E, Result, E->getType())) 13623 return false; 13624 } 13625 return Success(Result, E); 13626 } 13627 13628 //===----------------------------------------------------------------------===// 13629 // Float Evaluation 13630 //===----------------------------------------------------------------------===// 13631 13632 namespace { 13633 class FloatExprEvaluator 13634 : public ExprEvaluatorBase<FloatExprEvaluator> { 13635 APFloat &Result; 13636 public: 13637 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13638 : ExprEvaluatorBaseTy(info), Result(result) {} 13639 13640 bool Success(const APValue &V, const Expr *e) { 13641 Result = V.getFloat(); 13642 return true; 13643 } 13644 13645 bool ZeroInitialization(const Expr *E) { 13646 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13647 return true; 13648 } 13649 13650 bool VisitCallExpr(const CallExpr *E); 13651 13652 bool VisitUnaryOperator(const UnaryOperator *E); 13653 bool VisitBinaryOperator(const BinaryOperator *E); 13654 bool VisitFloatingLiteral(const FloatingLiteral *E); 13655 bool VisitCastExpr(const CastExpr *E); 13656 13657 bool VisitUnaryReal(const UnaryOperator *E); 13658 bool VisitUnaryImag(const UnaryOperator *E); 13659 13660 // FIXME: Missing: array subscript of vector, member of vector 13661 }; 13662 } // end anonymous namespace 13663 13664 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13665 assert(!E->isValueDependent()); 13666 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13667 return FloatExprEvaluator(Info, Result).Visit(E); 13668 } 13669 13670 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13671 QualType ResultTy, 13672 const Expr *Arg, 13673 bool SNaN, 13674 llvm::APFloat &Result) { 13675 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13676 if (!S) return false; 13677 13678 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13679 13680 llvm::APInt fill; 13681 13682 // Treat empty strings as if they were zero. 13683 if (S->getString().empty()) 13684 fill = llvm::APInt(32, 0); 13685 else if (S->getString().getAsInteger(0, fill)) 13686 return false; 13687 13688 if (Context.getTargetInfo().isNan2008()) { 13689 if (SNaN) 13690 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13691 else 13692 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13693 } else { 13694 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13695 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13696 // a different encoding to what became a standard in 2008, and for pre- 13697 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13698 // sNaN. This is now known as "legacy NaN" encoding. 13699 if (SNaN) 13700 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13701 else 13702 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13703 } 13704 13705 return true; 13706 } 13707 13708 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13709 switch (E->getBuiltinCallee()) { 13710 default: 13711 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13712 13713 case Builtin::BI__builtin_huge_val: 13714 case Builtin::BI__builtin_huge_valf: 13715 case Builtin::BI__builtin_huge_vall: 13716 case Builtin::BI__builtin_huge_valf128: 13717 case Builtin::BI__builtin_inf: 13718 case Builtin::BI__builtin_inff: 13719 case Builtin::BI__builtin_infl: 13720 case Builtin::BI__builtin_inff128: { 13721 const llvm::fltSemantics &Sem = 13722 Info.Ctx.getFloatTypeSemantics(E->getType()); 13723 Result = llvm::APFloat::getInf(Sem); 13724 return true; 13725 } 13726 13727 case Builtin::BI__builtin_nans: 13728 case Builtin::BI__builtin_nansf: 13729 case Builtin::BI__builtin_nansl: 13730 case Builtin::BI__builtin_nansf128: 13731 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13732 true, Result)) 13733 return Error(E); 13734 return true; 13735 13736 case Builtin::BI__builtin_nan: 13737 case Builtin::BI__builtin_nanf: 13738 case Builtin::BI__builtin_nanl: 13739 case Builtin::BI__builtin_nanf128: 13740 // If this is __builtin_nan() turn this into a nan, otherwise we 13741 // can't constant fold it. 13742 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13743 false, Result)) 13744 return Error(E); 13745 return true; 13746 13747 case Builtin::BI__builtin_fabs: 13748 case Builtin::BI__builtin_fabsf: 13749 case Builtin::BI__builtin_fabsl: 13750 case Builtin::BI__builtin_fabsf128: 13751 // The C standard says "fabs raises no floating-point exceptions, 13752 // even if x is a signaling NaN. The returned value is independent of 13753 // the current rounding direction mode." Therefore constant folding can 13754 // proceed without regard to the floating point settings. 13755 // Reference, WG14 N2478 F.10.4.3 13756 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13757 return false; 13758 13759 if (Result.isNegative()) 13760 Result.changeSign(); 13761 return true; 13762 13763 case Builtin::BI__arithmetic_fence: 13764 return EvaluateFloat(E->getArg(0), Result, Info); 13765 13766 // FIXME: Builtin::BI__builtin_powi 13767 // FIXME: Builtin::BI__builtin_powif 13768 // FIXME: Builtin::BI__builtin_powil 13769 13770 case Builtin::BI__builtin_copysign: 13771 case Builtin::BI__builtin_copysignf: 13772 case Builtin::BI__builtin_copysignl: 13773 case Builtin::BI__builtin_copysignf128: { 13774 APFloat RHS(0.); 13775 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13776 !EvaluateFloat(E->getArg(1), RHS, Info)) 13777 return false; 13778 Result.copySign(RHS); 13779 return true; 13780 } 13781 } 13782 } 13783 13784 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13785 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13786 ComplexValue CV; 13787 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13788 return false; 13789 Result = CV.FloatReal; 13790 return true; 13791 } 13792 13793 return Visit(E->getSubExpr()); 13794 } 13795 13796 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13797 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13798 ComplexValue CV; 13799 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13800 return false; 13801 Result = CV.FloatImag; 13802 return true; 13803 } 13804 13805 VisitIgnoredValue(E->getSubExpr()); 13806 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13807 Result = llvm::APFloat::getZero(Sem); 13808 return true; 13809 } 13810 13811 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13812 switch (E->getOpcode()) { 13813 default: return Error(E); 13814 case UO_Plus: 13815 return EvaluateFloat(E->getSubExpr(), Result, Info); 13816 case UO_Minus: 13817 // In C standard, WG14 N2478 F.3 p4 13818 // "the unary - raises no floating point exceptions, 13819 // even if the operand is signalling." 13820 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13821 return false; 13822 Result.changeSign(); 13823 return true; 13824 } 13825 } 13826 13827 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13828 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13829 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13830 13831 APFloat RHS(0.0); 13832 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13833 if (!LHSOK && !Info.noteFailure()) 13834 return false; 13835 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13836 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13837 } 13838 13839 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13840 Result = E->getValue(); 13841 return true; 13842 } 13843 13844 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13845 const Expr* SubExpr = E->getSubExpr(); 13846 13847 switch (E->getCastKind()) { 13848 default: 13849 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13850 13851 case CK_IntegralToFloating: { 13852 APSInt IntResult; 13853 const FPOptions FPO = E->getFPFeaturesInEffect( 13854 Info.Ctx.getLangOpts()); 13855 return EvaluateInteger(SubExpr, IntResult, Info) && 13856 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13857 IntResult, E->getType(), Result); 13858 } 13859 13860 case CK_FixedPointToFloating: { 13861 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13862 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13863 return false; 13864 Result = 13865 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13866 return true; 13867 } 13868 13869 case CK_FloatingCast: { 13870 if (!Visit(SubExpr)) 13871 return false; 13872 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13873 Result); 13874 } 13875 13876 case CK_FloatingComplexToReal: { 13877 ComplexValue V; 13878 if (!EvaluateComplex(SubExpr, V, Info)) 13879 return false; 13880 Result = V.getComplexFloatReal(); 13881 return true; 13882 } 13883 } 13884 } 13885 13886 //===----------------------------------------------------------------------===// 13887 // Complex Evaluation (for float and integer) 13888 //===----------------------------------------------------------------------===// 13889 13890 namespace { 13891 class ComplexExprEvaluator 13892 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13893 ComplexValue &Result; 13894 13895 public: 13896 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13897 : ExprEvaluatorBaseTy(info), Result(Result) {} 13898 13899 bool Success(const APValue &V, const Expr *e) { 13900 Result.setFrom(V); 13901 return true; 13902 } 13903 13904 bool ZeroInitialization(const Expr *E); 13905 13906 //===--------------------------------------------------------------------===// 13907 // Visitor Methods 13908 //===--------------------------------------------------------------------===// 13909 13910 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13911 bool VisitCastExpr(const CastExpr *E); 13912 bool VisitBinaryOperator(const BinaryOperator *E); 13913 bool VisitUnaryOperator(const UnaryOperator *E); 13914 bool VisitInitListExpr(const InitListExpr *E); 13915 bool VisitCallExpr(const CallExpr *E); 13916 }; 13917 } // end anonymous namespace 13918 13919 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13920 EvalInfo &Info) { 13921 assert(!E->isValueDependent()); 13922 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 13923 return ComplexExprEvaluator(Info, Result).Visit(E); 13924 } 13925 13926 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13927 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13928 if (ElemTy->isRealFloatingType()) { 13929 Result.makeComplexFloat(); 13930 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13931 Result.FloatReal = Zero; 13932 Result.FloatImag = Zero; 13933 } else { 13934 Result.makeComplexInt(); 13935 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13936 Result.IntReal = Zero; 13937 Result.IntImag = Zero; 13938 } 13939 return true; 13940 } 13941 13942 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13943 const Expr* SubExpr = E->getSubExpr(); 13944 13945 if (SubExpr->getType()->isRealFloatingType()) { 13946 Result.makeComplexFloat(); 13947 APFloat &Imag = Result.FloatImag; 13948 if (!EvaluateFloat(SubExpr, Imag, Info)) 13949 return false; 13950 13951 Result.FloatReal = APFloat(Imag.getSemantics()); 13952 return true; 13953 } else { 13954 assert(SubExpr->getType()->isIntegerType() && 13955 "Unexpected imaginary literal."); 13956 13957 Result.makeComplexInt(); 13958 APSInt &Imag = Result.IntImag; 13959 if (!EvaluateInteger(SubExpr, Imag, Info)) 13960 return false; 13961 13962 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13963 return true; 13964 } 13965 } 13966 13967 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13968 13969 switch (E->getCastKind()) { 13970 case CK_BitCast: 13971 case CK_BaseToDerived: 13972 case CK_DerivedToBase: 13973 case CK_UncheckedDerivedToBase: 13974 case CK_Dynamic: 13975 case CK_ToUnion: 13976 case CK_ArrayToPointerDecay: 13977 case CK_FunctionToPointerDecay: 13978 case CK_NullToPointer: 13979 case CK_NullToMemberPointer: 13980 case CK_BaseToDerivedMemberPointer: 13981 case CK_DerivedToBaseMemberPointer: 13982 case CK_MemberPointerToBoolean: 13983 case CK_ReinterpretMemberPointer: 13984 case CK_ConstructorConversion: 13985 case CK_IntegralToPointer: 13986 case CK_PointerToIntegral: 13987 case CK_PointerToBoolean: 13988 case CK_ToVoid: 13989 case CK_VectorSplat: 13990 case CK_IntegralCast: 13991 case CK_BooleanToSignedIntegral: 13992 case CK_IntegralToBoolean: 13993 case CK_IntegralToFloating: 13994 case CK_FloatingToIntegral: 13995 case CK_FloatingToBoolean: 13996 case CK_FloatingCast: 13997 case CK_CPointerToObjCPointerCast: 13998 case CK_BlockPointerToObjCPointerCast: 13999 case CK_AnyPointerToBlockPointerCast: 14000 case CK_ObjCObjectLValueCast: 14001 case CK_FloatingComplexToReal: 14002 case CK_FloatingComplexToBoolean: 14003 case CK_IntegralComplexToReal: 14004 case CK_IntegralComplexToBoolean: 14005 case CK_ARCProduceObject: 14006 case CK_ARCConsumeObject: 14007 case CK_ARCReclaimReturnedObject: 14008 case CK_ARCExtendBlockObject: 14009 case CK_CopyAndAutoreleaseBlockObject: 14010 case CK_BuiltinFnToFnPtr: 14011 case CK_ZeroToOCLOpaqueType: 14012 case CK_NonAtomicToAtomic: 14013 case CK_AddressSpaceConversion: 14014 case CK_IntToOCLSampler: 14015 case CK_FloatingToFixedPoint: 14016 case CK_FixedPointToFloating: 14017 case CK_FixedPointCast: 14018 case CK_FixedPointToBoolean: 14019 case CK_FixedPointToIntegral: 14020 case CK_IntegralToFixedPoint: 14021 case CK_MatrixCast: 14022 llvm_unreachable("invalid cast kind for complex value"); 14023 14024 case CK_LValueToRValue: 14025 case CK_AtomicToNonAtomic: 14026 case CK_NoOp: 14027 case CK_LValueToRValueBitCast: 14028 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14029 14030 case CK_Dependent: 14031 case CK_LValueBitCast: 14032 case CK_UserDefinedConversion: 14033 return Error(E); 14034 14035 case CK_FloatingRealToComplex: { 14036 APFloat &Real = Result.FloatReal; 14037 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14038 return false; 14039 14040 Result.makeComplexFloat(); 14041 Result.FloatImag = APFloat(Real.getSemantics()); 14042 return true; 14043 } 14044 14045 case CK_FloatingComplexCast: { 14046 if (!Visit(E->getSubExpr())) 14047 return false; 14048 14049 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14050 QualType From 14051 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14052 14053 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14054 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14055 } 14056 14057 case CK_FloatingComplexToIntegralComplex: { 14058 if (!Visit(E->getSubExpr())) 14059 return false; 14060 14061 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14062 QualType From 14063 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14064 Result.makeComplexInt(); 14065 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14066 To, Result.IntReal) && 14067 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14068 To, Result.IntImag); 14069 } 14070 14071 case CK_IntegralRealToComplex: { 14072 APSInt &Real = Result.IntReal; 14073 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14074 return false; 14075 14076 Result.makeComplexInt(); 14077 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14078 return true; 14079 } 14080 14081 case CK_IntegralComplexCast: { 14082 if (!Visit(E->getSubExpr())) 14083 return false; 14084 14085 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14086 QualType From 14087 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14088 14089 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14090 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14091 return true; 14092 } 14093 14094 case CK_IntegralComplexToFloatingComplex: { 14095 if (!Visit(E->getSubExpr())) 14096 return false; 14097 14098 const FPOptions FPO = E->getFPFeaturesInEffect( 14099 Info.Ctx.getLangOpts()); 14100 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14101 QualType From 14102 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14103 Result.makeComplexFloat(); 14104 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14105 To, Result.FloatReal) && 14106 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14107 To, Result.FloatImag); 14108 } 14109 } 14110 14111 llvm_unreachable("unknown cast resulting in complex value"); 14112 } 14113 14114 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14115 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14116 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14117 14118 // Track whether the LHS or RHS is real at the type system level. When this is 14119 // the case we can simplify our evaluation strategy. 14120 bool LHSReal = false, RHSReal = false; 14121 14122 bool LHSOK; 14123 if (E->getLHS()->getType()->isRealFloatingType()) { 14124 LHSReal = true; 14125 APFloat &Real = Result.FloatReal; 14126 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14127 if (LHSOK) { 14128 Result.makeComplexFloat(); 14129 Result.FloatImag = APFloat(Real.getSemantics()); 14130 } 14131 } else { 14132 LHSOK = Visit(E->getLHS()); 14133 } 14134 if (!LHSOK && !Info.noteFailure()) 14135 return false; 14136 14137 ComplexValue RHS; 14138 if (E->getRHS()->getType()->isRealFloatingType()) { 14139 RHSReal = true; 14140 APFloat &Real = RHS.FloatReal; 14141 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14142 return false; 14143 RHS.makeComplexFloat(); 14144 RHS.FloatImag = APFloat(Real.getSemantics()); 14145 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14146 return false; 14147 14148 assert(!(LHSReal && RHSReal) && 14149 "Cannot have both operands of a complex operation be real."); 14150 switch (E->getOpcode()) { 14151 default: return Error(E); 14152 case BO_Add: 14153 if (Result.isComplexFloat()) { 14154 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14155 APFloat::rmNearestTiesToEven); 14156 if (LHSReal) 14157 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14158 else if (!RHSReal) 14159 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14160 APFloat::rmNearestTiesToEven); 14161 } else { 14162 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14163 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14164 } 14165 break; 14166 case BO_Sub: 14167 if (Result.isComplexFloat()) { 14168 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14169 APFloat::rmNearestTiesToEven); 14170 if (LHSReal) { 14171 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14172 Result.getComplexFloatImag().changeSign(); 14173 } else if (!RHSReal) { 14174 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14175 APFloat::rmNearestTiesToEven); 14176 } 14177 } else { 14178 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14179 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14180 } 14181 break; 14182 case BO_Mul: 14183 if (Result.isComplexFloat()) { 14184 // This is an implementation of complex multiplication according to the 14185 // constraints laid out in C11 Annex G. The implementation uses the 14186 // following naming scheme: 14187 // (a + ib) * (c + id) 14188 ComplexValue LHS = Result; 14189 APFloat &A = LHS.getComplexFloatReal(); 14190 APFloat &B = LHS.getComplexFloatImag(); 14191 APFloat &C = RHS.getComplexFloatReal(); 14192 APFloat &D = RHS.getComplexFloatImag(); 14193 APFloat &ResR = Result.getComplexFloatReal(); 14194 APFloat &ResI = Result.getComplexFloatImag(); 14195 if (LHSReal) { 14196 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14197 ResR = A * C; 14198 ResI = A * D; 14199 } else if (RHSReal) { 14200 ResR = C * A; 14201 ResI = C * B; 14202 } else { 14203 // In the fully general case, we need to handle NaNs and infinities 14204 // robustly. 14205 APFloat AC = A * C; 14206 APFloat BD = B * D; 14207 APFloat AD = A * D; 14208 APFloat BC = B * C; 14209 ResR = AC - BD; 14210 ResI = AD + BC; 14211 if (ResR.isNaN() && ResI.isNaN()) { 14212 bool Recalc = false; 14213 if (A.isInfinity() || B.isInfinity()) { 14214 A = APFloat::copySign( 14215 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14216 B = APFloat::copySign( 14217 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14218 if (C.isNaN()) 14219 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14220 if (D.isNaN()) 14221 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14222 Recalc = true; 14223 } 14224 if (C.isInfinity() || D.isInfinity()) { 14225 C = APFloat::copySign( 14226 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14227 D = APFloat::copySign( 14228 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14229 if (A.isNaN()) 14230 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14231 if (B.isNaN()) 14232 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14233 Recalc = true; 14234 } 14235 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14236 AD.isInfinity() || BC.isInfinity())) { 14237 if (A.isNaN()) 14238 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14239 if (B.isNaN()) 14240 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14241 if (C.isNaN()) 14242 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14243 if (D.isNaN()) 14244 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14245 Recalc = true; 14246 } 14247 if (Recalc) { 14248 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14249 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14250 } 14251 } 14252 } 14253 } else { 14254 ComplexValue LHS = Result; 14255 Result.getComplexIntReal() = 14256 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14257 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14258 Result.getComplexIntImag() = 14259 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14260 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14261 } 14262 break; 14263 case BO_Div: 14264 if (Result.isComplexFloat()) { 14265 // This is an implementation of complex division according to the 14266 // constraints laid out in C11 Annex G. The implementation uses the 14267 // following naming scheme: 14268 // (a + ib) / (c + id) 14269 ComplexValue LHS = Result; 14270 APFloat &A = LHS.getComplexFloatReal(); 14271 APFloat &B = LHS.getComplexFloatImag(); 14272 APFloat &C = RHS.getComplexFloatReal(); 14273 APFloat &D = RHS.getComplexFloatImag(); 14274 APFloat &ResR = Result.getComplexFloatReal(); 14275 APFloat &ResI = Result.getComplexFloatImag(); 14276 if (RHSReal) { 14277 ResR = A / C; 14278 ResI = B / C; 14279 } else { 14280 if (LHSReal) { 14281 // No real optimizations we can do here, stub out with zero. 14282 B = APFloat::getZero(A.getSemantics()); 14283 } 14284 int DenomLogB = 0; 14285 APFloat MaxCD = maxnum(abs(C), abs(D)); 14286 if (MaxCD.isFinite()) { 14287 DenomLogB = ilogb(MaxCD); 14288 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14289 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14290 } 14291 APFloat Denom = C * C + D * D; 14292 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14293 APFloat::rmNearestTiesToEven); 14294 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14295 APFloat::rmNearestTiesToEven); 14296 if (ResR.isNaN() && ResI.isNaN()) { 14297 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14298 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14299 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14300 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14301 D.isFinite()) { 14302 A = APFloat::copySign( 14303 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14304 B = APFloat::copySign( 14305 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14306 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14307 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14308 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14309 C = APFloat::copySign( 14310 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14311 D = APFloat::copySign( 14312 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14313 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14314 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14315 } 14316 } 14317 } 14318 } else { 14319 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14320 return Error(E, diag::note_expr_divide_by_zero); 14321 14322 ComplexValue LHS = Result; 14323 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14324 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14325 Result.getComplexIntReal() = 14326 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14327 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14328 Result.getComplexIntImag() = 14329 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14330 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14331 } 14332 break; 14333 } 14334 14335 return true; 14336 } 14337 14338 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14339 // Get the operand value into 'Result'. 14340 if (!Visit(E->getSubExpr())) 14341 return false; 14342 14343 switch (E->getOpcode()) { 14344 default: 14345 return Error(E); 14346 case UO_Extension: 14347 return true; 14348 case UO_Plus: 14349 // The result is always just the subexpr. 14350 return true; 14351 case UO_Minus: 14352 if (Result.isComplexFloat()) { 14353 Result.getComplexFloatReal().changeSign(); 14354 Result.getComplexFloatImag().changeSign(); 14355 } 14356 else { 14357 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14358 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14359 } 14360 return true; 14361 case UO_Not: 14362 if (Result.isComplexFloat()) 14363 Result.getComplexFloatImag().changeSign(); 14364 else 14365 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14366 return true; 14367 } 14368 } 14369 14370 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14371 if (E->getNumInits() == 2) { 14372 if (E->getType()->isComplexType()) { 14373 Result.makeComplexFloat(); 14374 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14375 return false; 14376 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14377 return false; 14378 } else { 14379 Result.makeComplexInt(); 14380 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14381 return false; 14382 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14383 return false; 14384 } 14385 return true; 14386 } 14387 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14388 } 14389 14390 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14391 switch (E->getBuiltinCallee()) { 14392 case Builtin::BI__builtin_complex: 14393 Result.makeComplexFloat(); 14394 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14395 return false; 14396 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14397 return false; 14398 return true; 14399 14400 default: 14401 break; 14402 } 14403 14404 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14405 } 14406 14407 //===----------------------------------------------------------------------===// 14408 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14409 // implicit conversion. 14410 //===----------------------------------------------------------------------===// 14411 14412 namespace { 14413 class AtomicExprEvaluator : 14414 public ExprEvaluatorBase<AtomicExprEvaluator> { 14415 const LValue *This; 14416 APValue &Result; 14417 public: 14418 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14419 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14420 14421 bool Success(const APValue &V, const Expr *E) { 14422 Result = V; 14423 return true; 14424 } 14425 14426 bool ZeroInitialization(const Expr *E) { 14427 ImplicitValueInitExpr VIE( 14428 E->getType()->castAs<AtomicType>()->getValueType()); 14429 // For atomic-qualified class (and array) types in C++, initialize the 14430 // _Atomic-wrapped subobject directly, in-place. 14431 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14432 : Evaluate(Result, Info, &VIE); 14433 } 14434 14435 bool VisitCastExpr(const CastExpr *E) { 14436 switch (E->getCastKind()) { 14437 default: 14438 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14439 case CK_NonAtomicToAtomic: 14440 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14441 : Evaluate(Result, Info, E->getSubExpr()); 14442 } 14443 } 14444 }; 14445 } // end anonymous namespace 14446 14447 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14448 EvalInfo &Info) { 14449 assert(!E->isValueDependent()); 14450 assert(E->isPRValue() && E->getType()->isAtomicType()); 14451 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14452 } 14453 14454 //===----------------------------------------------------------------------===// 14455 // Void expression evaluation, primarily for a cast to void on the LHS of a 14456 // comma operator 14457 //===----------------------------------------------------------------------===// 14458 14459 namespace { 14460 class VoidExprEvaluator 14461 : public ExprEvaluatorBase<VoidExprEvaluator> { 14462 public: 14463 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14464 14465 bool Success(const APValue &V, const Expr *e) { return true; } 14466 14467 bool ZeroInitialization(const Expr *E) { return true; } 14468 14469 bool VisitCastExpr(const CastExpr *E) { 14470 switch (E->getCastKind()) { 14471 default: 14472 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14473 case CK_ToVoid: 14474 VisitIgnoredValue(E->getSubExpr()); 14475 return true; 14476 } 14477 } 14478 14479 bool VisitCallExpr(const CallExpr *E) { 14480 switch (E->getBuiltinCallee()) { 14481 case Builtin::BI__assume: 14482 case Builtin::BI__builtin_assume: 14483 // The argument is not evaluated! 14484 return true; 14485 14486 case Builtin::BI__builtin_operator_delete: 14487 return HandleOperatorDeleteCall(Info, E); 14488 14489 default: 14490 break; 14491 } 14492 14493 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14494 } 14495 14496 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14497 }; 14498 } // end anonymous namespace 14499 14500 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14501 // We cannot speculatively evaluate a delete expression. 14502 if (Info.SpeculativeEvaluationDepth) 14503 return false; 14504 14505 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14506 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14507 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14508 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14509 return false; 14510 } 14511 14512 const Expr *Arg = E->getArgument(); 14513 14514 LValue Pointer; 14515 if (!EvaluatePointer(Arg, Pointer, Info)) 14516 return false; 14517 if (Pointer.Designator.Invalid) 14518 return false; 14519 14520 // Deleting a null pointer has no effect. 14521 if (Pointer.isNullPointer()) { 14522 // This is the only case where we need to produce an extension warning: 14523 // the only other way we can succeed is if we find a dynamic allocation, 14524 // and we will have warned when we allocated it in that case. 14525 if (!Info.getLangOpts().CPlusPlus20) 14526 Info.CCEDiag(E, diag::note_constexpr_new); 14527 return true; 14528 } 14529 14530 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14531 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14532 if (!Alloc) 14533 return false; 14534 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14535 14536 // For the non-array case, the designator must be empty if the static type 14537 // does not have a virtual destructor. 14538 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14539 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14540 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14541 << Arg->getType()->getPointeeType() << AllocType; 14542 return false; 14543 } 14544 14545 // For a class type with a virtual destructor, the selected operator delete 14546 // is the one looked up when building the destructor. 14547 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14548 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14549 if (VirtualDelete && 14550 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14551 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14552 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14553 return false; 14554 } 14555 } 14556 14557 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14558 (*Alloc)->Value, AllocType)) 14559 return false; 14560 14561 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14562 // The element was already erased. This means the destructor call also 14563 // deleted the object. 14564 // FIXME: This probably results in undefined behavior before we get this 14565 // far, and should be diagnosed elsewhere first. 14566 Info.FFDiag(E, diag::note_constexpr_double_delete); 14567 return false; 14568 } 14569 14570 return true; 14571 } 14572 14573 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14574 assert(!E->isValueDependent()); 14575 assert(E->isPRValue() && E->getType()->isVoidType()); 14576 return VoidExprEvaluator(Info).Visit(E); 14577 } 14578 14579 //===----------------------------------------------------------------------===// 14580 // Top level Expr::EvaluateAsRValue method. 14581 //===----------------------------------------------------------------------===// 14582 14583 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14584 assert(!E->isValueDependent()); 14585 // In C, function designators are not lvalues, but we evaluate them as if they 14586 // are. 14587 QualType T = E->getType(); 14588 if (E->isGLValue() || T->isFunctionType()) { 14589 LValue LV; 14590 if (!EvaluateLValue(E, LV, Info)) 14591 return false; 14592 LV.moveInto(Result); 14593 } else if (T->isVectorType()) { 14594 if (!EvaluateVector(E, Result, Info)) 14595 return false; 14596 } else if (T->isIntegralOrEnumerationType()) { 14597 if (!IntExprEvaluator(Info, Result).Visit(E)) 14598 return false; 14599 } else if (T->hasPointerRepresentation()) { 14600 LValue LV; 14601 if (!EvaluatePointer(E, LV, Info)) 14602 return false; 14603 LV.moveInto(Result); 14604 } else if (T->isRealFloatingType()) { 14605 llvm::APFloat F(0.0); 14606 if (!EvaluateFloat(E, F, Info)) 14607 return false; 14608 Result = APValue(F); 14609 } else if (T->isAnyComplexType()) { 14610 ComplexValue C; 14611 if (!EvaluateComplex(E, C, Info)) 14612 return false; 14613 C.moveInto(Result); 14614 } else if (T->isFixedPointType()) { 14615 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14616 } else if (T->isMemberPointerType()) { 14617 MemberPtr P; 14618 if (!EvaluateMemberPointer(E, P, Info)) 14619 return false; 14620 P.moveInto(Result); 14621 return true; 14622 } else if (T->isArrayType()) { 14623 LValue LV; 14624 APValue &Value = 14625 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14626 if (!EvaluateArray(E, LV, Value, Info)) 14627 return false; 14628 Result = Value; 14629 } else if (T->isRecordType()) { 14630 LValue LV; 14631 APValue &Value = 14632 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14633 if (!EvaluateRecord(E, LV, Value, Info)) 14634 return false; 14635 Result = Value; 14636 } else if (T->isVoidType()) { 14637 if (!Info.getLangOpts().CPlusPlus11) 14638 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14639 << E->getType(); 14640 if (!EvaluateVoid(E, Info)) 14641 return false; 14642 } else if (T->isAtomicType()) { 14643 QualType Unqual = T.getAtomicUnqualifiedType(); 14644 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14645 LValue LV; 14646 APValue &Value = Info.CurrentCall->createTemporary( 14647 E, Unqual, ScopeKind::FullExpression, LV); 14648 if (!EvaluateAtomic(E, &LV, Value, Info)) 14649 return false; 14650 } else { 14651 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14652 return false; 14653 } 14654 } else if (Info.getLangOpts().CPlusPlus11) { 14655 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14656 return false; 14657 } else { 14658 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14659 return false; 14660 } 14661 14662 return true; 14663 } 14664 14665 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14666 /// cases, the in-place evaluation is essential, since later initializers for 14667 /// an object can indirectly refer to subobjects which were initialized earlier. 14668 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14669 const Expr *E, bool AllowNonLiteralTypes) { 14670 assert(!E->isValueDependent()); 14671 14672 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14673 return false; 14674 14675 if (E->isPRValue()) { 14676 // Evaluate arrays and record types in-place, so that later initializers can 14677 // refer to earlier-initialized members of the object. 14678 QualType T = E->getType(); 14679 if (T->isArrayType()) 14680 return EvaluateArray(E, This, Result, Info); 14681 else if (T->isRecordType()) 14682 return EvaluateRecord(E, This, Result, Info); 14683 else if (T->isAtomicType()) { 14684 QualType Unqual = T.getAtomicUnqualifiedType(); 14685 if (Unqual->isArrayType() || Unqual->isRecordType()) 14686 return EvaluateAtomic(E, &This, Result, Info); 14687 } 14688 } 14689 14690 // For any other type, in-place evaluation is unimportant. 14691 return Evaluate(Result, Info, E); 14692 } 14693 14694 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14695 /// lvalue-to-rvalue cast if it is an lvalue. 14696 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14697 assert(!E->isValueDependent()); 14698 if (Info.EnableNewConstInterp) { 14699 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14700 return false; 14701 } else { 14702 if (E->getType().isNull()) 14703 return false; 14704 14705 if (!CheckLiteralType(Info, E)) 14706 return false; 14707 14708 if (!::Evaluate(Result, Info, E)) 14709 return false; 14710 14711 if (E->isGLValue()) { 14712 LValue LV; 14713 LV.setFrom(Info.Ctx, Result); 14714 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14715 return false; 14716 } 14717 } 14718 14719 // Check this core constant expression is a constant expression. 14720 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14721 ConstantExprKind::Normal) && 14722 CheckMemoryLeaks(Info); 14723 } 14724 14725 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14726 const ASTContext &Ctx, bool &IsConst) { 14727 // Fast-path evaluations of integer literals, since we sometimes see files 14728 // containing vast quantities of these. 14729 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14730 Result.Val = APValue(APSInt(L->getValue(), 14731 L->getType()->isUnsignedIntegerType())); 14732 IsConst = true; 14733 return true; 14734 } 14735 14736 // This case should be rare, but we need to check it before we check on 14737 // the type below. 14738 if (Exp->getType().isNull()) { 14739 IsConst = false; 14740 return true; 14741 } 14742 14743 // FIXME: Evaluating values of large array and record types can cause 14744 // performance problems. Only do so in C++11 for now. 14745 if (Exp->isPRValue() && 14746 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14747 !Ctx.getLangOpts().CPlusPlus11) { 14748 IsConst = false; 14749 return true; 14750 } 14751 return false; 14752 } 14753 14754 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14755 Expr::SideEffectsKind SEK) { 14756 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14757 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14758 } 14759 14760 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14761 const ASTContext &Ctx, EvalInfo &Info) { 14762 assert(!E->isValueDependent()); 14763 bool IsConst; 14764 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14765 return IsConst; 14766 14767 return EvaluateAsRValue(Info, E, Result.Val); 14768 } 14769 14770 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14771 const ASTContext &Ctx, 14772 Expr::SideEffectsKind AllowSideEffects, 14773 EvalInfo &Info) { 14774 assert(!E->isValueDependent()); 14775 if (!E->getType()->isIntegralOrEnumerationType()) 14776 return false; 14777 14778 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14779 !ExprResult.Val.isInt() || 14780 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14781 return false; 14782 14783 return true; 14784 } 14785 14786 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14787 const ASTContext &Ctx, 14788 Expr::SideEffectsKind AllowSideEffects, 14789 EvalInfo &Info) { 14790 assert(!E->isValueDependent()); 14791 if (!E->getType()->isFixedPointType()) 14792 return false; 14793 14794 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14795 return false; 14796 14797 if (!ExprResult.Val.isFixedPoint() || 14798 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14799 return false; 14800 14801 return true; 14802 } 14803 14804 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14805 /// any crazy technique (that has nothing to do with language standards) that 14806 /// we want to. If this function returns true, it returns the folded constant 14807 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14808 /// will be applied to the result. 14809 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14810 bool InConstantContext) const { 14811 assert(!isValueDependent() && 14812 "Expression evaluator can't be called on a dependent expression."); 14813 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14814 Info.InConstantContext = InConstantContext; 14815 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14816 } 14817 14818 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14819 bool InConstantContext) const { 14820 assert(!isValueDependent() && 14821 "Expression evaluator can't be called on a dependent expression."); 14822 EvalResult Scratch; 14823 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14824 HandleConversionToBool(Scratch.Val, Result); 14825 } 14826 14827 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14828 SideEffectsKind AllowSideEffects, 14829 bool InConstantContext) const { 14830 assert(!isValueDependent() && 14831 "Expression evaluator can't be called on a dependent expression."); 14832 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14833 Info.InConstantContext = InConstantContext; 14834 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14835 } 14836 14837 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14838 SideEffectsKind AllowSideEffects, 14839 bool InConstantContext) const { 14840 assert(!isValueDependent() && 14841 "Expression evaluator can't be called on a dependent expression."); 14842 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14843 Info.InConstantContext = InConstantContext; 14844 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14845 } 14846 14847 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14848 SideEffectsKind AllowSideEffects, 14849 bool InConstantContext) const { 14850 assert(!isValueDependent() && 14851 "Expression evaluator can't be called on a dependent expression."); 14852 14853 if (!getType()->isRealFloatingType()) 14854 return false; 14855 14856 EvalResult ExprResult; 14857 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14858 !ExprResult.Val.isFloat() || 14859 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14860 return false; 14861 14862 Result = ExprResult.Val.getFloat(); 14863 return true; 14864 } 14865 14866 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14867 bool InConstantContext) const { 14868 assert(!isValueDependent() && 14869 "Expression evaluator can't be called on a dependent expression."); 14870 14871 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14872 Info.InConstantContext = InConstantContext; 14873 LValue LV; 14874 CheckedTemporaries CheckedTemps; 14875 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14876 Result.HasSideEffects || 14877 !CheckLValueConstantExpression(Info, getExprLoc(), 14878 Ctx.getLValueReferenceType(getType()), LV, 14879 ConstantExprKind::Normal, CheckedTemps)) 14880 return false; 14881 14882 LV.moveInto(Result.Val); 14883 return true; 14884 } 14885 14886 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14887 APValue DestroyedValue, QualType Type, 14888 SourceLocation Loc, Expr::EvalStatus &EStatus, 14889 bool IsConstantDestruction) { 14890 EvalInfo Info(Ctx, EStatus, 14891 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14892 : EvalInfo::EM_ConstantFold); 14893 Info.setEvaluatingDecl(Base, DestroyedValue, 14894 EvalInfo::EvaluatingDeclKind::Dtor); 14895 Info.InConstantContext = IsConstantDestruction; 14896 14897 LValue LVal; 14898 LVal.set(Base); 14899 14900 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14901 EStatus.HasSideEffects) 14902 return false; 14903 14904 if (!Info.discardCleanups()) 14905 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14906 14907 return true; 14908 } 14909 14910 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14911 ConstantExprKind Kind) const { 14912 assert(!isValueDependent() && 14913 "Expression evaluator can't be called on a dependent expression."); 14914 14915 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14916 EvalInfo Info(Ctx, Result, EM); 14917 Info.InConstantContext = true; 14918 14919 // The type of the object we're initializing is 'const T' for a class NTTP. 14920 QualType T = getType(); 14921 if (Kind == ConstantExprKind::ClassTemplateArgument) 14922 T.addConst(); 14923 14924 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14925 // represent the result of the evaluation. CheckConstantExpression ensures 14926 // this doesn't escape. 14927 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14928 APValue::LValueBase Base(&BaseMTE); 14929 14930 Info.setEvaluatingDecl(Base, Result.Val); 14931 LValue LVal; 14932 LVal.set(Base); 14933 14934 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14935 return false; 14936 14937 if (!Info.discardCleanups()) 14938 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14939 14940 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14941 Result.Val, Kind)) 14942 return false; 14943 if (!CheckMemoryLeaks(Info)) 14944 return false; 14945 14946 // If this is a class template argument, it's required to have constant 14947 // destruction too. 14948 if (Kind == ConstantExprKind::ClassTemplateArgument && 14949 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 14950 true) || 14951 Result.HasSideEffects)) { 14952 // FIXME: Prefix a note to indicate that the problem is lack of constant 14953 // destruction. 14954 return false; 14955 } 14956 14957 return true; 14958 } 14959 14960 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14961 const VarDecl *VD, 14962 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14963 assert(!isValueDependent() && 14964 "Expression evaluator can't be called on a dependent expression."); 14965 14966 // FIXME: Evaluating initializers for large array and record types can cause 14967 // performance problems. Only do so in C++11 for now. 14968 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14969 !Ctx.getLangOpts().CPlusPlus11) 14970 return false; 14971 14972 Expr::EvalStatus EStatus; 14973 EStatus.Diag = &Notes; 14974 14975 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14976 ? EvalInfo::EM_ConstantExpression 14977 : EvalInfo::EM_ConstantFold); 14978 Info.setEvaluatingDecl(VD, Value); 14979 Info.InConstantContext = true; 14980 14981 SourceLocation DeclLoc = VD->getLocation(); 14982 QualType DeclTy = VD->getType(); 14983 14984 if (Info.EnableNewConstInterp) { 14985 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14986 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14987 return false; 14988 } else { 14989 LValue LVal; 14990 LVal.set(VD); 14991 14992 if (!EvaluateInPlace(Value, Info, LVal, this, 14993 /*AllowNonLiteralTypes=*/true) || 14994 EStatus.HasSideEffects) 14995 return false; 14996 14997 // At this point, any lifetime-extended temporaries are completely 14998 // initialized. 14999 Info.performLifetimeExtension(); 15000 15001 if (!Info.discardCleanups()) 15002 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15003 } 15004 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15005 ConstantExprKind::Normal) && 15006 CheckMemoryLeaks(Info); 15007 } 15008 15009 bool VarDecl::evaluateDestruction( 15010 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15011 Expr::EvalStatus EStatus; 15012 EStatus.Diag = &Notes; 15013 15014 // Only treat the destruction as constant destruction if we formally have 15015 // constant initialization (or are usable in a constant expression). 15016 bool IsConstantDestruction = hasConstantInitialization(); 15017 15018 // Make a copy of the value for the destructor to mutate, if we know it. 15019 // Otherwise, treat the value as default-initialized; if the destructor works 15020 // anyway, then the destruction is constant (and must be essentially empty). 15021 APValue DestroyedValue; 15022 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15023 DestroyedValue = *getEvaluatedValue(); 15024 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15025 return false; 15026 15027 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15028 getType(), getLocation(), EStatus, 15029 IsConstantDestruction) || 15030 EStatus.HasSideEffects) 15031 return false; 15032 15033 ensureEvaluatedStmt()->HasConstantDestruction = true; 15034 return true; 15035 } 15036 15037 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15038 /// constant folded, but discard the result. 15039 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15040 assert(!isValueDependent() && 15041 "Expression evaluator can't be called on a dependent expression."); 15042 15043 EvalResult Result; 15044 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15045 !hasUnacceptableSideEffect(Result, SEK); 15046 } 15047 15048 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15049 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15050 assert(!isValueDependent() && 15051 "Expression evaluator can't be called on a dependent expression."); 15052 15053 EvalResult EVResult; 15054 EVResult.Diag = Diag; 15055 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15056 Info.InConstantContext = true; 15057 15058 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15059 (void)Result; 15060 assert(Result && "Could not evaluate expression"); 15061 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15062 15063 return EVResult.Val.getInt(); 15064 } 15065 15066 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15067 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15068 assert(!isValueDependent() && 15069 "Expression evaluator can't be called on a dependent expression."); 15070 15071 EvalResult EVResult; 15072 EVResult.Diag = Diag; 15073 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15074 Info.InConstantContext = true; 15075 Info.CheckingForUndefinedBehavior = true; 15076 15077 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15078 (void)Result; 15079 assert(Result && "Could not evaluate expression"); 15080 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15081 15082 return EVResult.Val.getInt(); 15083 } 15084 15085 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15086 assert(!isValueDependent() && 15087 "Expression evaluator can't be called on a dependent expression."); 15088 15089 bool IsConst; 15090 EvalResult EVResult; 15091 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15092 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15093 Info.CheckingForUndefinedBehavior = true; 15094 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15095 } 15096 } 15097 15098 bool Expr::EvalResult::isGlobalLValue() const { 15099 assert(Val.isLValue()); 15100 return IsGlobalLValue(Val.getLValueBase()); 15101 } 15102 15103 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15104 /// an integer constant expression. 15105 15106 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15107 /// comma, etc 15108 15109 // CheckICE - This function does the fundamental ICE checking: the returned 15110 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15111 // and a (possibly null) SourceLocation indicating the location of the problem. 15112 // 15113 // Note that to reduce code duplication, this helper does no evaluation 15114 // itself; the caller checks whether the expression is evaluatable, and 15115 // in the rare cases where CheckICE actually cares about the evaluated 15116 // value, it calls into Evaluate. 15117 15118 namespace { 15119 15120 enum ICEKind { 15121 /// This expression is an ICE. 15122 IK_ICE, 15123 /// This expression is not an ICE, but if it isn't evaluated, it's 15124 /// a legal subexpression for an ICE. This return value is used to handle 15125 /// the comma operator in C99 mode, and non-constant subexpressions. 15126 IK_ICEIfUnevaluated, 15127 /// This expression is not an ICE, and is not a legal subexpression for one. 15128 IK_NotICE 15129 }; 15130 15131 struct ICEDiag { 15132 ICEKind Kind; 15133 SourceLocation Loc; 15134 15135 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15136 }; 15137 15138 } 15139 15140 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15141 15142 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15143 15144 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15145 Expr::EvalResult EVResult; 15146 Expr::EvalStatus Status; 15147 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15148 15149 Info.InConstantContext = true; 15150 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15151 !EVResult.Val.isInt()) 15152 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15153 15154 return NoDiag(); 15155 } 15156 15157 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15158 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15159 if (!E->getType()->isIntegralOrEnumerationType()) 15160 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15161 15162 switch (E->getStmtClass()) { 15163 #define ABSTRACT_STMT(Node) 15164 #define STMT(Node, Base) case Expr::Node##Class: 15165 #define EXPR(Node, Base) 15166 #include "clang/AST/StmtNodes.inc" 15167 case Expr::PredefinedExprClass: 15168 case Expr::FloatingLiteralClass: 15169 case Expr::ImaginaryLiteralClass: 15170 case Expr::StringLiteralClass: 15171 case Expr::ArraySubscriptExprClass: 15172 case Expr::MatrixSubscriptExprClass: 15173 case Expr::OMPArraySectionExprClass: 15174 case Expr::OMPArrayShapingExprClass: 15175 case Expr::OMPIteratorExprClass: 15176 case Expr::MemberExprClass: 15177 case Expr::CompoundAssignOperatorClass: 15178 case Expr::CompoundLiteralExprClass: 15179 case Expr::ExtVectorElementExprClass: 15180 case Expr::DesignatedInitExprClass: 15181 case Expr::ArrayInitLoopExprClass: 15182 case Expr::ArrayInitIndexExprClass: 15183 case Expr::NoInitExprClass: 15184 case Expr::DesignatedInitUpdateExprClass: 15185 case Expr::ImplicitValueInitExprClass: 15186 case Expr::ParenListExprClass: 15187 case Expr::VAArgExprClass: 15188 case Expr::AddrLabelExprClass: 15189 case Expr::StmtExprClass: 15190 case Expr::CXXMemberCallExprClass: 15191 case Expr::CUDAKernelCallExprClass: 15192 case Expr::CXXAddrspaceCastExprClass: 15193 case Expr::CXXDynamicCastExprClass: 15194 case Expr::CXXTypeidExprClass: 15195 case Expr::CXXUuidofExprClass: 15196 case Expr::MSPropertyRefExprClass: 15197 case Expr::MSPropertySubscriptExprClass: 15198 case Expr::CXXNullPtrLiteralExprClass: 15199 case Expr::UserDefinedLiteralClass: 15200 case Expr::CXXThisExprClass: 15201 case Expr::CXXThrowExprClass: 15202 case Expr::CXXNewExprClass: 15203 case Expr::CXXDeleteExprClass: 15204 case Expr::CXXPseudoDestructorExprClass: 15205 case Expr::UnresolvedLookupExprClass: 15206 case Expr::TypoExprClass: 15207 case Expr::RecoveryExprClass: 15208 case Expr::DependentScopeDeclRefExprClass: 15209 case Expr::CXXConstructExprClass: 15210 case Expr::CXXInheritedCtorInitExprClass: 15211 case Expr::CXXStdInitializerListExprClass: 15212 case Expr::CXXBindTemporaryExprClass: 15213 case Expr::ExprWithCleanupsClass: 15214 case Expr::CXXTemporaryObjectExprClass: 15215 case Expr::CXXUnresolvedConstructExprClass: 15216 case Expr::CXXDependentScopeMemberExprClass: 15217 case Expr::UnresolvedMemberExprClass: 15218 case Expr::ObjCStringLiteralClass: 15219 case Expr::ObjCBoxedExprClass: 15220 case Expr::ObjCArrayLiteralClass: 15221 case Expr::ObjCDictionaryLiteralClass: 15222 case Expr::ObjCEncodeExprClass: 15223 case Expr::ObjCMessageExprClass: 15224 case Expr::ObjCSelectorExprClass: 15225 case Expr::ObjCProtocolExprClass: 15226 case Expr::ObjCIvarRefExprClass: 15227 case Expr::ObjCPropertyRefExprClass: 15228 case Expr::ObjCSubscriptRefExprClass: 15229 case Expr::ObjCIsaExprClass: 15230 case Expr::ObjCAvailabilityCheckExprClass: 15231 case Expr::ShuffleVectorExprClass: 15232 case Expr::ConvertVectorExprClass: 15233 case Expr::BlockExprClass: 15234 case Expr::NoStmtClass: 15235 case Expr::OpaqueValueExprClass: 15236 case Expr::PackExpansionExprClass: 15237 case Expr::SubstNonTypeTemplateParmPackExprClass: 15238 case Expr::FunctionParmPackExprClass: 15239 case Expr::AsTypeExprClass: 15240 case Expr::ObjCIndirectCopyRestoreExprClass: 15241 case Expr::MaterializeTemporaryExprClass: 15242 case Expr::PseudoObjectExprClass: 15243 case Expr::AtomicExprClass: 15244 case Expr::LambdaExprClass: 15245 case Expr::CXXFoldExprClass: 15246 case Expr::CoawaitExprClass: 15247 case Expr::DependentCoawaitExprClass: 15248 case Expr::CoyieldExprClass: 15249 case Expr::SYCLUniqueStableNameExprClass: 15250 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15251 15252 case Expr::InitListExprClass: { 15253 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15254 // form "T x = { a };" is equivalent to "T x = a;". 15255 // Unless we're initializing a reference, T is a scalar as it is known to be 15256 // of integral or enumeration type. 15257 if (E->isPRValue()) 15258 if (cast<InitListExpr>(E)->getNumInits() == 1) 15259 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15260 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15261 } 15262 15263 case Expr::SizeOfPackExprClass: 15264 case Expr::GNUNullExprClass: 15265 case Expr::SourceLocExprClass: 15266 return NoDiag(); 15267 15268 case Expr::SubstNonTypeTemplateParmExprClass: 15269 return 15270 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15271 15272 case Expr::ConstantExprClass: 15273 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15274 15275 case Expr::ParenExprClass: 15276 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15277 case Expr::GenericSelectionExprClass: 15278 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15279 case Expr::IntegerLiteralClass: 15280 case Expr::FixedPointLiteralClass: 15281 case Expr::CharacterLiteralClass: 15282 case Expr::ObjCBoolLiteralExprClass: 15283 case Expr::CXXBoolLiteralExprClass: 15284 case Expr::CXXScalarValueInitExprClass: 15285 case Expr::TypeTraitExprClass: 15286 case Expr::ConceptSpecializationExprClass: 15287 case Expr::RequiresExprClass: 15288 case Expr::ArrayTypeTraitExprClass: 15289 case Expr::ExpressionTraitExprClass: 15290 case Expr::CXXNoexceptExprClass: 15291 return NoDiag(); 15292 case Expr::CallExprClass: 15293 case Expr::CXXOperatorCallExprClass: { 15294 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15295 // constant expressions, but they can never be ICEs because an ICE cannot 15296 // contain an operand of (pointer to) function type. 15297 const CallExpr *CE = cast<CallExpr>(E); 15298 if (CE->getBuiltinCallee()) 15299 return CheckEvalInICE(E, Ctx); 15300 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15301 } 15302 case Expr::CXXRewrittenBinaryOperatorClass: 15303 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15304 Ctx); 15305 case Expr::DeclRefExprClass: { 15306 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15307 if (isa<EnumConstantDecl>(D)) 15308 return NoDiag(); 15309 15310 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15311 // integer variables in constant expressions: 15312 // 15313 // C++ 7.1.5.1p2 15314 // A variable of non-volatile const-qualified integral or enumeration 15315 // type initialized by an ICE can be used in ICEs. 15316 // 15317 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15318 // that mode, use of reference variables should not be allowed. 15319 const VarDecl *VD = dyn_cast<VarDecl>(D); 15320 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15321 !VD->getType()->isReferenceType()) 15322 return NoDiag(); 15323 15324 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15325 } 15326 case Expr::UnaryOperatorClass: { 15327 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15328 switch (Exp->getOpcode()) { 15329 case UO_PostInc: 15330 case UO_PostDec: 15331 case UO_PreInc: 15332 case UO_PreDec: 15333 case UO_AddrOf: 15334 case UO_Deref: 15335 case UO_Coawait: 15336 // C99 6.6/3 allows increment and decrement within unevaluated 15337 // subexpressions of constant expressions, but they can never be ICEs 15338 // because an ICE cannot contain an lvalue operand. 15339 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15340 case UO_Extension: 15341 case UO_LNot: 15342 case UO_Plus: 15343 case UO_Minus: 15344 case UO_Not: 15345 case UO_Real: 15346 case UO_Imag: 15347 return CheckICE(Exp->getSubExpr(), Ctx); 15348 } 15349 llvm_unreachable("invalid unary operator class"); 15350 } 15351 case Expr::OffsetOfExprClass: { 15352 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15353 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15354 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15355 // compliance: we should warn earlier for offsetof expressions with 15356 // array subscripts that aren't ICEs, and if the array subscripts 15357 // are ICEs, the value of the offsetof must be an integer constant. 15358 return CheckEvalInICE(E, Ctx); 15359 } 15360 case Expr::UnaryExprOrTypeTraitExprClass: { 15361 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15362 if ((Exp->getKind() == UETT_SizeOf) && 15363 Exp->getTypeOfArgument()->isVariableArrayType()) 15364 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15365 return NoDiag(); 15366 } 15367 case Expr::BinaryOperatorClass: { 15368 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15369 switch (Exp->getOpcode()) { 15370 case BO_PtrMemD: 15371 case BO_PtrMemI: 15372 case BO_Assign: 15373 case BO_MulAssign: 15374 case BO_DivAssign: 15375 case BO_RemAssign: 15376 case BO_AddAssign: 15377 case BO_SubAssign: 15378 case BO_ShlAssign: 15379 case BO_ShrAssign: 15380 case BO_AndAssign: 15381 case BO_XorAssign: 15382 case BO_OrAssign: 15383 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15384 // constant expressions, but they can never be ICEs because an ICE cannot 15385 // contain an lvalue operand. 15386 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15387 15388 case BO_Mul: 15389 case BO_Div: 15390 case BO_Rem: 15391 case BO_Add: 15392 case BO_Sub: 15393 case BO_Shl: 15394 case BO_Shr: 15395 case BO_LT: 15396 case BO_GT: 15397 case BO_LE: 15398 case BO_GE: 15399 case BO_EQ: 15400 case BO_NE: 15401 case BO_And: 15402 case BO_Xor: 15403 case BO_Or: 15404 case BO_Comma: 15405 case BO_Cmp: { 15406 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15407 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15408 if (Exp->getOpcode() == BO_Div || 15409 Exp->getOpcode() == BO_Rem) { 15410 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15411 // we don't evaluate one. 15412 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15413 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15414 if (REval == 0) 15415 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15416 if (REval.isSigned() && REval.isAllOnes()) { 15417 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15418 if (LEval.isMinSignedValue()) 15419 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15420 } 15421 } 15422 } 15423 if (Exp->getOpcode() == BO_Comma) { 15424 if (Ctx.getLangOpts().C99) { 15425 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15426 // if it isn't evaluated. 15427 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15428 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15429 } else { 15430 // In both C89 and C++, commas in ICEs are illegal. 15431 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15432 } 15433 } 15434 return Worst(LHSResult, RHSResult); 15435 } 15436 case BO_LAnd: 15437 case BO_LOr: { 15438 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15439 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15440 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15441 // Rare case where the RHS has a comma "side-effect"; we need 15442 // to actually check the condition to see whether the side 15443 // with the comma is evaluated. 15444 if ((Exp->getOpcode() == BO_LAnd) != 15445 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15446 return RHSResult; 15447 return NoDiag(); 15448 } 15449 15450 return Worst(LHSResult, RHSResult); 15451 } 15452 } 15453 llvm_unreachable("invalid binary operator kind"); 15454 } 15455 case Expr::ImplicitCastExprClass: 15456 case Expr::CStyleCastExprClass: 15457 case Expr::CXXFunctionalCastExprClass: 15458 case Expr::CXXStaticCastExprClass: 15459 case Expr::CXXReinterpretCastExprClass: 15460 case Expr::CXXConstCastExprClass: 15461 case Expr::ObjCBridgedCastExprClass: { 15462 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15463 if (isa<ExplicitCastExpr>(E)) { 15464 if (const FloatingLiteral *FL 15465 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15466 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15467 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15468 APSInt IgnoredVal(DestWidth, !DestSigned); 15469 bool Ignored; 15470 // If the value does not fit in the destination type, the behavior is 15471 // undefined, so we are not required to treat it as a constant 15472 // expression. 15473 if (FL->getValue().convertToInteger(IgnoredVal, 15474 llvm::APFloat::rmTowardZero, 15475 &Ignored) & APFloat::opInvalidOp) 15476 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15477 return NoDiag(); 15478 } 15479 } 15480 switch (cast<CastExpr>(E)->getCastKind()) { 15481 case CK_LValueToRValue: 15482 case CK_AtomicToNonAtomic: 15483 case CK_NonAtomicToAtomic: 15484 case CK_NoOp: 15485 case CK_IntegralToBoolean: 15486 case CK_IntegralCast: 15487 return CheckICE(SubExpr, Ctx); 15488 default: 15489 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15490 } 15491 } 15492 case Expr::BinaryConditionalOperatorClass: { 15493 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15494 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15495 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15496 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15497 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15498 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15499 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15500 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15501 return FalseResult; 15502 } 15503 case Expr::ConditionalOperatorClass: { 15504 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15505 // If the condition (ignoring parens) is a __builtin_constant_p call, 15506 // then only the true side is actually considered in an integer constant 15507 // expression, and it is fully evaluated. This is an important GNU 15508 // extension. See GCC PR38377 for discussion. 15509 if (const CallExpr *CallCE 15510 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15511 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15512 return CheckEvalInICE(E, Ctx); 15513 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15514 if (CondResult.Kind == IK_NotICE) 15515 return CondResult; 15516 15517 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15518 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15519 15520 if (TrueResult.Kind == IK_NotICE) 15521 return TrueResult; 15522 if (FalseResult.Kind == IK_NotICE) 15523 return FalseResult; 15524 if (CondResult.Kind == IK_ICEIfUnevaluated) 15525 return CondResult; 15526 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15527 return NoDiag(); 15528 // Rare case where the diagnostics depend on which side is evaluated 15529 // Note that if we get here, CondResult is 0, and at least one of 15530 // TrueResult and FalseResult is non-zero. 15531 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15532 return FalseResult; 15533 return TrueResult; 15534 } 15535 case Expr::CXXDefaultArgExprClass: 15536 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15537 case Expr::CXXDefaultInitExprClass: 15538 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15539 case Expr::ChooseExprClass: { 15540 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15541 } 15542 case Expr::BuiltinBitCastExprClass: { 15543 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15544 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15545 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15546 } 15547 } 15548 15549 llvm_unreachable("Invalid StmtClass!"); 15550 } 15551 15552 /// Evaluate an expression as a C++11 integral constant expression. 15553 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15554 const Expr *E, 15555 llvm::APSInt *Value, 15556 SourceLocation *Loc) { 15557 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15558 if (Loc) *Loc = E->getExprLoc(); 15559 return false; 15560 } 15561 15562 APValue Result; 15563 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15564 return false; 15565 15566 if (!Result.isInt()) { 15567 if (Loc) *Loc = E->getExprLoc(); 15568 return false; 15569 } 15570 15571 if (Value) *Value = Result.getInt(); 15572 return true; 15573 } 15574 15575 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15576 SourceLocation *Loc) const { 15577 assert(!isValueDependent() && 15578 "Expression evaluator can't be called on a dependent expression."); 15579 15580 if (Ctx.getLangOpts().CPlusPlus11) 15581 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15582 15583 ICEDiag D = CheckICE(this, Ctx); 15584 if (D.Kind != IK_ICE) { 15585 if (Loc) *Loc = D.Loc; 15586 return false; 15587 } 15588 return true; 15589 } 15590 15591 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15592 SourceLocation *Loc, 15593 bool isEvaluated) const { 15594 if (isValueDependent()) { 15595 // Expression evaluator can't succeed on a dependent expression. 15596 return None; 15597 } 15598 15599 APSInt Value; 15600 15601 if (Ctx.getLangOpts().CPlusPlus11) { 15602 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15603 return Value; 15604 return None; 15605 } 15606 15607 if (!isIntegerConstantExpr(Ctx, Loc)) 15608 return None; 15609 15610 // The only possible side-effects here are due to UB discovered in the 15611 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15612 // required to treat the expression as an ICE, so we produce the folded 15613 // value. 15614 EvalResult ExprResult; 15615 Expr::EvalStatus Status; 15616 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15617 Info.InConstantContext = true; 15618 15619 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15620 llvm_unreachable("ICE cannot be evaluated!"); 15621 15622 return ExprResult.Val.getInt(); 15623 } 15624 15625 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15626 assert(!isValueDependent() && 15627 "Expression evaluator can't be called on a dependent expression."); 15628 15629 return CheckICE(this, Ctx).Kind == IK_ICE; 15630 } 15631 15632 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15633 SourceLocation *Loc) const { 15634 assert(!isValueDependent() && 15635 "Expression evaluator can't be called on a dependent expression."); 15636 15637 // We support this checking in C++98 mode in order to diagnose compatibility 15638 // issues. 15639 assert(Ctx.getLangOpts().CPlusPlus); 15640 15641 // Build evaluation settings. 15642 Expr::EvalStatus Status; 15643 SmallVector<PartialDiagnosticAt, 8> Diags; 15644 Status.Diag = &Diags; 15645 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15646 15647 APValue Scratch; 15648 bool IsConstExpr = 15649 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15650 // FIXME: We don't produce a diagnostic for this, but the callers that 15651 // call us on arbitrary full-expressions should generally not care. 15652 Info.discardCleanups() && !Status.HasSideEffects; 15653 15654 if (!Diags.empty()) { 15655 IsConstExpr = false; 15656 if (Loc) *Loc = Diags[0].first; 15657 } else if (!IsConstExpr) { 15658 // FIXME: This shouldn't happen. 15659 if (Loc) *Loc = getExprLoc(); 15660 } 15661 15662 return IsConstExpr; 15663 } 15664 15665 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15666 const FunctionDecl *Callee, 15667 ArrayRef<const Expr*> Args, 15668 const Expr *This) const { 15669 assert(!isValueDependent() && 15670 "Expression evaluator can't be called on a dependent expression."); 15671 15672 Expr::EvalStatus Status; 15673 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15674 Info.InConstantContext = true; 15675 15676 LValue ThisVal; 15677 const LValue *ThisPtr = nullptr; 15678 if (This) { 15679 #ifndef NDEBUG 15680 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15681 assert(MD && "Don't provide `this` for non-methods."); 15682 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15683 #endif 15684 if (!This->isValueDependent() && 15685 EvaluateObjectArgument(Info, This, ThisVal) && 15686 !Info.EvalStatus.HasSideEffects) 15687 ThisPtr = &ThisVal; 15688 15689 // Ignore any side-effects from a failed evaluation. This is safe because 15690 // they can't interfere with any other argument evaluation. 15691 Info.EvalStatus.HasSideEffects = false; 15692 } 15693 15694 CallRef Call = Info.CurrentCall->createCall(Callee); 15695 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15696 I != E; ++I) { 15697 unsigned Idx = I - Args.begin(); 15698 if (Idx >= Callee->getNumParams()) 15699 break; 15700 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15701 if ((*I)->isValueDependent() || 15702 !EvaluateCallArg(PVD, *I, Call, Info) || 15703 Info.EvalStatus.HasSideEffects) { 15704 // If evaluation fails, throw away the argument entirely. 15705 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15706 *Slot = APValue(); 15707 } 15708 15709 // Ignore any side-effects from a failed evaluation. This is safe because 15710 // they can't interfere with any other argument evaluation. 15711 Info.EvalStatus.HasSideEffects = false; 15712 } 15713 15714 // Parameter cleanups happen in the caller and are not part of this 15715 // evaluation. 15716 Info.discardCleanups(); 15717 Info.EvalStatus.HasSideEffects = false; 15718 15719 // Build fake call to Callee. 15720 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15721 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15722 FullExpressionRAII Scope(Info); 15723 return Evaluate(Value, Info, this) && Scope.destroy() && 15724 !Info.EvalStatus.HasSideEffects; 15725 } 15726 15727 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15728 SmallVectorImpl< 15729 PartialDiagnosticAt> &Diags) { 15730 // FIXME: It would be useful to check constexpr function templates, but at the 15731 // moment the constant expression evaluator cannot cope with the non-rigorous 15732 // ASTs which we build for dependent expressions. 15733 if (FD->isDependentContext()) 15734 return true; 15735 15736 Expr::EvalStatus Status; 15737 Status.Diag = &Diags; 15738 15739 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15740 Info.InConstantContext = true; 15741 Info.CheckingPotentialConstantExpression = true; 15742 15743 // The constexpr VM attempts to compile all methods to bytecode here. 15744 if (Info.EnableNewConstInterp) { 15745 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15746 return Diags.empty(); 15747 } 15748 15749 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15750 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15751 15752 // Fabricate an arbitrary expression on the stack and pretend that it 15753 // is a temporary being used as the 'this' pointer. 15754 LValue This; 15755 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15756 This.set({&VIE, Info.CurrentCall->Index}); 15757 15758 ArrayRef<const Expr*> Args; 15759 15760 APValue Scratch; 15761 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15762 // Evaluate the call as a constant initializer, to allow the construction 15763 // of objects of non-literal types. 15764 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15765 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15766 } else { 15767 SourceLocation Loc = FD->getLocation(); 15768 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15769 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15770 } 15771 15772 return Diags.empty(); 15773 } 15774 15775 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15776 const FunctionDecl *FD, 15777 SmallVectorImpl< 15778 PartialDiagnosticAt> &Diags) { 15779 assert(!E->isValueDependent() && 15780 "Expression evaluator can't be called on a dependent expression."); 15781 15782 Expr::EvalStatus Status; 15783 Status.Diag = &Diags; 15784 15785 EvalInfo Info(FD->getASTContext(), Status, 15786 EvalInfo::EM_ConstantExpressionUnevaluated); 15787 Info.InConstantContext = true; 15788 Info.CheckingPotentialConstantExpression = true; 15789 15790 // Fabricate a call stack frame to give the arguments a plausible cover story. 15791 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15792 15793 APValue ResultScratch; 15794 Evaluate(ResultScratch, Info, E); 15795 return Diags.empty(); 15796 } 15797 15798 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15799 unsigned Type) const { 15800 if (!getType()->isPointerType()) 15801 return false; 15802 15803 Expr::EvalStatus Status; 15804 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15805 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15806 } 15807 15808 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15809 EvalInfo &Info) { 15810 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15811 return false; 15812 15813 LValue String; 15814 15815 if (!EvaluatePointer(E, String, Info)) 15816 return false; 15817 15818 QualType CharTy = E->getType()->getPointeeType(); 15819 15820 // Fast path: if it's a string literal, search the string value. 15821 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15822 String.getLValueBase().dyn_cast<const Expr *>())) { 15823 StringRef Str = S->getBytes(); 15824 int64_t Off = String.Offset.getQuantity(); 15825 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15826 S->getCharByteWidth() == 1 && 15827 // FIXME: Add fast-path for wchar_t too. 15828 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 15829 Str = Str.substr(Off); 15830 15831 StringRef::size_type Pos = Str.find(0); 15832 if (Pos != StringRef::npos) 15833 Str = Str.substr(0, Pos); 15834 15835 Result = Str.size(); 15836 return true; 15837 } 15838 15839 // Fall through to slow path. 15840 } 15841 15842 // Slow path: scan the bytes of the string looking for the terminating 0. 15843 for (uint64_t Strlen = 0; /**/; ++Strlen) { 15844 APValue Char; 15845 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 15846 !Char.isInt()) 15847 return false; 15848 if (!Char.getInt()) { 15849 Result = Strlen; 15850 return true; 15851 } 15852 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 15853 return false; 15854 } 15855 } 15856 15857 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 15858 Expr::EvalStatus Status; 15859 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15860 return EvaluateBuiltinStrLen(this, Result, Info); 15861 } 15862