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 ASTContext &getCtx() const override { return Ctx; } 987 988 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 989 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 990 EvaluatingDecl = Base; 991 IsEvaluatingDecl = EDK; 992 EvaluatingDeclValue = &Value; 993 } 994 995 bool CheckCallLimit(SourceLocation Loc) { 996 // Don't perform any constexpr calls (other than the call we're checking) 997 // when checking a potential constant expression. 998 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 999 return false; 1000 if (NextCallIndex == 0) { 1001 // NextCallIndex has wrapped around. 1002 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1003 return false; 1004 } 1005 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1006 return true; 1007 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1008 << getLangOpts().ConstexprCallDepth; 1009 return false; 1010 } 1011 1012 std::pair<CallStackFrame *, unsigned> 1013 getCallFrameAndDepth(unsigned CallIndex) { 1014 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1015 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1016 // be null in this loop. 1017 unsigned Depth = CallStackDepth; 1018 CallStackFrame *Frame = CurrentCall; 1019 while (Frame->Index > CallIndex) { 1020 Frame = Frame->Caller; 1021 --Depth; 1022 } 1023 if (Frame->Index == CallIndex) 1024 return {Frame, Depth}; 1025 return {nullptr, 0}; 1026 } 1027 1028 bool nextStep(const Stmt *S) { 1029 if (!StepsLeft) { 1030 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1031 return false; 1032 } 1033 --StepsLeft; 1034 return true; 1035 } 1036 1037 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1038 1039 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1040 Optional<DynAlloc*> Result; 1041 auto It = HeapAllocs.find(DA); 1042 if (It != HeapAllocs.end()) 1043 Result = &It->second; 1044 return Result; 1045 } 1046 1047 /// Get the allocated storage for the given parameter of the given call. 1048 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1049 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1050 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1051 : nullptr; 1052 } 1053 1054 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1055 struct StdAllocatorCaller { 1056 unsigned FrameIndex; 1057 QualType ElemType; 1058 explicit operator bool() const { return FrameIndex != 0; }; 1059 }; 1060 1061 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1062 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1063 Call = Call->Caller) { 1064 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1065 if (!MD) 1066 continue; 1067 const IdentifierInfo *FnII = MD->getIdentifier(); 1068 if (!FnII || !FnII->isStr(FnName)) 1069 continue; 1070 1071 const auto *CTSD = 1072 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1073 if (!CTSD) 1074 continue; 1075 1076 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1077 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1078 if (CTSD->isInStdNamespace() && ClassII && 1079 ClassII->isStr("allocator") && TAL.size() >= 1 && 1080 TAL[0].getKind() == TemplateArgument::Type) 1081 return {Call->Index, TAL[0].getAsType()}; 1082 } 1083 1084 return {}; 1085 } 1086 1087 void performLifetimeExtension() { 1088 // Disable the cleanups for lifetime-extended temporaries. 1089 llvm::erase_if(CleanupStack, [](Cleanup &C) { 1090 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); 1091 }); 1092 } 1093 1094 /// Throw away any remaining cleanups at the end of evaluation. If any 1095 /// cleanups would have had a side-effect, note that as an unmodeled 1096 /// side-effect and return false. Otherwise, return true. 1097 bool discardCleanups() { 1098 for (Cleanup &C : CleanupStack) { 1099 if (C.hasSideEffect() && !noteSideEffect()) { 1100 CleanupStack.clear(); 1101 return false; 1102 } 1103 } 1104 CleanupStack.clear(); 1105 return true; 1106 } 1107 1108 private: 1109 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1110 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1111 1112 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1113 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1114 1115 void setFoldFailureDiagnostic(bool Flag) override { 1116 HasFoldFailureDiagnostic = Flag; 1117 } 1118 1119 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 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) {} 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 // ... the address of an unnamed global constant 1982 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D); 1983 } 1984 1985 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1986 return true; 1987 1988 const Expr *E = B.get<const Expr*>(); 1989 switch (E->getStmtClass()) { 1990 default: 1991 return false; 1992 case Expr::CompoundLiteralExprClass: { 1993 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1994 return CLE->isFileScope() && CLE->isLValue(); 1995 } 1996 case Expr::MaterializeTemporaryExprClass: 1997 // A materialized temporary might have been lifetime-extended to static 1998 // storage duration. 1999 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2000 // A string literal has static storage duration. 2001 case Expr::StringLiteralClass: 2002 case Expr::PredefinedExprClass: 2003 case Expr::ObjCStringLiteralClass: 2004 case Expr::ObjCEncodeExprClass: 2005 return true; 2006 case Expr::ObjCBoxedExprClass: 2007 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2008 case Expr::CallExprClass: 2009 return IsConstantCall(cast<CallExpr>(E)); 2010 // For GCC compatibility, &&label has static storage duration. 2011 case Expr::AddrLabelExprClass: 2012 return true; 2013 // A Block literal expression may be used as the initialization value for 2014 // Block variables at global or local static scope. 2015 case Expr::BlockExprClass: 2016 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2017 // The APValue generated from a __builtin_source_location will be emitted as a 2018 // literal. 2019 case Expr::SourceLocExprClass: 2020 return true; 2021 case Expr::ImplicitValueInitExprClass: 2022 // FIXME: 2023 // We can never form an lvalue with an implicit value initialization as its 2024 // base through expression evaluation, so these only appear in one case: the 2025 // implicit variable declaration we invent when checking whether a constexpr 2026 // constructor can produce a constant expression. We must assume that such 2027 // an expression might be a global lvalue. 2028 return true; 2029 } 2030 } 2031 2032 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2033 return LVal.Base.dyn_cast<const ValueDecl*>(); 2034 } 2035 2036 static bool IsLiteralLValue(const LValue &Value) { 2037 if (Value.getLValueCallIndex()) 2038 return false; 2039 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2040 return E && !isa<MaterializeTemporaryExpr>(E); 2041 } 2042 2043 static bool IsWeakLValue(const LValue &Value) { 2044 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2045 return Decl && Decl->isWeak(); 2046 } 2047 2048 static bool isZeroSized(const LValue &Value) { 2049 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2050 if (Decl && isa<VarDecl>(Decl)) { 2051 QualType Ty = Decl->getType(); 2052 if (Ty->isArrayType()) 2053 return Ty->isIncompleteType() || 2054 Decl->getASTContext().getTypeSize(Ty) == 0; 2055 } 2056 return false; 2057 } 2058 2059 static bool HasSameBase(const LValue &A, const LValue &B) { 2060 if (!A.getLValueBase()) 2061 return !B.getLValueBase(); 2062 if (!B.getLValueBase()) 2063 return false; 2064 2065 if (A.getLValueBase().getOpaqueValue() != 2066 B.getLValueBase().getOpaqueValue()) 2067 return false; 2068 2069 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2070 A.getLValueVersion() == B.getLValueVersion(); 2071 } 2072 2073 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2074 assert(Base && "no location for a null lvalue"); 2075 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2076 2077 // For a parameter, find the corresponding call stack frame (if it still 2078 // exists), and point at the parameter of the function definition we actually 2079 // invoked. 2080 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2081 unsigned Idx = PVD->getFunctionScopeIndex(); 2082 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2083 if (F->Arguments.CallIndex == Base.getCallIndex() && 2084 F->Arguments.Version == Base.getVersion() && F->Callee && 2085 Idx < F->Callee->getNumParams()) { 2086 VD = F->Callee->getParamDecl(Idx); 2087 break; 2088 } 2089 } 2090 } 2091 2092 if (VD) 2093 Info.Note(VD->getLocation(), diag::note_declared_at); 2094 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2095 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2096 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2097 // FIXME: Produce a note for dangling pointers too. 2098 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2099 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2100 diag::note_constexpr_dynamic_alloc_here); 2101 } 2102 // We have no information to show for a typeid(T) object. 2103 } 2104 2105 enum class CheckEvaluationResultKind { 2106 ConstantExpression, 2107 FullyInitialized, 2108 }; 2109 2110 /// Materialized temporaries that we've already checked to determine if they're 2111 /// initializsed by a constant expression. 2112 using CheckedTemporaries = 2113 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2114 2115 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2116 EvalInfo &Info, SourceLocation DiagLoc, 2117 QualType Type, const APValue &Value, 2118 ConstantExprKind Kind, 2119 SourceLocation SubobjectLoc, 2120 CheckedTemporaries &CheckedTemps); 2121 2122 /// Check that this reference or pointer core constant expression is a valid 2123 /// value for an address or reference constant expression. Return true if we 2124 /// can fold this expression, whether or not it's a constant expression. 2125 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2126 QualType Type, const LValue &LVal, 2127 ConstantExprKind Kind, 2128 CheckedTemporaries &CheckedTemps) { 2129 bool IsReferenceType = Type->isReferenceType(); 2130 2131 APValue::LValueBase Base = LVal.getLValueBase(); 2132 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2133 2134 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2135 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2136 2137 // Additional restrictions apply in a template argument. We only enforce the 2138 // C++20 restrictions here; additional syntactic and semantic restrictions 2139 // are applied elsewhere. 2140 if (isTemplateArgument(Kind)) { 2141 int InvalidBaseKind = -1; 2142 StringRef Ident; 2143 if (Base.is<TypeInfoLValue>()) 2144 InvalidBaseKind = 0; 2145 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2146 InvalidBaseKind = 1; 2147 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2148 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2149 InvalidBaseKind = 2; 2150 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2151 InvalidBaseKind = 3; 2152 Ident = PE->getIdentKindName(); 2153 } 2154 2155 if (InvalidBaseKind != -1) { 2156 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2157 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2158 << Ident; 2159 return false; 2160 } 2161 } 2162 2163 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2164 if (FD->isConsteval()) { 2165 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2166 << !Type->isAnyPointerType(); 2167 Info.Note(FD->getLocation(), diag::note_declared_at); 2168 return false; 2169 } 2170 } 2171 2172 // Check that the object is a global. Note that the fake 'this' object we 2173 // manufacture when checking potential constant expressions is conservatively 2174 // assumed to be global here. 2175 if (!IsGlobalLValue(Base)) { 2176 if (Info.getLangOpts().CPlusPlus11) { 2177 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2178 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2179 << IsReferenceType << !Designator.Entries.empty() 2180 << !!VD << VD; 2181 2182 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2183 if (VarD && VarD->isConstexpr()) { 2184 // Non-static local constexpr variables have unintuitive semantics: 2185 // constexpr int a = 1; 2186 // constexpr const int *p = &a; 2187 // ... is invalid because the address of 'a' is not constant. Suggest 2188 // adding a 'static' in this case. 2189 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2190 << VarD 2191 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2192 } else { 2193 NoteLValueLocation(Info, Base); 2194 } 2195 } else { 2196 Info.FFDiag(Loc); 2197 } 2198 // Don't allow references to temporaries to escape. 2199 return false; 2200 } 2201 assert((Info.checkingPotentialConstantExpression() || 2202 LVal.getLValueCallIndex() == 0) && 2203 "have call index for global lvalue"); 2204 2205 if (Base.is<DynamicAllocLValue>()) { 2206 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2207 << IsReferenceType << !Designator.Entries.empty(); 2208 NoteLValueLocation(Info, Base); 2209 return false; 2210 } 2211 2212 if (BaseVD) { 2213 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2214 // Check if this is a thread-local variable. 2215 if (Var->getTLSKind()) 2216 // FIXME: Diagnostic! 2217 return false; 2218 2219 // A dllimport variable never acts like a constant, unless we're 2220 // evaluating a value for use only in name mangling. 2221 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2222 // FIXME: Diagnostic! 2223 return false; 2224 2225 // In CUDA/HIP device compilation, only device side variables have 2226 // constant addresses. 2227 if (Info.getCtx().getLangOpts().CUDA && 2228 Info.getCtx().getLangOpts().CUDAIsDevice && 2229 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { 2230 if ((!Var->hasAttr<CUDADeviceAttr>() && 2231 !Var->hasAttr<CUDAConstantAttr>() && 2232 !Var->getType()->isCUDADeviceBuiltinSurfaceType() && 2233 !Var->getType()->isCUDADeviceBuiltinTextureType()) || 2234 Var->hasAttr<HIPManagedAttr>()) 2235 return false; 2236 } 2237 } 2238 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2239 // __declspec(dllimport) must be handled very carefully: 2240 // We must never initialize an expression with the thunk in C++. 2241 // Doing otherwise would allow the same id-expression to yield 2242 // different addresses for the same function in different translation 2243 // units. However, this means that we must dynamically initialize the 2244 // expression with the contents of the import address table at runtime. 2245 // 2246 // The C language has no notion of ODR; furthermore, it has no notion of 2247 // dynamic initialization. This means that we are permitted to 2248 // perform initialization with the address of the thunk. 2249 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2250 FD->hasAttr<DLLImportAttr>()) 2251 // FIXME: Diagnostic! 2252 return false; 2253 } 2254 } else if (const auto *MTE = 2255 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2256 if (CheckedTemps.insert(MTE).second) { 2257 QualType TempType = getType(Base); 2258 if (TempType.isDestructedType()) { 2259 Info.FFDiag(MTE->getExprLoc(), 2260 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2261 << TempType; 2262 return false; 2263 } 2264 2265 APValue *V = MTE->getOrCreateValue(false); 2266 assert(V && "evasluation result refers to uninitialised temporary"); 2267 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2268 Info, MTE->getExprLoc(), TempType, *V, 2269 Kind, SourceLocation(), CheckedTemps)) 2270 return false; 2271 } 2272 } 2273 2274 // Allow address constant expressions to be past-the-end pointers. This is 2275 // an extension: the standard requires them to point to an object. 2276 if (!IsReferenceType) 2277 return true; 2278 2279 // A reference constant expression must refer to an object. 2280 if (!Base) { 2281 // FIXME: diagnostic 2282 Info.CCEDiag(Loc); 2283 return true; 2284 } 2285 2286 // Does this refer one past the end of some object? 2287 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2288 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2289 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2290 NoteLValueLocation(Info, Base); 2291 } 2292 2293 return true; 2294 } 2295 2296 /// Member pointers are constant expressions unless they point to a 2297 /// non-virtual dllimport member function. 2298 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2299 SourceLocation Loc, 2300 QualType Type, 2301 const APValue &Value, 2302 ConstantExprKind Kind) { 2303 const ValueDecl *Member = Value.getMemberPointerDecl(); 2304 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2305 if (!FD) 2306 return true; 2307 if (FD->isConsteval()) { 2308 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2309 Info.Note(FD->getLocation(), diag::note_declared_at); 2310 return false; 2311 } 2312 return isForManglingOnly(Kind) || FD->isVirtual() || 2313 !FD->hasAttr<DLLImportAttr>(); 2314 } 2315 2316 /// Check that this core constant expression is of literal type, and if not, 2317 /// produce an appropriate diagnostic. 2318 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2319 const LValue *This = nullptr) { 2320 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) 2321 return true; 2322 2323 // C++1y: A constant initializer for an object o [...] may also invoke 2324 // constexpr constructors for o and its subobjects even if those objects 2325 // are of non-literal class types. 2326 // 2327 // C++11 missed this detail for aggregates, so classes like this: 2328 // struct foo_t { union { int i; volatile int j; } u; }; 2329 // are not (obviously) initializable like so: 2330 // __attribute__((__require_constant_initialization__)) 2331 // static const foo_t x = {{0}}; 2332 // because "i" is a subobject with non-literal initialization (due to the 2333 // volatile member of the union). See: 2334 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2335 // Therefore, we use the C++1y behavior. 2336 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2337 return true; 2338 2339 // Prvalue constant expressions must be of literal types. 2340 if (Info.getLangOpts().CPlusPlus11) 2341 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2342 << E->getType(); 2343 else 2344 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2345 return false; 2346 } 2347 2348 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2349 EvalInfo &Info, SourceLocation DiagLoc, 2350 QualType Type, const APValue &Value, 2351 ConstantExprKind Kind, 2352 SourceLocation SubobjectLoc, 2353 CheckedTemporaries &CheckedTemps) { 2354 if (!Value.hasValue()) { 2355 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2356 << true << Type; 2357 if (SubobjectLoc.isValid()) 2358 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2359 return false; 2360 } 2361 2362 // We allow _Atomic(T) to be initialized from anything that T can be 2363 // initialized from. 2364 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2365 Type = AT->getValueType(); 2366 2367 // Core issue 1454: For a literal constant expression of array or class type, 2368 // each subobject of its value shall have been initialized by a constant 2369 // expression. 2370 if (Value.isArray()) { 2371 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2372 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2373 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2374 Value.getArrayInitializedElt(I), Kind, 2375 SubobjectLoc, CheckedTemps)) 2376 return false; 2377 } 2378 if (!Value.hasArrayFiller()) 2379 return true; 2380 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2381 Value.getArrayFiller(), Kind, SubobjectLoc, 2382 CheckedTemps); 2383 } 2384 if (Value.isUnion() && Value.getUnionField()) { 2385 return CheckEvaluationResult( 2386 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2387 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2388 CheckedTemps); 2389 } 2390 if (Value.isStruct()) { 2391 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2392 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2393 unsigned BaseIndex = 0; 2394 for (const CXXBaseSpecifier &BS : CD->bases()) { 2395 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2396 Value.getStructBase(BaseIndex), Kind, 2397 BS.getBeginLoc(), CheckedTemps)) 2398 return false; 2399 ++BaseIndex; 2400 } 2401 } 2402 for (const auto *I : RD->fields()) { 2403 if (I->isUnnamedBitfield()) 2404 continue; 2405 2406 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2407 Value.getStructField(I->getFieldIndex()), 2408 Kind, I->getLocation(), CheckedTemps)) 2409 return false; 2410 } 2411 } 2412 2413 if (Value.isLValue() && 2414 CERK == CheckEvaluationResultKind::ConstantExpression) { 2415 LValue LVal; 2416 LVal.setFrom(Info.Ctx, Value); 2417 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2418 CheckedTemps); 2419 } 2420 2421 if (Value.isMemberPointer() && 2422 CERK == CheckEvaluationResultKind::ConstantExpression) 2423 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2424 2425 // Everything else is fine. 2426 return true; 2427 } 2428 2429 /// Check that this core constant expression value is a valid value for a 2430 /// constant expression. If not, report an appropriate diagnostic. Does not 2431 /// check that the expression is of literal type. 2432 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2433 QualType Type, const APValue &Value, 2434 ConstantExprKind Kind) { 2435 // Nothing to check for a constant expression of type 'cv void'. 2436 if (Type->isVoidType()) 2437 return true; 2438 2439 CheckedTemporaries CheckedTemps; 2440 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2441 Info, DiagLoc, Type, Value, Kind, 2442 SourceLocation(), CheckedTemps); 2443 } 2444 2445 /// Check that this evaluated value is fully-initialized and can be loaded by 2446 /// an lvalue-to-rvalue conversion. 2447 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2448 QualType Type, const APValue &Value) { 2449 CheckedTemporaries CheckedTemps; 2450 return CheckEvaluationResult( 2451 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2452 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2453 } 2454 2455 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2456 /// "the allocated storage is deallocated within the evaluation". 2457 static bool CheckMemoryLeaks(EvalInfo &Info) { 2458 if (!Info.HeapAllocs.empty()) { 2459 // We can still fold to a constant despite a compile-time memory leak, 2460 // so long as the heap allocation isn't referenced in the result (we check 2461 // that in CheckConstantExpression). 2462 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2463 diag::note_constexpr_memory_leak) 2464 << unsigned(Info.HeapAllocs.size() - 1); 2465 } 2466 return true; 2467 } 2468 2469 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2470 // A null base expression indicates a null pointer. These are always 2471 // evaluatable, and they are false unless the offset is zero. 2472 if (!Value.getLValueBase()) { 2473 Result = !Value.getLValueOffset().isZero(); 2474 return true; 2475 } 2476 2477 // We have a non-null base. These are generally known to be true, but if it's 2478 // a weak declaration it can be null at runtime. 2479 Result = true; 2480 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2481 return !Decl || !Decl->isWeak(); 2482 } 2483 2484 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2485 switch (Val.getKind()) { 2486 case APValue::None: 2487 case APValue::Indeterminate: 2488 return false; 2489 case APValue::Int: 2490 Result = Val.getInt().getBoolValue(); 2491 return true; 2492 case APValue::FixedPoint: 2493 Result = Val.getFixedPoint().getBoolValue(); 2494 return true; 2495 case APValue::Float: 2496 Result = !Val.getFloat().isZero(); 2497 return true; 2498 case APValue::ComplexInt: 2499 Result = Val.getComplexIntReal().getBoolValue() || 2500 Val.getComplexIntImag().getBoolValue(); 2501 return true; 2502 case APValue::ComplexFloat: 2503 Result = !Val.getComplexFloatReal().isZero() || 2504 !Val.getComplexFloatImag().isZero(); 2505 return true; 2506 case APValue::LValue: 2507 return EvalPointerValueAsBool(Val, Result); 2508 case APValue::MemberPointer: 2509 Result = Val.getMemberPointerDecl(); 2510 return true; 2511 case APValue::Vector: 2512 case APValue::Array: 2513 case APValue::Struct: 2514 case APValue::Union: 2515 case APValue::AddrLabelDiff: 2516 return false; 2517 } 2518 2519 llvm_unreachable("unknown APValue kind"); 2520 } 2521 2522 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2523 EvalInfo &Info) { 2524 assert(!E->isValueDependent()); 2525 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2526 APValue Val; 2527 if (!Evaluate(Val, Info, E)) 2528 return false; 2529 return HandleConversionToBool(Val, Result); 2530 } 2531 2532 template<typename T> 2533 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2534 const T &SrcValue, QualType DestType) { 2535 Info.CCEDiag(E, diag::note_constexpr_overflow) 2536 << SrcValue << DestType; 2537 return Info.noteUndefinedBehavior(); 2538 } 2539 2540 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2541 QualType SrcType, const APFloat &Value, 2542 QualType DestType, APSInt &Result) { 2543 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2544 // Determine whether we are converting to unsigned or signed. 2545 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2546 2547 Result = APSInt(DestWidth, !DestSigned); 2548 bool ignored; 2549 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2550 & APFloat::opInvalidOp) 2551 return HandleOverflow(Info, E, Value, DestType); 2552 return true; 2553 } 2554 2555 /// Get rounding mode used for evaluation of the specified expression. 2556 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2557 /// dynamic. 2558 /// If rounding mode is unknown at compile time, still try to evaluate the 2559 /// expression. If the result is exact, it does not depend on rounding mode. 2560 /// So return "tonearest" mode instead of "dynamic". 2561 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2562 bool &DynamicRM) { 2563 llvm::RoundingMode RM = 2564 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2565 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2566 if (DynamicRM) 2567 RM = llvm::RoundingMode::NearestTiesToEven; 2568 return RM; 2569 } 2570 2571 /// Check if the given evaluation result is allowed for constant evaluation. 2572 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2573 APFloat::opStatus St) { 2574 // In a constant context, assume that any dynamic rounding mode or FP 2575 // exception state matches the default floating-point environment. 2576 if (Info.InConstantContext) 2577 return true; 2578 2579 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2580 if ((St & APFloat::opInexact) && 2581 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2582 // Inexact result means that it depends on rounding mode. If the requested 2583 // mode is dynamic, the evaluation cannot be made in compile time. 2584 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2585 return false; 2586 } 2587 2588 if ((St != APFloat::opOK) && 2589 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2590 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2591 FPO.getAllowFEnvAccess())) { 2592 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2593 return false; 2594 } 2595 2596 if ((St & APFloat::opStatus::opInvalidOp) && 2597 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2598 // There is no usefully definable result. 2599 Info.FFDiag(E); 2600 return false; 2601 } 2602 2603 // FIXME: if: 2604 // - evaluation triggered other FP exception, and 2605 // - exception mode is not "ignore", and 2606 // - the expression being evaluated is not a part of global variable 2607 // initializer, 2608 // the evaluation probably need to be rejected. 2609 return true; 2610 } 2611 2612 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2613 QualType SrcType, QualType DestType, 2614 APFloat &Result) { 2615 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2616 bool DynamicRM; 2617 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2618 APFloat::opStatus St; 2619 APFloat Value = Result; 2620 bool ignored; 2621 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2622 return checkFloatingPointResult(Info, E, St); 2623 } 2624 2625 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2626 QualType DestType, QualType SrcType, 2627 const APSInt &Value) { 2628 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2629 // Figure out if this is a truncate, extend or noop cast. 2630 // If the input is signed, do a sign extend, noop, or truncate. 2631 APSInt Result = Value.extOrTrunc(DestWidth); 2632 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2633 if (DestType->isBooleanType()) 2634 Result = Value.getBoolValue(); 2635 return Result; 2636 } 2637 2638 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2639 const FPOptions FPO, 2640 QualType SrcType, const APSInt &Value, 2641 QualType DestType, APFloat &Result) { 2642 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2643 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2644 APFloat::rmNearestTiesToEven); 2645 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2646 FPO.isFPConstrained()) { 2647 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2648 return false; 2649 } 2650 return true; 2651 } 2652 2653 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2654 APValue &Value, const FieldDecl *FD) { 2655 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2656 2657 if (!Value.isInt()) { 2658 // Trying to store a pointer-cast-to-integer into a bitfield. 2659 // FIXME: In this case, we should provide the diagnostic for casting 2660 // a pointer to an integer. 2661 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2662 Info.FFDiag(E); 2663 return false; 2664 } 2665 2666 APSInt &Int = Value.getInt(); 2667 unsigned OldBitWidth = Int.getBitWidth(); 2668 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2669 if (NewBitWidth < OldBitWidth) 2670 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2671 return true; 2672 } 2673 2674 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2675 llvm::APInt &Res) { 2676 APValue SVal; 2677 if (!Evaluate(SVal, Info, E)) 2678 return false; 2679 if (SVal.isInt()) { 2680 Res = SVal.getInt(); 2681 return true; 2682 } 2683 if (SVal.isFloat()) { 2684 Res = SVal.getFloat().bitcastToAPInt(); 2685 return true; 2686 } 2687 if (SVal.isVector()) { 2688 QualType VecTy = E->getType(); 2689 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2690 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2691 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2692 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2693 Res = llvm::APInt::getZero(VecSize); 2694 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2695 APValue &Elt = SVal.getVectorElt(i); 2696 llvm::APInt EltAsInt; 2697 if (Elt.isInt()) { 2698 EltAsInt = Elt.getInt(); 2699 } else if (Elt.isFloat()) { 2700 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2701 } else { 2702 // Don't try to handle vectors of anything other than int or float 2703 // (not sure if it's possible to hit this case). 2704 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2705 return false; 2706 } 2707 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2708 if (BigEndian) 2709 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2710 else 2711 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2712 } 2713 return true; 2714 } 2715 // Give up if the input isn't an int, float, or vector. For example, we 2716 // reject "(v4i16)(intptr_t)&a". 2717 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2718 return false; 2719 } 2720 2721 /// Perform the given integer operation, which is known to need at most BitWidth 2722 /// bits, and check for overflow in the original type (if that type was not an 2723 /// unsigned type). 2724 template<typename Operation> 2725 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2726 const APSInt &LHS, const APSInt &RHS, 2727 unsigned BitWidth, Operation Op, 2728 APSInt &Result) { 2729 if (LHS.isUnsigned()) { 2730 Result = Op(LHS, RHS); 2731 return true; 2732 } 2733 2734 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2735 Result = Value.trunc(LHS.getBitWidth()); 2736 if (Result.extend(BitWidth) != Value) { 2737 if (Info.checkingForUndefinedBehavior()) 2738 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2739 diag::warn_integer_constant_overflow) 2740 << toString(Result, 10) << E->getType(); 2741 return HandleOverflow(Info, E, Value, E->getType()); 2742 } 2743 return true; 2744 } 2745 2746 /// Perform the given binary integer operation. 2747 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2748 BinaryOperatorKind Opcode, APSInt RHS, 2749 APSInt &Result) { 2750 switch (Opcode) { 2751 default: 2752 Info.FFDiag(E); 2753 return false; 2754 case BO_Mul: 2755 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2756 std::multiplies<APSInt>(), Result); 2757 case BO_Add: 2758 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2759 std::plus<APSInt>(), Result); 2760 case BO_Sub: 2761 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2762 std::minus<APSInt>(), Result); 2763 case BO_And: Result = LHS & RHS; return true; 2764 case BO_Xor: Result = LHS ^ RHS; return true; 2765 case BO_Or: Result = LHS | RHS; return true; 2766 case BO_Div: 2767 case BO_Rem: 2768 if (RHS == 0) { 2769 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2770 return false; 2771 } 2772 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2773 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2774 // this operation and gives the two's complement result. 2775 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && 2776 LHS.isMinSignedValue()) 2777 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2778 E->getType()); 2779 return true; 2780 case BO_Shl: { 2781 if (Info.getLangOpts().OpenCL) 2782 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2783 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2784 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2785 RHS.isUnsigned()); 2786 else if (RHS.isSigned() && RHS.isNegative()) { 2787 // During constant-folding, a negative shift is an opposite shift. Such 2788 // a shift is not a constant expression. 2789 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2790 RHS = -RHS; 2791 goto shift_right; 2792 } 2793 shift_left: 2794 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2795 // the shifted type. 2796 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2797 if (SA != RHS) { 2798 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2799 << RHS << E->getType() << LHS.getBitWidth(); 2800 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2801 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2802 // operand, and must not overflow the corresponding unsigned type. 2803 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2804 // E1 x 2^E2 module 2^N. 2805 if (LHS.isNegative()) 2806 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2807 else if (LHS.countLeadingZeros() < SA) 2808 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2809 } 2810 Result = LHS << SA; 2811 return true; 2812 } 2813 case BO_Shr: { 2814 if (Info.getLangOpts().OpenCL) 2815 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2816 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2817 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2818 RHS.isUnsigned()); 2819 else if (RHS.isSigned() && RHS.isNegative()) { 2820 // During constant-folding, a negative shift is an opposite shift. Such a 2821 // shift is not a constant expression. 2822 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2823 RHS = -RHS; 2824 goto shift_left; 2825 } 2826 shift_right: 2827 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2828 // shifted type. 2829 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2830 if (SA != RHS) 2831 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2832 << RHS << E->getType() << LHS.getBitWidth(); 2833 Result = LHS >> SA; 2834 return true; 2835 } 2836 2837 case BO_LT: Result = LHS < RHS; return true; 2838 case BO_GT: Result = LHS > RHS; return true; 2839 case BO_LE: Result = LHS <= RHS; return true; 2840 case BO_GE: Result = LHS >= RHS; return true; 2841 case BO_EQ: Result = LHS == RHS; return true; 2842 case BO_NE: Result = LHS != RHS; return true; 2843 case BO_Cmp: 2844 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2845 } 2846 } 2847 2848 /// Perform the given binary floating-point operation, in-place, on LHS. 2849 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2850 APFloat &LHS, BinaryOperatorKind Opcode, 2851 const APFloat &RHS) { 2852 bool DynamicRM; 2853 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2854 APFloat::opStatus St; 2855 switch (Opcode) { 2856 default: 2857 Info.FFDiag(E); 2858 return false; 2859 case BO_Mul: 2860 St = LHS.multiply(RHS, RM); 2861 break; 2862 case BO_Add: 2863 St = LHS.add(RHS, RM); 2864 break; 2865 case BO_Sub: 2866 St = LHS.subtract(RHS, RM); 2867 break; 2868 case BO_Div: 2869 // [expr.mul]p4: 2870 // If the second operand of / or % is zero the behavior is undefined. 2871 if (RHS.isZero()) 2872 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2873 St = LHS.divide(RHS, RM); 2874 break; 2875 } 2876 2877 // [expr.pre]p4: 2878 // If during the evaluation of an expression, the result is not 2879 // mathematically defined [...], the behavior is undefined. 2880 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2881 if (LHS.isNaN()) { 2882 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2883 return Info.noteUndefinedBehavior(); 2884 } 2885 2886 return checkFloatingPointResult(Info, E, St); 2887 } 2888 2889 static bool handleLogicalOpForVector(const APInt &LHSValue, 2890 BinaryOperatorKind Opcode, 2891 const APInt &RHSValue, APInt &Result) { 2892 bool LHS = (LHSValue != 0); 2893 bool RHS = (RHSValue != 0); 2894 2895 if (Opcode == BO_LAnd) 2896 Result = LHS && RHS; 2897 else 2898 Result = LHS || RHS; 2899 return true; 2900 } 2901 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2902 BinaryOperatorKind Opcode, 2903 const APFloat &RHSValue, APInt &Result) { 2904 bool LHS = !LHSValue.isZero(); 2905 bool RHS = !RHSValue.isZero(); 2906 2907 if (Opcode == BO_LAnd) 2908 Result = LHS && RHS; 2909 else 2910 Result = LHS || RHS; 2911 return true; 2912 } 2913 2914 static bool handleLogicalOpForVector(const APValue &LHSValue, 2915 BinaryOperatorKind Opcode, 2916 const APValue &RHSValue, APInt &Result) { 2917 // The result is always an int type, however operands match the first. 2918 if (LHSValue.getKind() == APValue::Int) 2919 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2920 RHSValue.getInt(), Result); 2921 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2922 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2923 RHSValue.getFloat(), Result); 2924 } 2925 2926 template <typename APTy> 2927 static bool 2928 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2929 const APTy &RHSValue, APInt &Result) { 2930 switch (Opcode) { 2931 default: 2932 llvm_unreachable("unsupported binary operator"); 2933 case BO_EQ: 2934 Result = (LHSValue == RHSValue); 2935 break; 2936 case BO_NE: 2937 Result = (LHSValue != RHSValue); 2938 break; 2939 case BO_LT: 2940 Result = (LHSValue < RHSValue); 2941 break; 2942 case BO_GT: 2943 Result = (LHSValue > RHSValue); 2944 break; 2945 case BO_LE: 2946 Result = (LHSValue <= RHSValue); 2947 break; 2948 case BO_GE: 2949 Result = (LHSValue >= RHSValue); 2950 break; 2951 } 2952 2953 // The boolean operations on these vector types use an instruction that 2954 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 2955 // to -1 to make sure that we produce the correct value. 2956 Result.negate(); 2957 2958 return true; 2959 } 2960 2961 static bool handleCompareOpForVector(const APValue &LHSValue, 2962 BinaryOperatorKind Opcode, 2963 const APValue &RHSValue, APInt &Result) { 2964 // The result is always an int type, however operands match the first. 2965 if (LHSValue.getKind() == APValue::Int) 2966 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2967 RHSValue.getInt(), Result); 2968 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2969 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2970 RHSValue.getFloat(), Result); 2971 } 2972 2973 // Perform binary operations for vector types, in place on the LHS. 2974 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2975 BinaryOperatorKind Opcode, 2976 APValue &LHSValue, 2977 const APValue &RHSValue) { 2978 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2979 "Operation not supported on vector types"); 2980 2981 const auto *VT = E->getType()->castAs<VectorType>(); 2982 unsigned NumElements = VT->getNumElements(); 2983 QualType EltTy = VT->getElementType(); 2984 2985 // In the cases (typically C as I've observed) where we aren't evaluating 2986 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2987 // just give up. 2988 if (!LHSValue.isVector()) { 2989 assert(LHSValue.isLValue() && 2990 "A vector result that isn't a vector OR uncalculated LValue"); 2991 Info.FFDiag(E); 2992 return false; 2993 } 2994 2995 assert(LHSValue.getVectorLength() == NumElements && 2996 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2997 2998 SmallVector<APValue, 4> ResultElements; 2999 3000 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 3001 APValue LHSElt = LHSValue.getVectorElt(EltNum); 3002 APValue RHSElt = RHSValue.getVectorElt(EltNum); 3003 3004 if (EltTy->isIntegerType()) { 3005 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 3006 EltTy->isUnsignedIntegerType()}; 3007 bool Success = true; 3008 3009 if (BinaryOperator::isLogicalOp(Opcode)) 3010 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3011 else if (BinaryOperator::isComparisonOp(Opcode)) 3012 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 3013 else 3014 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 3015 RHSElt.getInt(), EltResult); 3016 3017 if (!Success) { 3018 Info.FFDiag(E); 3019 return false; 3020 } 3021 ResultElements.emplace_back(EltResult); 3022 3023 } else if (EltTy->isFloatingType()) { 3024 assert(LHSElt.getKind() == APValue::Float && 3025 RHSElt.getKind() == APValue::Float && 3026 "Mismatched LHS/RHS/Result Type"); 3027 APFloat LHSFloat = LHSElt.getFloat(); 3028 3029 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3030 RHSElt.getFloat())) { 3031 Info.FFDiag(E); 3032 return false; 3033 } 3034 3035 ResultElements.emplace_back(LHSFloat); 3036 } 3037 } 3038 3039 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3040 return true; 3041 } 3042 3043 /// Cast an lvalue referring to a base subobject to a derived class, by 3044 /// truncating the lvalue's path to the given length. 3045 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3046 const RecordDecl *TruncatedType, 3047 unsigned TruncatedElements) { 3048 SubobjectDesignator &D = Result.Designator; 3049 3050 // Check we actually point to a derived class object. 3051 if (TruncatedElements == D.Entries.size()) 3052 return true; 3053 assert(TruncatedElements >= D.MostDerivedPathLength && 3054 "not casting to a derived class"); 3055 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3056 return false; 3057 3058 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3059 const RecordDecl *RD = TruncatedType; 3060 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3061 if (RD->isInvalidDecl()) return false; 3062 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3063 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3064 if (isVirtualBaseClass(D.Entries[I])) 3065 Result.Offset -= Layout.getVBaseClassOffset(Base); 3066 else 3067 Result.Offset -= Layout.getBaseClassOffset(Base); 3068 RD = Base; 3069 } 3070 D.Entries.resize(TruncatedElements); 3071 return true; 3072 } 3073 3074 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3075 const CXXRecordDecl *Derived, 3076 const CXXRecordDecl *Base, 3077 const ASTRecordLayout *RL = nullptr) { 3078 if (!RL) { 3079 if (Derived->isInvalidDecl()) return false; 3080 RL = &Info.Ctx.getASTRecordLayout(Derived); 3081 } 3082 3083 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3084 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3085 return true; 3086 } 3087 3088 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3089 const CXXRecordDecl *DerivedDecl, 3090 const CXXBaseSpecifier *Base) { 3091 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3092 3093 if (!Base->isVirtual()) 3094 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3095 3096 SubobjectDesignator &D = Obj.Designator; 3097 if (D.Invalid) 3098 return false; 3099 3100 // Extract most-derived object and corresponding type. 3101 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3102 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3103 return false; 3104 3105 // Find the virtual base class. 3106 if (DerivedDecl->isInvalidDecl()) return false; 3107 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3108 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3109 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3110 return true; 3111 } 3112 3113 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3114 QualType Type, LValue &Result) { 3115 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3116 PathE = E->path_end(); 3117 PathI != PathE; ++PathI) { 3118 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3119 *PathI)) 3120 return false; 3121 Type = (*PathI)->getType(); 3122 } 3123 return true; 3124 } 3125 3126 /// Cast an lvalue referring to a derived class to a known base subobject. 3127 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3128 const CXXRecordDecl *DerivedRD, 3129 const CXXRecordDecl *BaseRD) { 3130 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3131 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3132 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3133 llvm_unreachable("Class must be derived from the passed in base class!"); 3134 3135 for (CXXBasePathElement &Elem : Paths.front()) 3136 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3137 return false; 3138 return true; 3139 } 3140 3141 /// Update LVal to refer to the given field, which must be a member of the type 3142 /// currently described by LVal. 3143 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3144 const FieldDecl *FD, 3145 const ASTRecordLayout *RL = nullptr) { 3146 if (!RL) { 3147 if (FD->getParent()->isInvalidDecl()) return false; 3148 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3149 } 3150 3151 unsigned I = FD->getFieldIndex(); 3152 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3153 LVal.addDecl(Info, E, FD); 3154 return true; 3155 } 3156 3157 /// Update LVal to refer to the given indirect field. 3158 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3159 LValue &LVal, 3160 const IndirectFieldDecl *IFD) { 3161 for (const auto *C : IFD->chain()) 3162 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3163 return false; 3164 return true; 3165 } 3166 3167 /// Get the size of the given type in char units. 3168 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3169 QualType Type, CharUnits &Size) { 3170 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3171 // extension. 3172 if (Type->isVoidType() || Type->isFunctionType()) { 3173 Size = CharUnits::One(); 3174 return true; 3175 } 3176 3177 if (Type->isDependentType()) { 3178 Info.FFDiag(Loc); 3179 return false; 3180 } 3181 3182 if (!Type->isConstantSizeType()) { 3183 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3184 // FIXME: Better diagnostic. 3185 Info.FFDiag(Loc); 3186 return false; 3187 } 3188 3189 Size = Info.Ctx.getTypeSizeInChars(Type); 3190 return true; 3191 } 3192 3193 /// Update a pointer value to model pointer arithmetic. 3194 /// \param Info - Information about the ongoing evaluation. 3195 /// \param E - The expression being evaluated, for diagnostic purposes. 3196 /// \param LVal - The pointer value to be updated. 3197 /// \param EltTy - The pointee type represented by LVal. 3198 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3199 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3200 LValue &LVal, QualType EltTy, 3201 APSInt Adjustment) { 3202 CharUnits SizeOfPointee; 3203 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3204 return false; 3205 3206 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3207 return true; 3208 } 3209 3210 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3211 LValue &LVal, QualType EltTy, 3212 int64_t Adjustment) { 3213 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3214 APSInt::get(Adjustment)); 3215 } 3216 3217 /// Update an lvalue to refer to a component of a complex number. 3218 /// \param Info - Information about the ongoing evaluation. 3219 /// \param LVal - The lvalue to be updated. 3220 /// \param EltTy - The complex number's component type. 3221 /// \param Imag - False for the real component, true for the imaginary. 3222 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3223 LValue &LVal, QualType EltTy, 3224 bool Imag) { 3225 if (Imag) { 3226 CharUnits SizeOfComponent; 3227 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3228 return false; 3229 LVal.Offset += SizeOfComponent; 3230 } 3231 LVal.addComplex(Info, E, EltTy, Imag); 3232 return true; 3233 } 3234 3235 /// Try to evaluate the initializer for a variable declaration. 3236 /// 3237 /// \param Info Information about the ongoing evaluation. 3238 /// \param E An expression to be used when printing diagnostics. 3239 /// \param VD The variable whose initializer should be obtained. 3240 /// \param Version The version of the variable within the frame. 3241 /// \param Frame The frame in which the variable was created. Must be null 3242 /// if this variable is not local to the evaluation. 3243 /// \param Result Filled in with a pointer to the value of the variable. 3244 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3245 const VarDecl *VD, CallStackFrame *Frame, 3246 unsigned Version, APValue *&Result) { 3247 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3248 3249 // If this is a local variable, dig out its value. 3250 if (Frame) { 3251 Result = Frame->getTemporary(VD, Version); 3252 if (Result) 3253 return true; 3254 3255 if (!isa<ParmVarDecl>(VD)) { 3256 // Assume variables referenced within a lambda's call operator that were 3257 // not declared within the call operator are captures and during checking 3258 // of a potential constant expression, assume they are unknown constant 3259 // expressions. 3260 assert(isLambdaCallOperator(Frame->Callee) && 3261 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3262 "missing value for local variable"); 3263 if (Info.checkingPotentialConstantExpression()) 3264 return false; 3265 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3266 // still reachable at all? 3267 Info.FFDiag(E->getBeginLoc(), 3268 diag::note_unimplemented_constexpr_lambda_feature_ast) 3269 << "captures not currently allowed"; 3270 return false; 3271 } 3272 } 3273 3274 // If we're currently evaluating the initializer of this declaration, use that 3275 // in-flight value. 3276 if (Info.EvaluatingDecl == Base) { 3277 Result = Info.EvaluatingDeclValue; 3278 return true; 3279 } 3280 3281 if (isa<ParmVarDecl>(VD)) { 3282 // Assume parameters of a potential constant expression are usable in 3283 // constant expressions. 3284 if (!Info.checkingPotentialConstantExpression() || 3285 !Info.CurrentCall->Callee || 3286 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3287 if (Info.getLangOpts().CPlusPlus11) { 3288 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3289 << VD; 3290 NoteLValueLocation(Info, Base); 3291 } else { 3292 Info.FFDiag(E); 3293 } 3294 } 3295 return false; 3296 } 3297 3298 // Dig out the initializer, and use the declaration which it's attached to. 3299 // FIXME: We should eventually check whether the variable has a reachable 3300 // initializing declaration. 3301 const Expr *Init = VD->getAnyInitializer(VD); 3302 if (!Init) { 3303 // Don't diagnose during potential constant expression checking; an 3304 // initializer might be added later. 3305 if (!Info.checkingPotentialConstantExpression()) { 3306 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3307 << VD; 3308 NoteLValueLocation(Info, Base); 3309 } 3310 return false; 3311 } 3312 3313 if (Init->isValueDependent()) { 3314 // The DeclRefExpr is not value-dependent, but the variable it refers to 3315 // has a value-dependent initializer. This should only happen in 3316 // constant-folding cases, where the variable is not actually of a suitable 3317 // type for use in a constant expression (otherwise the DeclRefExpr would 3318 // have been value-dependent too), so diagnose that. 3319 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3320 if (!Info.checkingPotentialConstantExpression()) { 3321 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3322 ? diag::note_constexpr_ltor_non_constexpr 3323 : diag::note_constexpr_ltor_non_integral, 1) 3324 << VD << VD->getType(); 3325 NoteLValueLocation(Info, Base); 3326 } 3327 return false; 3328 } 3329 3330 // Check that we can fold the initializer. In C++, we will have already done 3331 // this in the cases where it matters for conformance. 3332 if (!VD->evaluateValue()) { 3333 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3334 NoteLValueLocation(Info, Base); 3335 return false; 3336 } 3337 3338 // Check that the variable is actually usable in constant expressions. For a 3339 // const integral variable or a reference, we might have a non-constant 3340 // initializer that we can nonetheless evaluate the initializer for. Such 3341 // variables are not usable in constant expressions. In C++98, the 3342 // initializer also syntactically needs to be an ICE. 3343 // 3344 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3345 // expressions here; doing so would regress diagnostics for things like 3346 // reading from a volatile constexpr variable. 3347 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3348 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3349 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3350 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3351 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3352 NoteLValueLocation(Info, Base); 3353 } 3354 3355 // Never use the initializer of a weak variable, not even for constant 3356 // folding. We can't be sure that this is the definition that will be used. 3357 if (VD->isWeak()) { 3358 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3359 NoteLValueLocation(Info, Base); 3360 return false; 3361 } 3362 3363 Result = VD->getEvaluatedValue(); 3364 return true; 3365 } 3366 3367 /// Get the base index of the given base class within an APValue representing 3368 /// the given derived class. 3369 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3370 const CXXRecordDecl *Base) { 3371 Base = Base->getCanonicalDecl(); 3372 unsigned Index = 0; 3373 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3374 E = Derived->bases_end(); I != E; ++I, ++Index) { 3375 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3376 return Index; 3377 } 3378 3379 llvm_unreachable("base class missing from derived class's bases list"); 3380 } 3381 3382 /// Extract the value of a character from a string literal. 3383 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3384 uint64_t Index) { 3385 assert(!isa<SourceLocExpr>(Lit) && 3386 "SourceLocExpr should have already been converted to a StringLiteral"); 3387 3388 // FIXME: Support MakeStringConstant 3389 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3390 std::string Str; 3391 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3392 assert(Index <= Str.size() && "Index too large"); 3393 return APSInt::getUnsigned(Str.c_str()[Index]); 3394 } 3395 3396 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3397 Lit = PE->getFunctionName(); 3398 const StringLiteral *S = cast<StringLiteral>(Lit); 3399 const ConstantArrayType *CAT = 3400 Info.Ctx.getAsConstantArrayType(S->getType()); 3401 assert(CAT && "string literal isn't an array"); 3402 QualType CharType = CAT->getElementType(); 3403 assert(CharType->isIntegerType() && "unexpected character type"); 3404 3405 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3406 CharType->isUnsignedIntegerType()); 3407 if (Index < S->getLength()) 3408 Value = S->getCodeUnit(Index); 3409 return Value; 3410 } 3411 3412 // Expand a string literal into an array of characters. 3413 // 3414 // FIXME: This is inefficient; we should probably introduce something similar 3415 // to the LLVM ConstantDataArray to make this cheaper. 3416 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3417 APValue &Result, 3418 QualType AllocType = QualType()) { 3419 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3420 AllocType.isNull() ? S->getType() : AllocType); 3421 assert(CAT && "string literal isn't an array"); 3422 QualType CharType = CAT->getElementType(); 3423 assert(CharType->isIntegerType() && "unexpected character type"); 3424 3425 unsigned Elts = CAT->getSize().getZExtValue(); 3426 Result = APValue(APValue::UninitArray(), 3427 std::min(S->getLength(), Elts), Elts); 3428 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3429 CharType->isUnsignedIntegerType()); 3430 if (Result.hasArrayFiller()) 3431 Result.getArrayFiller() = APValue(Value); 3432 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3433 Value = S->getCodeUnit(I); 3434 Result.getArrayInitializedElt(I) = APValue(Value); 3435 } 3436 } 3437 3438 // Expand an array so that it has more than Index filled elements. 3439 static void expandArray(APValue &Array, unsigned Index) { 3440 unsigned Size = Array.getArraySize(); 3441 assert(Index < Size); 3442 3443 // Always at least double the number of elements for which we store a value. 3444 unsigned OldElts = Array.getArrayInitializedElts(); 3445 unsigned NewElts = std::max(Index+1, OldElts * 2); 3446 NewElts = std::min(Size, std::max(NewElts, 8u)); 3447 3448 // Copy the data across. 3449 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3450 for (unsigned I = 0; I != OldElts; ++I) 3451 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3452 for (unsigned I = OldElts; I != NewElts; ++I) 3453 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3454 if (NewValue.hasArrayFiller()) 3455 NewValue.getArrayFiller() = Array.getArrayFiller(); 3456 Array.swap(NewValue); 3457 } 3458 3459 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3460 /// conversion. If it's of class type, we may assume that the copy operation 3461 /// is trivial. Note that this is never true for a union type with fields 3462 /// (because the copy always "reads" the active member) and always true for 3463 /// a non-class type. 3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3465 static bool isReadByLvalueToRvalueConversion(QualType T) { 3466 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3467 return !RD || isReadByLvalueToRvalueConversion(RD); 3468 } 3469 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3470 // FIXME: A trivial copy of a union copies the object representation, even if 3471 // the union is empty. 3472 if (RD->isUnion()) 3473 return !RD->field_empty(); 3474 if (RD->isEmpty()) 3475 return false; 3476 3477 for (auto *Field : RD->fields()) 3478 if (!Field->isUnnamedBitfield() && 3479 isReadByLvalueToRvalueConversion(Field->getType())) 3480 return true; 3481 3482 for (auto &BaseSpec : RD->bases()) 3483 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3484 return true; 3485 3486 return false; 3487 } 3488 3489 /// Diagnose an attempt to read from any unreadable field within the specified 3490 /// type, which might be a class type. 3491 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3492 QualType T) { 3493 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3494 if (!RD) 3495 return false; 3496 3497 if (!RD->hasMutableFields()) 3498 return false; 3499 3500 for (auto *Field : RD->fields()) { 3501 // If we're actually going to read this field in some way, then it can't 3502 // be mutable. If we're in a union, then assigning to a mutable field 3503 // (even an empty one) can change the active member, so that's not OK. 3504 // FIXME: Add core issue number for the union case. 3505 if (Field->isMutable() && 3506 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3507 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3508 Info.Note(Field->getLocation(), diag::note_declared_at); 3509 return true; 3510 } 3511 3512 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3513 return true; 3514 } 3515 3516 for (auto &BaseSpec : RD->bases()) 3517 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3518 return true; 3519 3520 // All mutable fields were empty, and thus not actually read. 3521 return false; 3522 } 3523 3524 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3525 APValue::LValueBase Base, 3526 bool MutableSubobject = false) { 3527 // A temporary or transient heap allocation we created. 3528 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3529 return true; 3530 3531 switch (Info.IsEvaluatingDecl) { 3532 case EvalInfo::EvaluatingDeclKind::None: 3533 return false; 3534 3535 case EvalInfo::EvaluatingDeclKind::Ctor: 3536 // The variable whose initializer we're evaluating. 3537 if (Info.EvaluatingDecl == Base) 3538 return true; 3539 3540 // A temporary lifetime-extended by the variable whose initializer we're 3541 // evaluating. 3542 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3543 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3544 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3545 return false; 3546 3547 case EvalInfo::EvaluatingDeclKind::Dtor: 3548 // C++2a [expr.const]p6: 3549 // [during constant destruction] the lifetime of a and its non-mutable 3550 // subobjects (but not its mutable subobjects) [are] considered to start 3551 // within e. 3552 if (MutableSubobject || Base != Info.EvaluatingDecl) 3553 return false; 3554 // FIXME: We can meaningfully extend this to cover non-const objects, but 3555 // we will need special handling: we should be able to access only 3556 // subobjects of such objects that are themselves declared const. 3557 QualType T = getType(Base); 3558 return T.isConstQualified() || T->isReferenceType(); 3559 } 3560 3561 llvm_unreachable("unknown evaluating decl kind"); 3562 } 3563 3564 namespace { 3565 /// A handle to a complete object (an object that is not a subobject of 3566 /// another object). 3567 struct CompleteObject { 3568 /// The identity of the object. 3569 APValue::LValueBase Base; 3570 /// The value of the complete object. 3571 APValue *Value; 3572 /// The type of the complete object. 3573 QualType Type; 3574 3575 CompleteObject() : Value(nullptr) {} 3576 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3577 : Base(Base), Value(Value), Type(Type) {} 3578 3579 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3580 // If this isn't a "real" access (eg, if it's just accessing the type 3581 // info), allow it. We assume the type doesn't change dynamically for 3582 // subobjects of constexpr objects (even though we'd hit UB here if it 3583 // did). FIXME: Is this right? 3584 if (!isAnyAccess(AK)) 3585 return true; 3586 3587 // In C++14 onwards, it is permitted to read a mutable member whose 3588 // lifetime began within the evaluation. 3589 // FIXME: Should we also allow this in C++11? 3590 if (!Info.getLangOpts().CPlusPlus14) 3591 return false; 3592 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3593 } 3594 3595 explicit operator bool() const { return !Type.isNull(); } 3596 }; 3597 } // end anonymous namespace 3598 3599 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3600 bool IsMutable = false) { 3601 // C++ [basic.type.qualifier]p1: 3602 // - A const object is an object of type const T or a non-mutable subobject 3603 // of a const object. 3604 if (ObjType.isConstQualified() && !IsMutable) 3605 SubobjType.addConst(); 3606 // - A volatile object is an object of type const T or a subobject of a 3607 // volatile object. 3608 if (ObjType.isVolatileQualified()) 3609 SubobjType.addVolatile(); 3610 return SubobjType; 3611 } 3612 3613 /// Find the designated sub-object of an rvalue. 3614 template<typename SubobjectHandler> 3615 typename SubobjectHandler::result_type 3616 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3617 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3618 if (Sub.Invalid) 3619 // A diagnostic will have already been produced. 3620 return handler.failed(); 3621 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3622 if (Info.getLangOpts().CPlusPlus11) 3623 Info.FFDiag(E, Sub.isOnePastTheEnd() 3624 ? diag::note_constexpr_access_past_end 3625 : diag::note_constexpr_access_unsized_array) 3626 << handler.AccessKind; 3627 else 3628 Info.FFDiag(E); 3629 return handler.failed(); 3630 } 3631 3632 APValue *O = Obj.Value; 3633 QualType ObjType = Obj.Type; 3634 const FieldDecl *LastField = nullptr; 3635 const FieldDecl *VolatileField = nullptr; 3636 3637 // Walk the designator's path to find the subobject. 3638 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3639 // Reading an indeterminate value is undefined, but assigning over one is OK. 3640 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3641 (O->isIndeterminate() && 3642 !isValidIndeterminateAccess(handler.AccessKind))) { 3643 if (!Info.checkingPotentialConstantExpression()) 3644 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3645 << handler.AccessKind << O->isIndeterminate(); 3646 return handler.failed(); 3647 } 3648 3649 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3650 // const and volatile semantics are not applied on an object under 3651 // {con,de}struction. 3652 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3653 ObjType->isRecordType() && 3654 Info.isEvaluatingCtorDtor( 3655 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3656 Sub.Entries.begin() + I)) != 3657 ConstructionPhase::None) { 3658 ObjType = Info.Ctx.getCanonicalType(ObjType); 3659 ObjType.removeLocalConst(); 3660 ObjType.removeLocalVolatile(); 3661 } 3662 3663 // If this is our last pass, check that the final object type is OK. 3664 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3665 // Accesses to volatile objects are prohibited. 3666 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3667 if (Info.getLangOpts().CPlusPlus) { 3668 int DiagKind; 3669 SourceLocation Loc; 3670 const NamedDecl *Decl = nullptr; 3671 if (VolatileField) { 3672 DiagKind = 2; 3673 Loc = VolatileField->getLocation(); 3674 Decl = VolatileField; 3675 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3676 DiagKind = 1; 3677 Loc = VD->getLocation(); 3678 Decl = VD; 3679 } else { 3680 DiagKind = 0; 3681 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3682 Loc = E->getExprLoc(); 3683 } 3684 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3685 << handler.AccessKind << DiagKind << Decl; 3686 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3687 } else { 3688 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3689 } 3690 return handler.failed(); 3691 } 3692 3693 // If we are reading an object of class type, there may still be more 3694 // things we need to check: if there are any mutable subobjects, we 3695 // cannot perform this read. (This only happens when performing a trivial 3696 // copy or assignment.) 3697 if (ObjType->isRecordType() && 3698 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3699 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3700 return handler.failed(); 3701 } 3702 3703 if (I == N) { 3704 if (!handler.found(*O, ObjType)) 3705 return false; 3706 3707 // If we modified a bit-field, truncate it to the right width. 3708 if (isModification(handler.AccessKind) && 3709 LastField && LastField->isBitField() && 3710 !truncateBitfieldValue(Info, E, *O, LastField)) 3711 return false; 3712 3713 return true; 3714 } 3715 3716 LastField = nullptr; 3717 if (ObjType->isArrayType()) { 3718 // Next subobject is an array element. 3719 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3720 assert(CAT && "vla in literal type?"); 3721 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3722 if (CAT->getSize().ule(Index)) { 3723 // Note, it should not be possible to form a pointer with a valid 3724 // designator which points more than one past the end of the array. 3725 if (Info.getLangOpts().CPlusPlus11) 3726 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3727 << handler.AccessKind; 3728 else 3729 Info.FFDiag(E); 3730 return handler.failed(); 3731 } 3732 3733 ObjType = CAT->getElementType(); 3734 3735 if (O->getArrayInitializedElts() > Index) 3736 O = &O->getArrayInitializedElt(Index); 3737 else if (!isRead(handler.AccessKind)) { 3738 expandArray(*O, Index); 3739 O = &O->getArrayInitializedElt(Index); 3740 } else 3741 O = &O->getArrayFiller(); 3742 } else if (ObjType->isAnyComplexType()) { 3743 // Next subobject is a complex number. 3744 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3745 if (Index > 1) { 3746 if (Info.getLangOpts().CPlusPlus11) 3747 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3748 << handler.AccessKind; 3749 else 3750 Info.FFDiag(E); 3751 return handler.failed(); 3752 } 3753 3754 ObjType = getSubobjectType( 3755 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3756 3757 assert(I == N - 1 && "extracting subobject of scalar?"); 3758 if (O->isComplexInt()) { 3759 return handler.found(Index ? O->getComplexIntImag() 3760 : O->getComplexIntReal(), ObjType); 3761 } else { 3762 assert(O->isComplexFloat()); 3763 return handler.found(Index ? O->getComplexFloatImag() 3764 : O->getComplexFloatReal(), ObjType); 3765 } 3766 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3767 if (Field->isMutable() && 3768 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3769 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3770 << handler.AccessKind << Field; 3771 Info.Note(Field->getLocation(), diag::note_declared_at); 3772 return handler.failed(); 3773 } 3774 3775 // Next subobject is a class, struct or union field. 3776 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3777 if (RD->isUnion()) { 3778 const FieldDecl *UnionField = O->getUnionField(); 3779 if (!UnionField || 3780 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3781 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3782 // Placement new onto an inactive union member makes it active. 3783 O->setUnion(Field, APValue()); 3784 } else { 3785 // FIXME: If O->getUnionValue() is absent, report that there's no 3786 // active union member rather than reporting the prior active union 3787 // member. We'll need to fix nullptr_t to not use APValue() as its 3788 // representation first. 3789 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3790 << handler.AccessKind << Field << !UnionField << UnionField; 3791 return handler.failed(); 3792 } 3793 } 3794 O = &O->getUnionValue(); 3795 } else 3796 O = &O->getStructField(Field->getFieldIndex()); 3797 3798 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3799 LastField = Field; 3800 if (Field->getType().isVolatileQualified()) 3801 VolatileField = Field; 3802 } else { 3803 // Next subobject is a base class. 3804 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3805 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3806 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3807 3808 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3809 } 3810 } 3811 } 3812 3813 namespace { 3814 struct ExtractSubobjectHandler { 3815 EvalInfo &Info; 3816 const Expr *E; 3817 APValue &Result; 3818 const AccessKinds AccessKind; 3819 3820 typedef bool result_type; 3821 bool failed() { return false; } 3822 bool found(APValue &Subobj, QualType SubobjType) { 3823 Result = Subobj; 3824 if (AccessKind == AK_ReadObjectRepresentation) 3825 return true; 3826 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3827 } 3828 bool found(APSInt &Value, QualType SubobjType) { 3829 Result = APValue(Value); 3830 return true; 3831 } 3832 bool found(APFloat &Value, QualType SubobjType) { 3833 Result = APValue(Value); 3834 return true; 3835 } 3836 }; 3837 } // end anonymous namespace 3838 3839 /// Extract the designated sub-object of an rvalue. 3840 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3841 const CompleteObject &Obj, 3842 const SubobjectDesignator &Sub, APValue &Result, 3843 AccessKinds AK = AK_Read) { 3844 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3845 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3846 return findSubobject(Info, E, Obj, Sub, Handler); 3847 } 3848 3849 namespace { 3850 struct ModifySubobjectHandler { 3851 EvalInfo &Info; 3852 APValue &NewVal; 3853 const Expr *E; 3854 3855 typedef bool result_type; 3856 static const AccessKinds AccessKind = AK_Assign; 3857 3858 bool checkConst(QualType QT) { 3859 // Assigning to a const object has undefined behavior. 3860 if (QT.isConstQualified()) { 3861 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3862 return false; 3863 } 3864 return true; 3865 } 3866 3867 bool failed() { return false; } 3868 bool found(APValue &Subobj, QualType SubobjType) { 3869 if (!checkConst(SubobjType)) 3870 return false; 3871 // We've been given ownership of NewVal, so just swap it in. 3872 Subobj.swap(NewVal); 3873 return true; 3874 } 3875 bool found(APSInt &Value, QualType SubobjType) { 3876 if (!checkConst(SubobjType)) 3877 return false; 3878 if (!NewVal.isInt()) { 3879 // Maybe trying to write a cast pointer value into a complex? 3880 Info.FFDiag(E); 3881 return false; 3882 } 3883 Value = NewVal.getInt(); 3884 return true; 3885 } 3886 bool found(APFloat &Value, QualType SubobjType) { 3887 if (!checkConst(SubobjType)) 3888 return false; 3889 Value = NewVal.getFloat(); 3890 return true; 3891 } 3892 }; 3893 } // end anonymous namespace 3894 3895 const AccessKinds ModifySubobjectHandler::AccessKind; 3896 3897 /// Update the designated sub-object of an rvalue to the given value. 3898 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3899 const CompleteObject &Obj, 3900 const SubobjectDesignator &Sub, 3901 APValue &NewVal) { 3902 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3903 return findSubobject(Info, E, Obj, Sub, Handler); 3904 } 3905 3906 /// Find the position where two subobject designators diverge, or equivalently 3907 /// the length of the common initial subsequence. 3908 static unsigned FindDesignatorMismatch(QualType ObjType, 3909 const SubobjectDesignator &A, 3910 const SubobjectDesignator &B, 3911 bool &WasArrayIndex) { 3912 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3913 for (/**/; I != N; ++I) { 3914 if (!ObjType.isNull() && 3915 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3916 // Next subobject is an array element. 3917 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3918 WasArrayIndex = true; 3919 return I; 3920 } 3921 if (ObjType->isAnyComplexType()) 3922 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3923 else 3924 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3925 } else { 3926 if (A.Entries[I].getAsBaseOrMember() != 3927 B.Entries[I].getAsBaseOrMember()) { 3928 WasArrayIndex = false; 3929 return I; 3930 } 3931 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3932 // Next subobject is a field. 3933 ObjType = FD->getType(); 3934 else 3935 // Next subobject is a base class. 3936 ObjType = QualType(); 3937 } 3938 } 3939 WasArrayIndex = false; 3940 return I; 3941 } 3942 3943 /// Determine whether the given subobject designators refer to elements of the 3944 /// same array object. 3945 static bool AreElementsOfSameArray(QualType ObjType, 3946 const SubobjectDesignator &A, 3947 const SubobjectDesignator &B) { 3948 if (A.Entries.size() != B.Entries.size()) 3949 return false; 3950 3951 bool IsArray = A.MostDerivedIsArrayElement; 3952 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3953 // A is a subobject of the array element. 3954 return false; 3955 3956 // If A (and B) designates an array element, the last entry will be the array 3957 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3958 // of length 1' case, and the entire path must match. 3959 bool WasArrayIndex; 3960 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3961 return CommonLength >= A.Entries.size() - IsArray; 3962 } 3963 3964 /// Find the complete object to which an LValue refers. 3965 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3966 AccessKinds AK, const LValue &LVal, 3967 QualType LValType) { 3968 if (LVal.InvalidBase) { 3969 Info.FFDiag(E); 3970 return CompleteObject(); 3971 } 3972 3973 if (!LVal.Base) { 3974 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3975 return CompleteObject(); 3976 } 3977 3978 CallStackFrame *Frame = nullptr; 3979 unsigned Depth = 0; 3980 if (LVal.getLValueCallIndex()) { 3981 std::tie(Frame, Depth) = 3982 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3983 if (!Frame) { 3984 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3985 << AK << LVal.Base.is<const ValueDecl*>(); 3986 NoteLValueLocation(Info, LVal.Base); 3987 return CompleteObject(); 3988 } 3989 } 3990 3991 bool IsAccess = isAnyAccess(AK); 3992 3993 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3994 // is not a constant expression (even if the object is non-volatile). We also 3995 // apply this rule to C++98, in order to conform to the expected 'volatile' 3996 // semantics. 3997 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3998 if (Info.getLangOpts().CPlusPlus) 3999 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 4000 << AK << LValType; 4001 else 4002 Info.FFDiag(E); 4003 return CompleteObject(); 4004 } 4005 4006 // Compute value storage location and type of base object. 4007 APValue *BaseVal = nullptr; 4008 QualType BaseType = getType(LVal.Base); 4009 4010 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 4011 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4012 // This is the object whose initializer we're evaluating, so its lifetime 4013 // started in the current evaluation. 4014 BaseVal = Info.EvaluatingDeclValue; 4015 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 4016 // Allow reading from a GUID declaration. 4017 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 4018 if (isModification(AK)) { 4019 // All the remaining cases do not permit modification of the object. 4020 Info.FFDiag(E, diag::note_constexpr_modify_global); 4021 return CompleteObject(); 4022 } 4023 APValue &V = GD->getAsAPValue(); 4024 if (V.isAbsent()) { 4025 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4026 << GD->getType(); 4027 return CompleteObject(); 4028 } 4029 return CompleteObject(LVal.Base, &V, GD->getType()); 4030 } 4031 4032 // Allow reading the APValue from an UnnamedGlobalConstantDecl. 4033 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) { 4034 if (isModification(AK)) { 4035 Info.FFDiag(E, diag::note_constexpr_modify_global); 4036 return CompleteObject(); 4037 } 4038 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), 4039 GCD->getType()); 4040 } 4041 4042 // Allow reading from template parameter objects. 4043 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4044 if (isModification(AK)) { 4045 Info.FFDiag(E, diag::note_constexpr_modify_global); 4046 return CompleteObject(); 4047 } 4048 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4049 TPO->getType()); 4050 } 4051 4052 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4053 // In C++11, constexpr, non-volatile variables initialized with constant 4054 // expressions are constant expressions too. Inside constexpr functions, 4055 // parameters are constant expressions even if they're non-const. 4056 // In C++1y, objects local to a constant expression (those with a Frame) are 4057 // both readable and writable inside constant expressions. 4058 // In C, such things can also be folded, although they are not ICEs. 4059 const VarDecl *VD = dyn_cast<VarDecl>(D); 4060 if (VD) { 4061 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4062 VD = VDef; 4063 } 4064 if (!VD || VD->isInvalidDecl()) { 4065 Info.FFDiag(E); 4066 return CompleteObject(); 4067 } 4068 4069 bool IsConstant = BaseType.isConstant(Info.Ctx); 4070 4071 // Unless we're looking at a local variable or argument in a constexpr call, 4072 // the variable we're reading must be const. 4073 if (!Frame) { 4074 if (IsAccess && isa<ParmVarDecl>(VD)) { 4075 // Access of a parameter that's not associated with a frame isn't going 4076 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4077 // suitable diagnostic. 4078 } else if (Info.getLangOpts().CPlusPlus14 && 4079 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4080 // OK, we can read and modify an object if we're in the process of 4081 // evaluating its initializer, because its lifetime began in this 4082 // evaluation. 4083 } else if (isModification(AK)) { 4084 // All the remaining cases do not permit modification of the object. 4085 Info.FFDiag(E, diag::note_constexpr_modify_global); 4086 return CompleteObject(); 4087 } else if (VD->isConstexpr()) { 4088 // OK, we can read this variable. 4089 } else if (BaseType->isIntegralOrEnumerationType()) { 4090 if (!IsConstant) { 4091 if (!IsAccess) 4092 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4093 if (Info.getLangOpts().CPlusPlus) { 4094 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4095 Info.Note(VD->getLocation(), diag::note_declared_at); 4096 } else { 4097 Info.FFDiag(E); 4098 } 4099 return CompleteObject(); 4100 } 4101 } else if (!IsAccess) { 4102 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4103 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4104 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4105 // This variable might end up being constexpr. Don't diagnose it yet. 4106 } else if (IsConstant) { 4107 // Keep evaluating to see what we can do. In particular, we support 4108 // folding of const floating-point types, in order to make static const 4109 // data members of such types (supported as an extension) more useful. 4110 if (Info.getLangOpts().CPlusPlus) { 4111 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4112 ? diag::note_constexpr_ltor_non_constexpr 4113 : diag::note_constexpr_ltor_non_integral, 1) 4114 << VD << BaseType; 4115 Info.Note(VD->getLocation(), diag::note_declared_at); 4116 } else { 4117 Info.CCEDiag(E); 4118 } 4119 } else { 4120 // Never allow reading a non-const value. 4121 if (Info.getLangOpts().CPlusPlus) { 4122 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4123 ? diag::note_constexpr_ltor_non_constexpr 4124 : diag::note_constexpr_ltor_non_integral, 1) 4125 << VD << BaseType; 4126 Info.Note(VD->getLocation(), diag::note_declared_at); 4127 } else { 4128 Info.FFDiag(E); 4129 } 4130 return CompleteObject(); 4131 } 4132 } 4133 4134 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4135 return CompleteObject(); 4136 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4137 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4138 if (!Alloc) { 4139 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4140 return CompleteObject(); 4141 } 4142 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4143 LVal.Base.getDynamicAllocType()); 4144 } else { 4145 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4146 4147 if (!Frame) { 4148 if (const MaterializeTemporaryExpr *MTE = 4149 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4150 assert(MTE->getStorageDuration() == SD_Static && 4151 "should have a frame for a non-global materialized temporary"); 4152 4153 // C++20 [expr.const]p4: [DR2126] 4154 // An object or reference is usable in constant expressions if it is 4155 // - a temporary object of non-volatile const-qualified literal type 4156 // whose lifetime is extended to that of a variable that is usable 4157 // in constant expressions 4158 // 4159 // C++20 [expr.const]p5: 4160 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4161 // - a non-volatile glvalue that refers to an object that is usable 4162 // in constant expressions, or 4163 // - a non-volatile glvalue of literal type that refers to a 4164 // non-volatile object whose lifetime began within the evaluation 4165 // of E; 4166 // 4167 // C++11 misses the 'began within the evaluation of e' check and 4168 // instead allows all temporaries, including things like: 4169 // int &&r = 1; 4170 // int x = ++r; 4171 // constexpr int k = r; 4172 // Therefore we use the C++14-onwards rules in C++11 too. 4173 // 4174 // Note that temporaries whose lifetimes began while evaluating a 4175 // variable's constructor are not usable while evaluating the 4176 // corresponding destructor, not even if they're of const-qualified 4177 // types. 4178 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4179 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4180 if (!IsAccess) 4181 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4182 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4183 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4184 return CompleteObject(); 4185 } 4186 4187 BaseVal = MTE->getOrCreateValue(false); 4188 assert(BaseVal && "got reference to unevaluated temporary"); 4189 } else { 4190 if (!IsAccess) 4191 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4192 APValue Val; 4193 LVal.moveInto(Val); 4194 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4195 << AK 4196 << Val.getAsString(Info.Ctx, 4197 Info.Ctx.getLValueReferenceType(LValType)); 4198 NoteLValueLocation(Info, LVal.Base); 4199 return CompleteObject(); 4200 } 4201 } else { 4202 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4203 assert(BaseVal && "missing value for temporary"); 4204 } 4205 } 4206 4207 // In C++14, we can't safely access any mutable state when we might be 4208 // evaluating after an unmodeled side effect. Parameters are modeled as state 4209 // in the caller, but aren't visible once the call returns, so they can be 4210 // modified in a speculatively-evaluated call. 4211 // 4212 // FIXME: Not all local state is mutable. Allow local constant subobjects 4213 // to be read here (but take care with 'mutable' fields). 4214 unsigned VisibleDepth = Depth; 4215 if (llvm::isa_and_nonnull<ParmVarDecl>( 4216 LVal.Base.dyn_cast<const ValueDecl *>())) 4217 ++VisibleDepth; 4218 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4219 Info.EvalStatus.HasSideEffects) || 4220 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4221 return CompleteObject(); 4222 4223 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4224 } 4225 4226 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4227 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4228 /// glvalue referred to by an entity of reference type. 4229 /// 4230 /// \param Info - Information about the ongoing evaluation. 4231 /// \param Conv - The expression for which we are performing the conversion. 4232 /// Used for diagnostics. 4233 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4234 /// case of a non-class type). 4235 /// \param LVal - The glvalue on which we are attempting to perform this action. 4236 /// \param RVal - The produced value will be placed here. 4237 /// \param WantObjectRepresentation - If true, we're looking for the object 4238 /// representation rather than the value, and in particular, 4239 /// there is no requirement that the result be fully initialized. 4240 static bool 4241 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4242 const LValue &LVal, APValue &RVal, 4243 bool WantObjectRepresentation = false) { 4244 if (LVal.Designator.Invalid) 4245 return false; 4246 4247 // Check for special cases where there is no existing APValue to look at. 4248 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4249 4250 AccessKinds AK = 4251 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4252 4253 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4254 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4255 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4256 // initializer until now for such expressions. Such an expression can't be 4257 // an ICE in C, so this only matters for fold. 4258 if (Type.isVolatileQualified()) { 4259 Info.FFDiag(Conv); 4260 return false; 4261 } 4262 APValue Lit; 4263 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4264 return false; 4265 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4266 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4267 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4268 // Special-case character extraction so we don't have to construct an 4269 // APValue for the whole string. 4270 assert(LVal.Designator.Entries.size() <= 1 && 4271 "Can only read characters from string literals"); 4272 if (LVal.Designator.Entries.empty()) { 4273 // Fail for now for LValue to RValue conversion of an array. 4274 // (This shouldn't show up in C/C++, but it could be triggered by a 4275 // weird EvaluateAsRValue call from a tool.) 4276 Info.FFDiag(Conv); 4277 return false; 4278 } 4279 if (LVal.Designator.isOnePastTheEnd()) { 4280 if (Info.getLangOpts().CPlusPlus11) 4281 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4282 else 4283 Info.FFDiag(Conv); 4284 return false; 4285 } 4286 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4287 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4288 return true; 4289 } 4290 } 4291 4292 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4293 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4294 } 4295 4296 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4297 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4298 QualType LValType, APValue &Val) { 4299 if (LVal.Designator.Invalid) 4300 return false; 4301 4302 if (!Info.getLangOpts().CPlusPlus14) { 4303 Info.FFDiag(E); 4304 return false; 4305 } 4306 4307 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4308 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4309 } 4310 4311 namespace { 4312 struct CompoundAssignSubobjectHandler { 4313 EvalInfo &Info; 4314 const CompoundAssignOperator *E; 4315 QualType PromotedLHSType; 4316 BinaryOperatorKind Opcode; 4317 const APValue &RHS; 4318 4319 static const AccessKinds AccessKind = AK_Assign; 4320 4321 typedef bool result_type; 4322 4323 bool checkConst(QualType QT) { 4324 // Assigning to a const object has undefined behavior. 4325 if (QT.isConstQualified()) { 4326 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4327 return false; 4328 } 4329 return true; 4330 } 4331 4332 bool failed() { return false; } 4333 bool found(APValue &Subobj, QualType SubobjType) { 4334 switch (Subobj.getKind()) { 4335 case APValue::Int: 4336 return found(Subobj.getInt(), SubobjType); 4337 case APValue::Float: 4338 return found(Subobj.getFloat(), SubobjType); 4339 case APValue::ComplexInt: 4340 case APValue::ComplexFloat: 4341 // FIXME: Implement complex compound assignment. 4342 Info.FFDiag(E); 4343 return false; 4344 case APValue::LValue: 4345 return foundPointer(Subobj, SubobjType); 4346 case APValue::Vector: 4347 return foundVector(Subobj, SubobjType); 4348 default: 4349 // FIXME: can this happen? 4350 Info.FFDiag(E); 4351 return false; 4352 } 4353 } 4354 4355 bool foundVector(APValue &Value, QualType SubobjType) { 4356 if (!checkConst(SubobjType)) 4357 return false; 4358 4359 if (!SubobjType->isVectorType()) { 4360 Info.FFDiag(E); 4361 return false; 4362 } 4363 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4364 } 4365 4366 bool found(APSInt &Value, QualType SubobjType) { 4367 if (!checkConst(SubobjType)) 4368 return false; 4369 4370 if (!SubobjType->isIntegerType()) { 4371 // We don't support compound assignment on integer-cast-to-pointer 4372 // values. 4373 Info.FFDiag(E); 4374 return false; 4375 } 4376 4377 if (RHS.isInt()) { 4378 APSInt LHS = 4379 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4380 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4381 return false; 4382 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4383 return true; 4384 } else if (RHS.isFloat()) { 4385 const FPOptions FPO = E->getFPFeaturesInEffect( 4386 Info.Ctx.getLangOpts()); 4387 APFloat FValue(0.0); 4388 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4389 PromotedLHSType, FValue) && 4390 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4391 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4392 Value); 4393 } 4394 4395 Info.FFDiag(E); 4396 return false; 4397 } 4398 bool found(APFloat &Value, QualType SubobjType) { 4399 return checkConst(SubobjType) && 4400 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4401 Value) && 4402 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4403 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4404 } 4405 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4406 if (!checkConst(SubobjType)) 4407 return false; 4408 4409 QualType PointeeType; 4410 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4411 PointeeType = PT->getPointeeType(); 4412 4413 if (PointeeType.isNull() || !RHS.isInt() || 4414 (Opcode != BO_Add && Opcode != BO_Sub)) { 4415 Info.FFDiag(E); 4416 return false; 4417 } 4418 4419 APSInt Offset = RHS.getInt(); 4420 if (Opcode == BO_Sub) 4421 negateAsSigned(Offset); 4422 4423 LValue LVal; 4424 LVal.setFrom(Info.Ctx, Subobj); 4425 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4426 return false; 4427 LVal.moveInto(Subobj); 4428 return true; 4429 } 4430 }; 4431 } // end anonymous namespace 4432 4433 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4434 4435 /// Perform a compound assignment of LVal <op>= RVal. 4436 static bool handleCompoundAssignment(EvalInfo &Info, 4437 const CompoundAssignOperator *E, 4438 const LValue &LVal, QualType LValType, 4439 QualType PromotedLValType, 4440 BinaryOperatorKind Opcode, 4441 const APValue &RVal) { 4442 if (LVal.Designator.Invalid) 4443 return false; 4444 4445 if (!Info.getLangOpts().CPlusPlus14) { 4446 Info.FFDiag(E); 4447 return false; 4448 } 4449 4450 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4451 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4452 RVal }; 4453 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4454 } 4455 4456 namespace { 4457 struct IncDecSubobjectHandler { 4458 EvalInfo &Info; 4459 const UnaryOperator *E; 4460 AccessKinds AccessKind; 4461 APValue *Old; 4462 4463 typedef bool result_type; 4464 4465 bool checkConst(QualType QT) { 4466 // Assigning to a const object has undefined behavior. 4467 if (QT.isConstQualified()) { 4468 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4469 return false; 4470 } 4471 return true; 4472 } 4473 4474 bool failed() { return false; } 4475 bool found(APValue &Subobj, QualType SubobjType) { 4476 // Stash the old value. Also clear Old, so we don't clobber it later 4477 // if we're post-incrementing a complex. 4478 if (Old) { 4479 *Old = Subobj; 4480 Old = nullptr; 4481 } 4482 4483 switch (Subobj.getKind()) { 4484 case APValue::Int: 4485 return found(Subobj.getInt(), SubobjType); 4486 case APValue::Float: 4487 return found(Subobj.getFloat(), SubobjType); 4488 case APValue::ComplexInt: 4489 return found(Subobj.getComplexIntReal(), 4490 SubobjType->castAs<ComplexType>()->getElementType() 4491 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4492 case APValue::ComplexFloat: 4493 return found(Subobj.getComplexFloatReal(), 4494 SubobjType->castAs<ComplexType>()->getElementType() 4495 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4496 case APValue::LValue: 4497 return foundPointer(Subobj, SubobjType); 4498 default: 4499 // FIXME: can this happen? 4500 Info.FFDiag(E); 4501 return false; 4502 } 4503 } 4504 bool found(APSInt &Value, QualType SubobjType) { 4505 if (!checkConst(SubobjType)) 4506 return false; 4507 4508 if (!SubobjType->isIntegerType()) { 4509 // We don't support increment / decrement on integer-cast-to-pointer 4510 // values. 4511 Info.FFDiag(E); 4512 return false; 4513 } 4514 4515 if (Old) *Old = APValue(Value); 4516 4517 // bool arithmetic promotes to int, and the conversion back to bool 4518 // doesn't reduce mod 2^n, so special-case it. 4519 if (SubobjType->isBooleanType()) { 4520 if (AccessKind == AK_Increment) 4521 Value = 1; 4522 else 4523 Value = !Value; 4524 return true; 4525 } 4526 4527 bool WasNegative = Value.isNegative(); 4528 if (AccessKind == AK_Increment) { 4529 ++Value; 4530 4531 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4532 APSInt ActualValue(Value, /*IsUnsigned*/true); 4533 return HandleOverflow(Info, E, ActualValue, SubobjType); 4534 } 4535 } else { 4536 --Value; 4537 4538 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4539 unsigned BitWidth = Value.getBitWidth(); 4540 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4541 ActualValue.setBit(BitWidth); 4542 return HandleOverflow(Info, E, ActualValue, SubobjType); 4543 } 4544 } 4545 return true; 4546 } 4547 bool found(APFloat &Value, QualType SubobjType) { 4548 if (!checkConst(SubobjType)) 4549 return false; 4550 4551 if (Old) *Old = APValue(Value); 4552 4553 APFloat One(Value.getSemantics(), 1); 4554 if (AccessKind == AK_Increment) 4555 Value.add(One, APFloat::rmNearestTiesToEven); 4556 else 4557 Value.subtract(One, APFloat::rmNearestTiesToEven); 4558 return true; 4559 } 4560 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4561 if (!checkConst(SubobjType)) 4562 return false; 4563 4564 QualType PointeeType; 4565 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4566 PointeeType = PT->getPointeeType(); 4567 else { 4568 Info.FFDiag(E); 4569 return false; 4570 } 4571 4572 LValue LVal; 4573 LVal.setFrom(Info.Ctx, Subobj); 4574 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4575 AccessKind == AK_Increment ? 1 : -1)) 4576 return false; 4577 LVal.moveInto(Subobj); 4578 return true; 4579 } 4580 }; 4581 } // end anonymous namespace 4582 4583 /// Perform an increment or decrement on LVal. 4584 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4585 QualType LValType, bool IsIncrement, APValue *Old) { 4586 if (LVal.Designator.Invalid) 4587 return false; 4588 4589 if (!Info.getLangOpts().CPlusPlus14) { 4590 Info.FFDiag(E); 4591 return false; 4592 } 4593 4594 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4595 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4596 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4597 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4598 } 4599 4600 /// Build an lvalue for the object argument of a member function call. 4601 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4602 LValue &This) { 4603 if (Object->getType()->isPointerType() && Object->isPRValue()) 4604 return EvaluatePointer(Object, This, Info); 4605 4606 if (Object->isGLValue()) 4607 return EvaluateLValue(Object, This, Info); 4608 4609 if (Object->getType()->isLiteralType(Info.Ctx)) 4610 return EvaluateTemporary(Object, This, Info); 4611 4612 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4613 return false; 4614 } 4615 4616 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4617 /// lvalue referring to the result. 4618 /// 4619 /// \param Info - Information about the ongoing evaluation. 4620 /// \param LV - An lvalue referring to the base of the member pointer. 4621 /// \param RHS - The member pointer expression. 4622 /// \param IncludeMember - Specifies whether the member itself is included in 4623 /// the resulting LValue subobject designator. This is not possible when 4624 /// creating a bound member function. 4625 /// \return The field or method declaration to which the member pointer refers, 4626 /// or 0 if evaluation fails. 4627 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4628 QualType LVType, 4629 LValue &LV, 4630 const Expr *RHS, 4631 bool IncludeMember = true) { 4632 MemberPtr MemPtr; 4633 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4634 return nullptr; 4635 4636 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4637 // member value, the behavior is undefined. 4638 if (!MemPtr.getDecl()) { 4639 // FIXME: Specific diagnostic. 4640 Info.FFDiag(RHS); 4641 return nullptr; 4642 } 4643 4644 if (MemPtr.isDerivedMember()) { 4645 // This is a member of some derived class. Truncate LV appropriately. 4646 // The end of the derived-to-base path for the base object must match the 4647 // derived-to-base path for the member pointer. 4648 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4649 LV.Designator.Entries.size()) { 4650 Info.FFDiag(RHS); 4651 return nullptr; 4652 } 4653 unsigned PathLengthToMember = 4654 LV.Designator.Entries.size() - MemPtr.Path.size(); 4655 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4656 const CXXRecordDecl *LVDecl = getAsBaseClass( 4657 LV.Designator.Entries[PathLengthToMember + I]); 4658 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4659 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4660 Info.FFDiag(RHS); 4661 return nullptr; 4662 } 4663 } 4664 4665 // Truncate the lvalue to the appropriate derived class. 4666 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4667 PathLengthToMember)) 4668 return nullptr; 4669 } else if (!MemPtr.Path.empty()) { 4670 // Extend the LValue path with the member pointer's path. 4671 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4672 MemPtr.Path.size() + IncludeMember); 4673 4674 // Walk down to the appropriate base class. 4675 if (const PointerType *PT = LVType->getAs<PointerType>()) 4676 LVType = PT->getPointeeType(); 4677 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4678 assert(RD && "member pointer access on non-class-type expression"); 4679 // The first class in the path is that of the lvalue. 4680 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4681 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4682 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4683 return nullptr; 4684 RD = Base; 4685 } 4686 // Finally cast to the class containing the member. 4687 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4688 MemPtr.getContainingRecord())) 4689 return nullptr; 4690 } 4691 4692 // Add the member. Note that we cannot build bound member functions here. 4693 if (IncludeMember) { 4694 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4695 if (!HandleLValueMember(Info, RHS, LV, FD)) 4696 return nullptr; 4697 } else if (const IndirectFieldDecl *IFD = 4698 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4699 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4700 return nullptr; 4701 } else { 4702 llvm_unreachable("can't construct reference to bound member function"); 4703 } 4704 } 4705 4706 return MemPtr.getDecl(); 4707 } 4708 4709 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4710 const BinaryOperator *BO, 4711 LValue &LV, 4712 bool IncludeMember = true) { 4713 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4714 4715 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4716 if (Info.noteFailure()) { 4717 MemberPtr MemPtr; 4718 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4719 } 4720 return nullptr; 4721 } 4722 4723 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4724 BO->getRHS(), IncludeMember); 4725 } 4726 4727 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4728 /// the provided lvalue, which currently refers to the base object. 4729 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4730 LValue &Result) { 4731 SubobjectDesignator &D = Result.Designator; 4732 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4733 return false; 4734 4735 QualType TargetQT = E->getType(); 4736 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4737 TargetQT = PT->getPointeeType(); 4738 4739 // Check this cast lands within the final derived-to-base subobject path. 4740 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4741 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4742 << D.MostDerivedType << TargetQT; 4743 return false; 4744 } 4745 4746 // Check the type of the final cast. We don't need to check the path, 4747 // since a cast can only be formed if the path is unique. 4748 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4749 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4750 const CXXRecordDecl *FinalType; 4751 if (NewEntriesSize == D.MostDerivedPathLength) 4752 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4753 else 4754 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4755 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4756 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4757 << D.MostDerivedType << TargetQT; 4758 return false; 4759 } 4760 4761 // Truncate the lvalue to the appropriate derived class. 4762 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4763 } 4764 4765 /// Get the value to use for a default-initialized object of type T. 4766 /// Return false if it encounters something invalid. 4767 static bool getDefaultInitValue(QualType T, APValue &Result) { 4768 bool Success = true; 4769 if (auto *RD = T->getAsCXXRecordDecl()) { 4770 if (RD->isInvalidDecl()) { 4771 Result = APValue(); 4772 return false; 4773 } 4774 if (RD->isUnion()) { 4775 Result = APValue((const FieldDecl *)nullptr); 4776 return true; 4777 } 4778 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4779 std::distance(RD->field_begin(), RD->field_end())); 4780 4781 unsigned Index = 0; 4782 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4783 End = RD->bases_end(); 4784 I != End; ++I, ++Index) 4785 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4786 4787 for (const auto *I : RD->fields()) { 4788 if (I->isUnnamedBitfield()) 4789 continue; 4790 Success &= getDefaultInitValue(I->getType(), 4791 Result.getStructField(I->getFieldIndex())); 4792 } 4793 return Success; 4794 } 4795 4796 if (auto *AT = 4797 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4798 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4799 if (Result.hasArrayFiller()) 4800 Success &= 4801 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4802 4803 return Success; 4804 } 4805 4806 Result = APValue::IndeterminateValue(); 4807 return true; 4808 } 4809 4810 namespace { 4811 enum EvalStmtResult { 4812 /// Evaluation failed. 4813 ESR_Failed, 4814 /// Hit a 'return' statement. 4815 ESR_Returned, 4816 /// Evaluation succeeded. 4817 ESR_Succeeded, 4818 /// Hit a 'continue' statement. 4819 ESR_Continue, 4820 /// Hit a 'break' statement. 4821 ESR_Break, 4822 /// Still scanning for 'case' or 'default' statement. 4823 ESR_CaseNotFound 4824 }; 4825 } 4826 4827 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4828 // We don't need to evaluate the initializer for a static local. 4829 if (!VD->hasLocalStorage()) 4830 return true; 4831 4832 LValue Result; 4833 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4834 ScopeKind::Block, Result); 4835 4836 const Expr *InitE = VD->getInit(); 4837 if (!InitE) { 4838 if (VD->getType()->isDependentType()) 4839 return Info.noteSideEffect(); 4840 return getDefaultInitValue(VD->getType(), Val); 4841 } 4842 if (InitE->isValueDependent()) 4843 return false; 4844 4845 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4846 // Wipe out any partially-computed value, to allow tracking that this 4847 // evaluation failed. 4848 Val = APValue(); 4849 return false; 4850 } 4851 4852 return true; 4853 } 4854 4855 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4856 bool OK = true; 4857 4858 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4859 OK &= EvaluateVarDecl(Info, VD); 4860 4861 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4862 for (auto *BD : DD->bindings()) 4863 if (auto *VD = BD->getHoldingVar()) 4864 OK &= EvaluateDecl(Info, VD); 4865 4866 return OK; 4867 } 4868 4869 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4870 assert(E->isValueDependent()); 4871 if (Info.noteSideEffect()) 4872 return true; 4873 assert(E->containsErrors() && "valid value-dependent expression should never " 4874 "reach invalid code path."); 4875 return false; 4876 } 4877 4878 /// Evaluate a condition (either a variable declaration or an expression). 4879 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4880 const Expr *Cond, bool &Result) { 4881 if (Cond->isValueDependent()) 4882 return false; 4883 FullExpressionRAII Scope(Info); 4884 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4885 return false; 4886 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4887 return false; 4888 return Scope.destroy(); 4889 } 4890 4891 namespace { 4892 /// A location where the result (returned value) of evaluating a 4893 /// statement should be stored. 4894 struct StmtResult { 4895 /// The APValue that should be filled in with the returned value. 4896 APValue &Value; 4897 /// The location containing the result, if any (used to support RVO). 4898 const LValue *Slot; 4899 }; 4900 4901 struct TempVersionRAII { 4902 CallStackFrame &Frame; 4903 4904 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4905 Frame.pushTempVersion(); 4906 } 4907 4908 ~TempVersionRAII() { 4909 Frame.popTempVersion(); 4910 } 4911 }; 4912 4913 } 4914 4915 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4916 const Stmt *S, 4917 const SwitchCase *SC = nullptr); 4918 4919 /// Evaluate the body of a loop, and translate the result as appropriate. 4920 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4921 const Stmt *Body, 4922 const SwitchCase *Case = nullptr) { 4923 BlockScopeRAII Scope(Info); 4924 4925 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4926 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4927 ESR = ESR_Failed; 4928 4929 switch (ESR) { 4930 case ESR_Break: 4931 return ESR_Succeeded; 4932 case ESR_Succeeded: 4933 case ESR_Continue: 4934 return ESR_Continue; 4935 case ESR_Failed: 4936 case ESR_Returned: 4937 case ESR_CaseNotFound: 4938 return ESR; 4939 } 4940 llvm_unreachable("Invalid EvalStmtResult!"); 4941 } 4942 4943 /// Evaluate a switch statement. 4944 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4945 const SwitchStmt *SS) { 4946 BlockScopeRAII Scope(Info); 4947 4948 // Evaluate the switch condition. 4949 APSInt Value; 4950 { 4951 if (const Stmt *Init = SS->getInit()) { 4952 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4953 if (ESR != ESR_Succeeded) { 4954 if (ESR != ESR_Failed && !Scope.destroy()) 4955 ESR = ESR_Failed; 4956 return ESR; 4957 } 4958 } 4959 4960 FullExpressionRAII CondScope(Info); 4961 if (SS->getConditionVariable() && 4962 !EvaluateDecl(Info, SS->getConditionVariable())) 4963 return ESR_Failed; 4964 if (SS->getCond()->isValueDependent()) { 4965 if (!EvaluateDependentExpr(SS->getCond(), Info)) 4966 return ESR_Failed; 4967 } else { 4968 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4969 return ESR_Failed; 4970 } 4971 if (!CondScope.destroy()) 4972 return ESR_Failed; 4973 } 4974 4975 // Find the switch case corresponding to the value of the condition. 4976 // FIXME: Cache this lookup. 4977 const SwitchCase *Found = nullptr; 4978 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4979 SC = SC->getNextSwitchCase()) { 4980 if (isa<DefaultStmt>(SC)) { 4981 Found = SC; 4982 continue; 4983 } 4984 4985 const CaseStmt *CS = cast<CaseStmt>(SC); 4986 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4987 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4988 : LHS; 4989 if (LHS <= Value && Value <= RHS) { 4990 Found = SC; 4991 break; 4992 } 4993 } 4994 4995 if (!Found) 4996 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4997 4998 // Search the switch body for the switch case and evaluate it from there. 4999 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 5000 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 5001 return ESR_Failed; 5002 5003 switch (ESR) { 5004 case ESR_Break: 5005 return ESR_Succeeded; 5006 case ESR_Succeeded: 5007 case ESR_Continue: 5008 case ESR_Failed: 5009 case ESR_Returned: 5010 return ESR; 5011 case ESR_CaseNotFound: 5012 // This can only happen if the switch case is nested within a statement 5013 // expression. We have no intention of supporting that. 5014 Info.FFDiag(Found->getBeginLoc(), 5015 diag::note_constexpr_stmt_expr_unsupported); 5016 return ESR_Failed; 5017 } 5018 llvm_unreachable("Invalid EvalStmtResult!"); 5019 } 5020 5021 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { 5022 // An expression E is a core constant expression unless the evaluation of E 5023 // would evaluate one of the following: [C++2b] - a control flow that passes 5024 // through a declaration of a variable with static or thread storage duration. 5025 if (VD->isLocalVarDecl() && VD->isStaticLocal()) { 5026 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) 5027 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; 5028 return false; 5029 } 5030 return true; 5031 } 5032 5033 // Evaluate a statement. 5034 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 5035 const Stmt *S, const SwitchCase *Case) { 5036 if (!Info.nextStep(S)) 5037 return ESR_Failed; 5038 5039 // If we're hunting down a 'case' or 'default' label, recurse through 5040 // substatements until we hit the label. 5041 if (Case) { 5042 switch (S->getStmtClass()) { 5043 case Stmt::CompoundStmtClass: 5044 // FIXME: Precompute which substatement of a compound statement we 5045 // would jump to, and go straight there rather than performing a 5046 // linear scan each time. 5047 case Stmt::LabelStmtClass: 5048 case Stmt::AttributedStmtClass: 5049 case Stmt::DoStmtClass: 5050 break; 5051 5052 case Stmt::CaseStmtClass: 5053 case Stmt::DefaultStmtClass: 5054 if (Case == S) 5055 Case = nullptr; 5056 break; 5057 5058 case Stmt::IfStmtClass: { 5059 // FIXME: Precompute which side of an 'if' we would jump to, and go 5060 // straight there rather than scanning both sides. 5061 const IfStmt *IS = cast<IfStmt>(S); 5062 5063 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5064 // preceded by our switch label. 5065 BlockScopeRAII Scope(Info); 5066 5067 // Step into the init statement in case it brings an (uninitialized) 5068 // variable into scope. 5069 if (const Stmt *Init = IS->getInit()) { 5070 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5071 if (ESR != ESR_CaseNotFound) { 5072 assert(ESR != ESR_Succeeded); 5073 return ESR; 5074 } 5075 } 5076 5077 // Condition variable must be initialized if it exists. 5078 // FIXME: We can skip evaluating the body if there's a condition 5079 // variable, as there can't be any case labels within it. 5080 // (The same is true for 'for' statements.) 5081 5082 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5083 if (ESR == ESR_Failed) 5084 return ESR; 5085 if (ESR != ESR_CaseNotFound) 5086 return Scope.destroy() ? ESR : ESR_Failed; 5087 if (!IS->getElse()) 5088 return ESR_CaseNotFound; 5089 5090 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5091 if (ESR == ESR_Failed) 5092 return ESR; 5093 if (ESR != ESR_CaseNotFound) 5094 return Scope.destroy() ? ESR : ESR_Failed; 5095 return ESR_CaseNotFound; 5096 } 5097 5098 case Stmt::WhileStmtClass: { 5099 EvalStmtResult ESR = 5100 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5101 if (ESR != ESR_Continue) 5102 return ESR; 5103 break; 5104 } 5105 5106 case Stmt::ForStmtClass: { 5107 const ForStmt *FS = cast<ForStmt>(S); 5108 BlockScopeRAII Scope(Info); 5109 5110 // Step into the init statement in case it brings an (uninitialized) 5111 // variable into scope. 5112 if (const Stmt *Init = FS->getInit()) { 5113 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5114 if (ESR != ESR_CaseNotFound) { 5115 assert(ESR != ESR_Succeeded); 5116 return ESR; 5117 } 5118 } 5119 5120 EvalStmtResult ESR = 5121 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5122 if (ESR != ESR_Continue) 5123 return ESR; 5124 if (const auto *Inc = FS->getInc()) { 5125 if (Inc->isValueDependent()) { 5126 if (!EvaluateDependentExpr(Inc, Info)) 5127 return ESR_Failed; 5128 } else { 5129 FullExpressionRAII IncScope(Info); 5130 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5131 return ESR_Failed; 5132 } 5133 } 5134 break; 5135 } 5136 5137 case Stmt::DeclStmtClass: { 5138 // Start the lifetime of any uninitialized variables we encounter. They 5139 // might be used by the selected branch of the switch. 5140 const DeclStmt *DS = cast<DeclStmt>(S); 5141 for (const auto *D : DS->decls()) { 5142 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5143 if (!CheckLocalVariableDeclaration(Info, VD)) 5144 return ESR_Failed; 5145 if (VD->hasLocalStorage() && !VD->getInit()) 5146 if (!EvaluateVarDecl(Info, VD)) 5147 return ESR_Failed; 5148 // FIXME: If the variable has initialization that can't be jumped 5149 // over, bail out of any immediately-surrounding compound-statement 5150 // too. There can't be any case labels here. 5151 } 5152 } 5153 return ESR_CaseNotFound; 5154 } 5155 5156 default: 5157 return ESR_CaseNotFound; 5158 } 5159 } 5160 5161 switch (S->getStmtClass()) { 5162 default: 5163 if (const Expr *E = dyn_cast<Expr>(S)) { 5164 if (E->isValueDependent()) { 5165 if (!EvaluateDependentExpr(E, Info)) 5166 return ESR_Failed; 5167 } else { 5168 // Don't bother evaluating beyond an expression-statement which couldn't 5169 // be evaluated. 5170 // FIXME: Do we need the FullExpressionRAII object here? 5171 // VisitExprWithCleanups should create one when necessary. 5172 FullExpressionRAII Scope(Info); 5173 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5174 return ESR_Failed; 5175 } 5176 return ESR_Succeeded; 5177 } 5178 5179 Info.FFDiag(S->getBeginLoc()); 5180 return ESR_Failed; 5181 5182 case Stmt::NullStmtClass: 5183 return ESR_Succeeded; 5184 5185 case Stmt::DeclStmtClass: { 5186 const DeclStmt *DS = cast<DeclStmt>(S); 5187 for (const auto *D : DS->decls()) { 5188 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 5189 if (VD && !CheckLocalVariableDeclaration(Info, VD)) 5190 return ESR_Failed; 5191 // Each declaration initialization is its own full-expression. 5192 FullExpressionRAII Scope(Info); 5193 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5194 return ESR_Failed; 5195 if (!Scope.destroy()) 5196 return ESR_Failed; 5197 } 5198 return ESR_Succeeded; 5199 } 5200 5201 case Stmt::ReturnStmtClass: { 5202 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5203 FullExpressionRAII Scope(Info); 5204 if (RetExpr && RetExpr->isValueDependent()) { 5205 EvaluateDependentExpr(RetExpr, Info); 5206 // We know we returned, but we don't know what the value is. 5207 return ESR_Failed; 5208 } 5209 if (RetExpr && 5210 !(Result.Slot 5211 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5212 : Evaluate(Result.Value, Info, RetExpr))) 5213 return ESR_Failed; 5214 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5215 } 5216 5217 case Stmt::CompoundStmtClass: { 5218 BlockScopeRAII Scope(Info); 5219 5220 const CompoundStmt *CS = cast<CompoundStmt>(S); 5221 for (const auto *BI : CS->body()) { 5222 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5223 if (ESR == ESR_Succeeded) 5224 Case = nullptr; 5225 else if (ESR != ESR_CaseNotFound) { 5226 if (ESR != ESR_Failed && !Scope.destroy()) 5227 return ESR_Failed; 5228 return ESR; 5229 } 5230 } 5231 if (Case) 5232 return ESR_CaseNotFound; 5233 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5234 } 5235 5236 case Stmt::IfStmtClass: { 5237 const IfStmt *IS = cast<IfStmt>(S); 5238 5239 // Evaluate the condition, as either a var decl or as an expression. 5240 BlockScopeRAII Scope(Info); 5241 if (const Stmt *Init = IS->getInit()) { 5242 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5243 if (ESR != ESR_Succeeded) { 5244 if (ESR != ESR_Failed && !Scope.destroy()) 5245 return ESR_Failed; 5246 return ESR; 5247 } 5248 } 5249 bool Cond; 5250 if (IS->isConsteval()) 5251 Cond = IS->isNonNegatedConsteval(); 5252 else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), 5253 Cond)) 5254 return ESR_Failed; 5255 5256 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5257 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5258 if (ESR != ESR_Succeeded) { 5259 if (ESR != ESR_Failed && !Scope.destroy()) 5260 return ESR_Failed; 5261 return ESR; 5262 } 5263 } 5264 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5265 } 5266 5267 case Stmt::WhileStmtClass: { 5268 const WhileStmt *WS = cast<WhileStmt>(S); 5269 while (true) { 5270 BlockScopeRAII Scope(Info); 5271 bool Continue; 5272 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5273 Continue)) 5274 return ESR_Failed; 5275 if (!Continue) 5276 break; 5277 5278 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5279 if (ESR != ESR_Continue) { 5280 if (ESR != ESR_Failed && !Scope.destroy()) 5281 return ESR_Failed; 5282 return ESR; 5283 } 5284 if (!Scope.destroy()) 5285 return ESR_Failed; 5286 } 5287 return ESR_Succeeded; 5288 } 5289 5290 case Stmt::DoStmtClass: { 5291 const DoStmt *DS = cast<DoStmt>(S); 5292 bool Continue; 5293 do { 5294 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5295 if (ESR != ESR_Continue) 5296 return ESR; 5297 Case = nullptr; 5298 5299 if (DS->getCond()->isValueDependent()) { 5300 EvaluateDependentExpr(DS->getCond(), Info); 5301 // Bailout as we don't know whether to keep going or terminate the loop. 5302 return ESR_Failed; 5303 } 5304 FullExpressionRAII CondScope(Info); 5305 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5306 !CondScope.destroy()) 5307 return ESR_Failed; 5308 } while (Continue); 5309 return ESR_Succeeded; 5310 } 5311 5312 case Stmt::ForStmtClass: { 5313 const ForStmt *FS = cast<ForStmt>(S); 5314 BlockScopeRAII ForScope(Info); 5315 if (FS->getInit()) { 5316 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5317 if (ESR != ESR_Succeeded) { 5318 if (ESR != ESR_Failed && !ForScope.destroy()) 5319 return ESR_Failed; 5320 return ESR; 5321 } 5322 } 5323 while (true) { 5324 BlockScopeRAII IterScope(Info); 5325 bool Continue = true; 5326 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5327 FS->getCond(), Continue)) 5328 return ESR_Failed; 5329 if (!Continue) 5330 break; 5331 5332 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5333 if (ESR != ESR_Continue) { 5334 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5335 return ESR_Failed; 5336 return ESR; 5337 } 5338 5339 if (const auto *Inc = FS->getInc()) { 5340 if (Inc->isValueDependent()) { 5341 if (!EvaluateDependentExpr(Inc, Info)) 5342 return ESR_Failed; 5343 } else { 5344 FullExpressionRAII IncScope(Info); 5345 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5346 return ESR_Failed; 5347 } 5348 } 5349 5350 if (!IterScope.destroy()) 5351 return ESR_Failed; 5352 } 5353 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5354 } 5355 5356 case Stmt::CXXForRangeStmtClass: { 5357 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5358 BlockScopeRAII Scope(Info); 5359 5360 // Evaluate the init-statement if present. 5361 if (FS->getInit()) { 5362 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5363 if (ESR != ESR_Succeeded) { 5364 if (ESR != ESR_Failed && !Scope.destroy()) 5365 return ESR_Failed; 5366 return ESR; 5367 } 5368 } 5369 5370 // Initialize the __range variable. 5371 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5372 if (ESR != ESR_Succeeded) { 5373 if (ESR != ESR_Failed && !Scope.destroy()) 5374 return ESR_Failed; 5375 return ESR; 5376 } 5377 5378 // In error-recovery cases it's possible to get here even if we failed to 5379 // synthesize the __begin and __end variables. 5380 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) 5381 return ESR_Failed; 5382 5383 // Create the __begin and __end iterators. 5384 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5385 if (ESR != ESR_Succeeded) { 5386 if (ESR != ESR_Failed && !Scope.destroy()) 5387 return ESR_Failed; 5388 return ESR; 5389 } 5390 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5391 if (ESR != ESR_Succeeded) { 5392 if (ESR != ESR_Failed && !Scope.destroy()) 5393 return ESR_Failed; 5394 return ESR; 5395 } 5396 5397 while (true) { 5398 // Condition: __begin != __end. 5399 { 5400 if (FS->getCond()->isValueDependent()) { 5401 EvaluateDependentExpr(FS->getCond(), Info); 5402 // We don't know whether to keep going or terminate the loop. 5403 return ESR_Failed; 5404 } 5405 bool Continue = true; 5406 FullExpressionRAII CondExpr(Info); 5407 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5408 return ESR_Failed; 5409 if (!Continue) 5410 break; 5411 } 5412 5413 // User's variable declaration, initialized by *__begin. 5414 BlockScopeRAII InnerScope(Info); 5415 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5416 if (ESR != ESR_Succeeded) { 5417 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5418 return ESR_Failed; 5419 return ESR; 5420 } 5421 5422 // Loop body. 5423 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5424 if (ESR != ESR_Continue) { 5425 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5426 return ESR_Failed; 5427 return ESR; 5428 } 5429 if (FS->getInc()->isValueDependent()) { 5430 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5431 return ESR_Failed; 5432 } else { 5433 // Increment: ++__begin 5434 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5435 return ESR_Failed; 5436 } 5437 5438 if (!InnerScope.destroy()) 5439 return ESR_Failed; 5440 } 5441 5442 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5443 } 5444 5445 case Stmt::SwitchStmtClass: 5446 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5447 5448 case Stmt::ContinueStmtClass: 5449 return ESR_Continue; 5450 5451 case Stmt::BreakStmtClass: 5452 return ESR_Break; 5453 5454 case Stmt::LabelStmtClass: 5455 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5456 5457 case Stmt::AttributedStmtClass: 5458 // As a general principle, C++11 attributes can be ignored without 5459 // any semantic impact. 5460 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5461 Case); 5462 5463 case Stmt::CaseStmtClass: 5464 case Stmt::DefaultStmtClass: 5465 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5466 case Stmt::CXXTryStmtClass: 5467 // Evaluate try blocks by evaluating all sub statements. 5468 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5469 } 5470 } 5471 5472 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5473 /// default constructor. If so, we'll fold it whether or not it's marked as 5474 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5475 /// so we need special handling. 5476 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5477 const CXXConstructorDecl *CD, 5478 bool IsValueInitialization) { 5479 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5480 return false; 5481 5482 // Value-initialization does not call a trivial default constructor, so such a 5483 // call is a core constant expression whether or not the constructor is 5484 // constexpr. 5485 if (!CD->isConstexpr() && !IsValueInitialization) { 5486 if (Info.getLangOpts().CPlusPlus11) { 5487 // FIXME: If DiagDecl is an implicitly-declared special member function, 5488 // we should be much more explicit about why it's not constexpr. 5489 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5490 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5491 Info.Note(CD->getLocation(), diag::note_declared_at); 5492 } else { 5493 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5494 } 5495 } 5496 return true; 5497 } 5498 5499 /// CheckConstexprFunction - Check that a function can be called in a constant 5500 /// expression. 5501 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5502 const FunctionDecl *Declaration, 5503 const FunctionDecl *Definition, 5504 const Stmt *Body) { 5505 // Potential constant expressions can contain calls to declared, but not yet 5506 // defined, constexpr functions. 5507 if (Info.checkingPotentialConstantExpression() && !Definition && 5508 Declaration->isConstexpr()) 5509 return false; 5510 5511 // Bail out if the function declaration itself is invalid. We will 5512 // have produced a relevant diagnostic while parsing it, so just 5513 // note the problematic sub-expression. 5514 if (Declaration->isInvalidDecl()) { 5515 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5516 return false; 5517 } 5518 5519 // DR1872: An instantiated virtual constexpr function can't be called in a 5520 // constant expression (prior to C++20). We can still constant-fold such a 5521 // call. 5522 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5523 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5524 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5525 5526 if (Definition && Definition->isInvalidDecl()) { 5527 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5528 return false; 5529 } 5530 5531 // Can we evaluate this function call? 5532 if (Definition && Definition->isConstexpr() && Body) 5533 return true; 5534 5535 if (Info.getLangOpts().CPlusPlus11) { 5536 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5537 5538 // If this function is not constexpr because it is an inherited 5539 // non-constexpr constructor, diagnose that directly. 5540 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5541 if (CD && CD->isInheritingConstructor()) { 5542 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5543 if (!Inherited->isConstexpr()) 5544 DiagDecl = CD = Inherited; 5545 } 5546 5547 // FIXME: If DiagDecl is an implicitly-declared special member function 5548 // or an inheriting constructor, we should be much more explicit about why 5549 // it's not constexpr. 5550 if (CD && CD->isInheritingConstructor()) 5551 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5552 << CD->getInheritedConstructor().getConstructor()->getParent(); 5553 else 5554 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5555 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5556 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5557 } else { 5558 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5559 } 5560 return false; 5561 } 5562 5563 namespace { 5564 struct CheckDynamicTypeHandler { 5565 AccessKinds AccessKind; 5566 typedef bool result_type; 5567 bool failed() { return false; } 5568 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5569 bool found(APSInt &Value, QualType SubobjType) { return true; } 5570 bool found(APFloat &Value, QualType SubobjType) { return true; } 5571 }; 5572 } // end anonymous namespace 5573 5574 /// Check that we can access the notional vptr of an object / determine its 5575 /// dynamic type. 5576 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5577 AccessKinds AK, bool Polymorphic) { 5578 if (This.Designator.Invalid) 5579 return false; 5580 5581 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5582 5583 if (!Obj) 5584 return false; 5585 5586 if (!Obj.Value) { 5587 // The object is not usable in constant expressions, so we can't inspect 5588 // its value to see if it's in-lifetime or what the active union members 5589 // are. We can still check for a one-past-the-end lvalue. 5590 if (This.Designator.isOnePastTheEnd() || 5591 This.Designator.isMostDerivedAnUnsizedArray()) { 5592 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5593 ? diag::note_constexpr_access_past_end 5594 : diag::note_constexpr_access_unsized_array) 5595 << AK; 5596 return false; 5597 } else if (Polymorphic) { 5598 // Conservatively refuse to perform a polymorphic operation if we would 5599 // not be able to read a notional 'vptr' value. 5600 APValue Val; 5601 This.moveInto(Val); 5602 QualType StarThisType = 5603 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5604 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5605 << AK << Val.getAsString(Info.Ctx, StarThisType); 5606 return false; 5607 } 5608 return true; 5609 } 5610 5611 CheckDynamicTypeHandler Handler{AK}; 5612 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5613 } 5614 5615 /// Check that the pointee of the 'this' pointer in a member function call is 5616 /// either within its lifetime or in its period of construction or destruction. 5617 static bool 5618 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5619 const LValue &This, 5620 const CXXMethodDecl *NamedMember) { 5621 return checkDynamicType( 5622 Info, E, This, 5623 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5624 } 5625 5626 struct DynamicType { 5627 /// The dynamic class type of the object. 5628 const CXXRecordDecl *Type; 5629 /// The corresponding path length in the lvalue. 5630 unsigned PathLength; 5631 }; 5632 5633 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5634 unsigned PathLength) { 5635 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5636 Designator.Entries.size() && "invalid path length"); 5637 return (PathLength == Designator.MostDerivedPathLength) 5638 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5639 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5640 } 5641 5642 /// Determine the dynamic type of an object. 5643 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5644 LValue &This, AccessKinds AK) { 5645 // If we don't have an lvalue denoting an object of class type, there is no 5646 // meaningful dynamic type. (We consider objects of non-class type to have no 5647 // dynamic type.) 5648 if (!checkDynamicType(Info, E, This, AK, true)) 5649 return None; 5650 5651 // Refuse to compute a dynamic type in the presence of virtual bases. This 5652 // shouldn't happen other than in constant-folding situations, since literal 5653 // types can't have virtual bases. 5654 // 5655 // Note that consumers of DynamicType assume that the type has no virtual 5656 // bases, and will need modifications if this restriction is relaxed. 5657 const CXXRecordDecl *Class = 5658 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5659 if (!Class || Class->getNumVBases()) { 5660 Info.FFDiag(E); 5661 return None; 5662 } 5663 5664 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5665 // binary search here instead. But the overwhelmingly common case is that 5666 // we're not in the middle of a constructor, so it probably doesn't matter 5667 // in practice. 5668 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5669 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5670 PathLength <= Path.size(); ++PathLength) { 5671 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5672 Path.slice(0, PathLength))) { 5673 case ConstructionPhase::Bases: 5674 case ConstructionPhase::DestroyingBases: 5675 // We're constructing or destroying a base class. This is not the dynamic 5676 // type. 5677 break; 5678 5679 case ConstructionPhase::None: 5680 case ConstructionPhase::AfterBases: 5681 case ConstructionPhase::AfterFields: 5682 case ConstructionPhase::Destroying: 5683 // We've finished constructing the base classes and not yet started 5684 // destroying them again, so this is the dynamic type. 5685 return DynamicType{getBaseClassType(This.Designator, PathLength), 5686 PathLength}; 5687 } 5688 } 5689 5690 // CWG issue 1517: we're constructing a base class of the object described by 5691 // 'This', so that object has not yet begun its period of construction and 5692 // any polymorphic operation on it results in undefined behavior. 5693 Info.FFDiag(E); 5694 return None; 5695 } 5696 5697 /// Perform virtual dispatch. 5698 static const CXXMethodDecl *HandleVirtualDispatch( 5699 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5700 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5701 Optional<DynamicType> DynType = ComputeDynamicType( 5702 Info, E, This, 5703 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5704 if (!DynType) 5705 return nullptr; 5706 5707 // Find the final overrider. It must be declared in one of the classes on the 5708 // path from the dynamic type to the static type. 5709 // FIXME: If we ever allow literal types to have virtual base classes, that 5710 // won't be true. 5711 const CXXMethodDecl *Callee = Found; 5712 unsigned PathLength = DynType->PathLength; 5713 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5714 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5715 const CXXMethodDecl *Overrider = 5716 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5717 if (Overrider) { 5718 Callee = Overrider; 5719 break; 5720 } 5721 } 5722 5723 // C++2a [class.abstract]p6: 5724 // the effect of making a virtual call to a pure virtual function [...] is 5725 // undefined 5726 if (Callee->isPure()) { 5727 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5728 Info.Note(Callee->getLocation(), diag::note_declared_at); 5729 return nullptr; 5730 } 5731 5732 // If necessary, walk the rest of the path to determine the sequence of 5733 // covariant adjustment steps to apply. 5734 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5735 Found->getReturnType())) { 5736 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5737 for (unsigned CovariantPathLength = PathLength + 1; 5738 CovariantPathLength != This.Designator.Entries.size(); 5739 ++CovariantPathLength) { 5740 const CXXRecordDecl *NextClass = 5741 getBaseClassType(This.Designator, CovariantPathLength); 5742 const CXXMethodDecl *Next = 5743 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5744 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5745 Next->getReturnType(), CovariantAdjustmentPath.back())) 5746 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5747 } 5748 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5749 CovariantAdjustmentPath.back())) 5750 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5751 } 5752 5753 // Perform 'this' adjustment. 5754 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5755 return nullptr; 5756 5757 return Callee; 5758 } 5759 5760 /// Perform the adjustment from a value returned by a virtual function to 5761 /// a value of the statically expected type, which may be a pointer or 5762 /// reference to a base class of the returned type. 5763 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5764 APValue &Result, 5765 ArrayRef<QualType> Path) { 5766 assert(Result.isLValue() && 5767 "unexpected kind of APValue for covariant return"); 5768 if (Result.isNullPointer()) 5769 return true; 5770 5771 LValue LVal; 5772 LVal.setFrom(Info.Ctx, Result); 5773 5774 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5775 for (unsigned I = 1; I != Path.size(); ++I) { 5776 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5777 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5778 if (OldClass != NewClass && 5779 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5780 return false; 5781 OldClass = NewClass; 5782 } 5783 5784 LVal.moveInto(Result); 5785 return true; 5786 } 5787 5788 /// Determine whether \p Base, which is known to be a direct base class of 5789 /// \p Derived, is a public base class. 5790 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5791 const CXXRecordDecl *Base) { 5792 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5793 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5794 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5795 return BaseSpec.getAccessSpecifier() == AS_public; 5796 } 5797 llvm_unreachable("Base is not a direct base of Derived"); 5798 } 5799 5800 /// Apply the given dynamic cast operation on the provided lvalue. 5801 /// 5802 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5803 /// to find a suitable target subobject. 5804 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5805 LValue &Ptr) { 5806 // We can't do anything with a non-symbolic pointer value. 5807 SubobjectDesignator &D = Ptr.Designator; 5808 if (D.Invalid) 5809 return false; 5810 5811 // C++ [expr.dynamic.cast]p6: 5812 // If v is a null pointer value, the result is a null pointer value. 5813 if (Ptr.isNullPointer() && !E->isGLValue()) 5814 return true; 5815 5816 // For all the other cases, we need the pointer to point to an object within 5817 // its lifetime / period of construction / destruction, and we need to know 5818 // its dynamic type. 5819 Optional<DynamicType> DynType = 5820 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5821 if (!DynType) 5822 return false; 5823 5824 // C++ [expr.dynamic.cast]p7: 5825 // If T is "pointer to cv void", then the result is a pointer to the most 5826 // derived object 5827 if (E->getType()->isVoidPointerType()) 5828 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5829 5830 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5831 assert(C && "dynamic_cast target is not void pointer nor class"); 5832 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5833 5834 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5835 // C++ [expr.dynamic.cast]p9: 5836 if (!E->isGLValue()) { 5837 // The value of a failed cast to pointer type is the null pointer value 5838 // of the required result type. 5839 Ptr.setNull(Info.Ctx, E->getType()); 5840 return true; 5841 } 5842 5843 // A failed cast to reference type throws [...] std::bad_cast. 5844 unsigned DiagKind; 5845 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5846 DynType->Type->isDerivedFrom(C))) 5847 DiagKind = 0; 5848 else if (!Paths || Paths->begin() == Paths->end()) 5849 DiagKind = 1; 5850 else if (Paths->isAmbiguous(CQT)) 5851 DiagKind = 2; 5852 else { 5853 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5854 DiagKind = 3; 5855 } 5856 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5857 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5858 << Info.Ctx.getRecordType(DynType->Type) 5859 << E->getType().getUnqualifiedType(); 5860 return false; 5861 }; 5862 5863 // Runtime check, phase 1: 5864 // Walk from the base subobject towards the derived object looking for the 5865 // target type. 5866 for (int PathLength = Ptr.Designator.Entries.size(); 5867 PathLength >= (int)DynType->PathLength; --PathLength) { 5868 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5869 if (declaresSameEntity(Class, C)) 5870 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5871 // We can only walk across public inheritance edges. 5872 if (PathLength > (int)DynType->PathLength && 5873 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5874 Class)) 5875 return RuntimeCheckFailed(nullptr); 5876 } 5877 5878 // Runtime check, phase 2: 5879 // Search the dynamic type for an unambiguous public base of type C. 5880 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5881 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5882 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5883 Paths.front().Access == AS_public) { 5884 // Downcast to the dynamic type... 5885 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5886 return false; 5887 // ... then upcast to the chosen base class subobject. 5888 for (CXXBasePathElement &Elem : Paths.front()) 5889 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5890 return false; 5891 return true; 5892 } 5893 5894 // Otherwise, the runtime check fails. 5895 return RuntimeCheckFailed(&Paths); 5896 } 5897 5898 namespace { 5899 struct StartLifetimeOfUnionMemberHandler { 5900 EvalInfo &Info; 5901 const Expr *LHSExpr; 5902 const FieldDecl *Field; 5903 bool DuringInit; 5904 bool Failed = false; 5905 static const AccessKinds AccessKind = AK_Assign; 5906 5907 typedef bool result_type; 5908 bool failed() { return Failed; } 5909 bool found(APValue &Subobj, QualType SubobjType) { 5910 // We are supposed to perform no initialization but begin the lifetime of 5911 // the object. We interpret that as meaning to do what default 5912 // initialization of the object would do if all constructors involved were 5913 // trivial: 5914 // * All base, non-variant member, and array element subobjects' lifetimes 5915 // begin 5916 // * No variant members' lifetimes begin 5917 // * All scalar subobjects whose lifetimes begin have indeterminate values 5918 assert(SubobjType->isUnionType()); 5919 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5920 // This union member is already active. If it's also in-lifetime, there's 5921 // nothing to do. 5922 if (Subobj.getUnionValue().hasValue()) 5923 return true; 5924 } else if (DuringInit) { 5925 // We're currently in the process of initializing a different union 5926 // member. If we carried on, that initialization would attempt to 5927 // store to an inactive union member, resulting in undefined behavior. 5928 Info.FFDiag(LHSExpr, 5929 diag::note_constexpr_union_member_change_during_init); 5930 return false; 5931 } 5932 APValue Result; 5933 Failed = !getDefaultInitValue(Field->getType(), Result); 5934 Subobj.setUnion(Field, Result); 5935 return true; 5936 } 5937 bool found(APSInt &Value, QualType SubobjType) { 5938 llvm_unreachable("wrong value kind for union object"); 5939 } 5940 bool found(APFloat &Value, QualType SubobjType) { 5941 llvm_unreachable("wrong value kind for union object"); 5942 } 5943 }; 5944 } // end anonymous namespace 5945 5946 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5947 5948 /// Handle a builtin simple-assignment or a call to a trivial assignment 5949 /// operator whose left-hand side might involve a union member access. If it 5950 /// does, implicitly start the lifetime of any accessed union elements per 5951 /// C++20 [class.union]5. 5952 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5953 const LValue &LHS) { 5954 if (LHS.InvalidBase || LHS.Designator.Invalid) 5955 return false; 5956 5957 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5958 // C++ [class.union]p5: 5959 // define the set S(E) of subexpressions of E as follows: 5960 unsigned PathLength = LHS.Designator.Entries.size(); 5961 for (const Expr *E = LHSExpr; E != nullptr;) { 5962 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5963 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5964 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5965 // Note that we can't implicitly start the lifetime of a reference, 5966 // so we don't need to proceed any further if we reach one. 5967 if (!FD || FD->getType()->isReferenceType()) 5968 break; 5969 5970 // ... and also contains A.B if B names a union member ... 5971 if (FD->getParent()->isUnion()) { 5972 // ... of a non-class, non-array type, or of a class type with a 5973 // trivial default constructor that is not deleted, or an array of 5974 // such types. 5975 auto *RD = 5976 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5977 if (!RD || RD->hasTrivialDefaultConstructor()) 5978 UnionPathLengths.push_back({PathLength - 1, FD}); 5979 } 5980 5981 E = ME->getBase(); 5982 --PathLength; 5983 assert(declaresSameEntity(FD, 5984 LHS.Designator.Entries[PathLength] 5985 .getAsBaseOrMember().getPointer())); 5986 5987 // -- If E is of the form A[B] and is interpreted as a built-in array 5988 // subscripting operator, S(E) is [S(the array operand, if any)]. 5989 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5990 // Step over an ArrayToPointerDecay implicit cast. 5991 auto *Base = ASE->getBase()->IgnoreImplicit(); 5992 if (!Base->getType()->isArrayType()) 5993 break; 5994 5995 E = Base; 5996 --PathLength; 5997 5998 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5999 // Step over a derived-to-base conversion. 6000 E = ICE->getSubExpr(); 6001 if (ICE->getCastKind() == CK_NoOp) 6002 continue; 6003 if (ICE->getCastKind() != CK_DerivedToBase && 6004 ICE->getCastKind() != CK_UncheckedDerivedToBase) 6005 break; 6006 // Walk path backwards as we walk up from the base to the derived class. 6007 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 6008 --PathLength; 6009 (void)Elt; 6010 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 6011 LHS.Designator.Entries[PathLength] 6012 .getAsBaseOrMember().getPointer())); 6013 } 6014 6015 // -- Otherwise, S(E) is empty. 6016 } else { 6017 break; 6018 } 6019 } 6020 6021 // Common case: no unions' lifetimes are started. 6022 if (UnionPathLengths.empty()) 6023 return true; 6024 6025 // if modification of X [would access an inactive union member], an object 6026 // of the type of X is implicitly created 6027 CompleteObject Obj = 6028 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 6029 if (!Obj) 6030 return false; 6031 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 6032 llvm::reverse(UnionPathLengths)) { 6033 // Form a designator for the union object. 6034 SubobjectDesignator D = LHS.Designator; 6035 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 6036 6037 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 6038 ConstructionPhase::AfterBases; 6039 StartLifetimeOfUnionMemberHandler StartLifetime{ 6040 Info, LHSExpr, LengthAndField.second, DuringInit}; 6041 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 6042 return false; 6043 } 6044 6045 return true; 6046 } 6047 6048 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 6049 CallRef Call, EvalInfo &Info, 6050 bool NonNull = false) { 6051 LValue LV; 6052 // Create the parameter slot and register its destruction. For a vararg 6053 // argument, create a temporary. 6054 // FIXME: For calling conventions that destroy parameters in the callee, 6055 // should we consider performing destruction when the function returns 6056 // instead? 6057 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 6058 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 6059 ScopeKind::Call, LV); 6060 if (!EvaluateInPlace(V, Info, LV, Arg)) 6061 return false; 6062 6063 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6064 // undefined behavior, so is non-constant. 6065 if (NonNull && V.isLValue() && V.isNullPointer()) { 6066 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6067 return false; 6068 } 6069 6070 return true; 6071 } 6072 6073 /// Evaluate the arguments to a function call. 6074 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6075 EvalInfo &Info, const FunctionDecl *Callee, 6076 bool RightToLeft = false) { 6077 bool Success = true; 6078 llvm::SmallBitVector ForbiddenNullArgs; 6079 if (Callee->hasAttr<NonNullAttr>()) { 6080 ForbiddenNullArgs.resize(Args.size()); 6081 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6082 if (!Attr->args_size()) { 6083 ForbiddenNullArgs.set(); 6084 break; 6085 } else 6086 for (auto Idx : Attr->args()) { 6087 unsigned ASTIdx = Idx.getASTIndex(); 6088 if (ASTIdx >= Args.size()) 6089 continue; 6090 ForbiddenNullArgs[ASTIdx] = true; 6091 } 6092 } 6093 } 6094 for (unsigned I = 0; I < Args.size(); I++) { 6095 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6096 const ParmVarDecl *PVD = 6097 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6098 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6099 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6100 // If we're checking for a potential constant expression, evaluate all 6101 // initializers even if some of them fail. 6102 if (!Info.noteFailure()) 6103 return false; 6104 Success = false; 6105 } 6106 } 6107 return Success; 6108 } 6109 6110 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6111 /// constructor or assignment operator. 6112 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6113 const Expr *E, APValue &Result, 6114 bool CopyObjectRepresentation) { 6115 // Find the reference argument. 6116 CallStackFrame *Frame = Info.CurrentCall; 6117 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6118 if (!RefValue) { 6119 Info.FFDiag(E); 6120 return false; 6121 } 6122 6123 // Copy out the contents of the RHS object. 6124 LValue RefLValue; 6125 RefLValue.setFrom(Info.Ctx, *RefValue); 6126 return handleLValueToRValueConversion( 6127 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6128 CopyObjectRepresentation); 6129 } 6130 6131 /// Evaluate a function call. 6132 static bool HandleFunctionCall(SourceLocation CallLoc, 6133 const FunctionDecl *Callee, const LValue *This, 6134 ArrayRef<const Expr *> Args, CallRef Call, 6135 const Stmt *Body, EvalInfo &Info, 6136 APValue &Result, const LValue *ResultSlot) { 6137 if (!Info.CheckCallLimit(CallLoc)) 6138 return false; 6139 6140 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6141 6142 // For a trivial copy or move assignment, perform an APValue copy. This is 6143 // essential for unions, where the operations performed by the assignment 6144 // operator cannot be represented as statements. 6145 // 6146 // Skip this for non-union classes with no fields; in that case, the defaulted 6147 // copy/move does not actually read the object. 6148 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6149 if (MD && MD->isDefaulted() && 6150 (MD->getParent()->isUnion() || 6151 (MD->isTrivial() && 6152 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6153 assert(This && 6154 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6155 APValue RHSValue; 6156 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6157 MD->getParent()->isUnion())) 6158 return false; 6159 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6160 RHSValue)) 6161 return false; 6162 This->moveInto(Result); 6163 return true; 6164 } else if (MD && isLambdaCallOperator(MD)) { 6165 // We're in a lambda; determine the lambda capture field maps unless we're 6166 // just constexpr checking a lambda's call operator. constexpr checking is 6167 // done before the captures have been added to the closure object (unless 6168 // we're inferring constexpr-ness), so we don't have access to them in this 6169 // case. But since we don't need the captures to constexpr check, we can 6170 // just ignore them. 6171 if (!Info.checkingPotentialConstantExpression()) 6172 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6173 Frame.LambdaThisCaptureField); 6174 } 6175 6176 StmtResult Ret = {Result, ResultSlot}; 6177 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6178 if (ESR == ESR_Succeeded) { 6179 if (Callee->getReturnType()->isVoidType()) 6180 return true; 6181 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6182 } 6183 return ESR == ESR_Returned; 6184 } 6185 6186 /// Evaluate a constructor call. 6187 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6188 CallRef Call, 6189 const CXXConstructorDecl *Definition, 6190 EvalInfo &Info, APValue &Result) { 6191 SourceLocation CallLoc = E->getExprLoc(); 6192 if (!Info.CheckCallLimit(CallLoc)) 6193 return false; 6194 6195 const CXXRecordDecl *RD = Definition->getParent(); 6196 if (RD->getNumVBases()) { 6197 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6198 return false; 6199 } 6200 6201 EvalInfo::EvaluatingConstructorRAII EvalObj( 6202 Info, 6203 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6204 RD->getNumBases()); 6205 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6206 6207 // FIXME: Creating an APValue just to hold a nonexistent return value is 6208 // wasteful. 6209 APValue RetVal; 6210 StmtResult Ret = {RetVal, nullptr}; 6211 6212 // If it's a delegating constructor, delegate. 6213 if (Definition->isDelegatingConstructor()) { 6214 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6215 if ((*I)->getInit()->isValueDependent()) { 6216 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6217 return false; 6218 } else { 6219 FullExpressionRAII InitScope(Info); 6220 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6221 !InitScope.destroy()) 6222 return false; 6223 } 6224 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6225 } 6226 6227 // For a trivial copy or move constructor, perform an APValue copy. This is 6228 // essential for unions (or classes with anonymous union members), where the 6229 // operations performed by the constructor cannot be represented by 6230 // ctor-initializers. 6231 // 6232 // Skip this for empty non-union classes; we should not perform an 6233 // lvalue-to-rvalue conversion on them because their copy constructor does not 6234 // actually read them. 6235 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6236 (Definition->getParent()->isUnion() || 6237 (Definition->isTrivial() && 6238 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6239 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6240 Definition->getParent()->isUnion()); 6241 } 6242 6243 // Reserve space for the struct members. 6244 if (!Result.hasValue()) { 6245 if (!RD->isUnion()) 6246 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6247 std::distance(RD->field_begin(), RD->field_end())); 6248 else 6249 // A union starts with no active member. 6250 Result = APValue((const FieldDecl*)nullptr); 6251 } 6252 6253 if (RD->isInvalidDecl()) return false; 6254 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6255 6256 // A scope for temporaries lifetime-extended by reference members. 6257 BlockScopeRAII LifetimeExtendedScope(Info); 6258 6259 bool Success = true; 6260 unsigned BasesSeen = 0; 6261 #ifndef NDEBUG 6262 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6263 #endif 6264 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6265 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6266 // We might be initializing the same field again if this is an indirect 6267 // field initialization. 6268 if (FieldIt == RD->field_end() || 6269 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6270 assert(Indirect && "fields out of order?"); 6271 return; 6272 } 6273 6274 // Default-initialize any fields with no explicit initializer. 6275 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6276 assert(FieldIt != RD->field_end() && "missing field?"); 6277 if (!FieldIt->isUnnamedBitfield()) 6278 Success &= getDefaultInitValue( 6279 FieldIt->getType(), 6280 Result.getStructField(FieldIt->getFieldIndex())); 6281 } 6282 ++FieldIt; 6283 }; 6284 for (const auto *I : Definition->inits()) { 6285 LValue Subobject = This; 6286 LValue SubobjectParent = This; 6287 APValue *Value = &Result; 6288 6289 // Determine the subobject to initialize. 6290 FieldDecl *FD = nullptr; 6291 if (I->isBaseInitializer()) { 6292 QualType BaseType(I->getBaseClass(), 0); 6293 #ifndef NDEBUG 6294 // Non-virtual base classes are initialized in the order in the class 6295 // definition. We have already checked for virtual base classes. 6296 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6297 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6298 "base class initializers not in expected order"); 6299 ++BaseIt; 6300 #endif 6301 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6302 BaseType->getAsCXXRecordDecl(), &Layout)) 6303 return false; 6304 Value = &Result.getStructBase(BasesSeen++); 6305 } else if ((FD = I->getMember())) { 6306 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6307 return false; 6308 if (RD->isUnion()) { 6309 Result = APValue(FD); 6310 Value = &Result.getUnionValue(); 6311 } else { 6312 SkipToField(FD, false); 6313 Value = &Result.getStructField(FD->getFieldIndex()); 6314 } 6315 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6316 // Walk the indirect field decl's chain to find the object to initialize, 6317 // and make sure we've initialized every step along it. 6318 auto IndirectFieldChain = IFD->chain(); 6319 for (auto *C : IndirectFieldChain) { 6320 FD = cast<FieldDecl>(C); 6321 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6322 // Switch the union field if it differs. This happens if we had 6323 // preceding zero-initialization, and we're now initializing a union 6324 // subobject other than the first. 6325 // FIXME: In this case, the values of the other subobjects are 6326 // specified, since zero-initialization sets all padding bits to zero. 6327 if (!Value->hasValue() || 6328 (Value->isUnion() && Value->getUnionField() != FD)) { 6329 if (CD->isUnion()) 6330 *Value = APValue(FD); 6331 else 6332 // FIXME: This immediately starts the lifetime of all members of 6333 // an anonymous struct. It would be preferable to strictly start 6334 // member lifetime in initialization order. 6335 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6336 } 6337 // Store Subobject as its parent before updating it for the last element 6338 // in the chain. 6339 if (C == IndirectFieldChain.back()) 6340 SubobjectParent = Subobject; 6341 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6342 return false; 6343 if (CD->isUnion()) 6344 Value = &Value->getUnionValue(); 6345 else { 6346 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6347 SkipToField(FD, true); 6348 Value = &Value->getStructField(FD->getFieldIndex()); 6349 } 6350 } 6351 } else { 6352 llvm_unreachable("unknown base initializer kind"); 6353 } 6354 6355 // Need to override This for implicit field initializers as in this case 6356 // This refers to innermost anonymous struct/union containing initializer, 6357 // not to currently constructed class. 6358 const Expr *Init = I->getInit(); 6359 if (Init->isValueDependent()) { 6360 if (!EvaluateDependentExpr(Init, Info)) 6361 return false; 6362 } else { 6363 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6364 isa<CXXDefaultInitExpr>(Init)); 6365 FullExpressionRAII InitScope(Info); 6366 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6367 (FD && FD->isBitField() && 6368 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6369 // If we're checking for a potential constant expression, evaluate all 6370 // initializers even if some of them fail. 6371 if (!Info.noteFailure()) 6372 return false; 6373 Success = false; 6374 } 6375 } 6376 6377 // This is the point at which the dynamic type of the object becomes this 6378 // class type. 6379 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6380 EvalObj.finishedConstructingBases(); 6381 } 6382 6383 // Default-initialize any remaining fields. 6384 if (!RD->isUnion()) { 6385 for (; FieldIt != RD->field_end(); ++FieldIt) { 6386 if (!FieldIt->isUnnamedBitfield()) 6387 Success &= getDefaultInitValue( 6388 FieldIt->getType(), 6389 Result.getStructField(FieldIt->getFieldIndex())); 6390 } 6391 } 6392 6393 EvalObj.finishedConstructingFields(); 6394 6395 return Success && 6396 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6397 LifetimeExtendedScope.destroy(); 6398 } 6399 6400 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6401 ArrayRef<const Expr*> Args, 6402 const CXXConstructorDecl *Definition, 6403 EvalInfo &Info, APValue &Result) { 6404 CallScopeRAII CallScope(Info); 6405 CallRef Call = Info.CurrentCall->createCall(Definition); 6406 if (!EvaluateArgs(Args, Call, Info, Definition)) 6407 return false; 6408 6409 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6410 CallScope.destroy(); 6411 } 6412 6413 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6414 const LValue &This, APValue &Value, 6415 QualType T) { 6416 // Objects can only be destroyed while they're within their lifetimes. 6417 // FIXME: We have no representation for whether an object of type nullptr_t 6418 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6419 // as indeterminate instead? 6420 if (Value.isAbsent() && !T->isNullPtrType()) { 6421 APValue Printable; 6422 This.moveInto(Printable); 6423 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6424 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6425 return false; 6426 } 6427 6428 // Invent an expression for location purposes. 6429 // FIXME: We shouldn't need to do this. 6430 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); 6431 6432 // For arrays, destroy elements right-to-left. 6433 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6434 uint64_t Size = CAT->getSize().getZExtValue(); 6435 QualType ElemT = CAT->getElementType(); 6436 6437 LValue ElemLV = This; 6438 ElemLV.addArray(Info, &LocE, CAT); 6439 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6440 return false; 6441 6442 // Ensure that we have actual array elements available to destroy; the 6443 // destructors might mutate the value, so we can't run them on the array 6444 // filler. 6445 if (Size && Size > Value.getArrayInitializedElts()) 6446 expandArray(Value, Value.getArraySize() - 1); 6447 6448 for (; Size != 0; --Size) { 6449 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6450 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6451 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6452 return false; 6453 } 6454 6455 // End the lifetime of this array now. 6456 Value = APValue(); 6457 return true; 6458 } 6459 6460 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6461 if (!RD) { 6462 if (T.isDestructedType()) { 6463 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6464 return false; 6465 } 6466 6467 Value = APValue(); 6468 return true; 6469 } 6470 6471 if (RD->getNumVBases()) { 6472 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6473 return false; 6474 } 6475 6476 const CXXDestructorDecl *DD = RD->getDestructor(); 6477 if (!DD && !RD->hasTrivialDestructor()) { 6478 Info.FFDiag(CallLoc); 6479 return false; 6480 } 6481 6482 if (!DD || DD->isTrivial() || 6483 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6484 // A trivial destructor just ends the lifetime of the object. Check for 6485 // this case before checking for a body, because we might not bother 6486 // building a body for a trivial destructor. Note that it doesn't matter 6487 // whether the destructor is constexpr in this case; all trivial 6488 // destructors are constexpr. 6489 // 6490 // If an anonymous union would be destroyed, some enclosing destructor must 6491 // have been explicitly defined, and the anonymous union destruction should 6492 // have no effect. 6493 Value = APValue(); 6494 return true; 6495 } 6496 6497 if (!Info.CheckCallLimit(CallLoc)) 6498 return false; 6499 6500 const FunctionDecl *Definition = nullptr; 6501 const Stmt *Body = DD->getBody(Definition); 6502 6503 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6504 return false; 6505 6506 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6507 6508 // We're now in the period of destruction of this object. 6509 unsigned BasesLeft = RD->getNumBases(); 6510 EvalInfo::EvaluatingDestructorRAII EvalObj( 6511 Info, 6512 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6513 if (!EvalObj.DidInsert) { 6514 // C++2a [class.dtor]p19: 6515 // the behavior is undefined if the destructor is invoked for an object 6516 // whose lifetime has ended 6517 // (Note that formally the lifetime ends when the period of destruction 6518 // begins, even though certain uses of the object remain valid until the 6519 // period of destruction ends.) 6520 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6521 return false; 6522 } 6523 6524 // FIXME: Creating an APValue just to hold a nonexistent return value is 6525 // wasteful. 6526 APValue RetVal; 6527 StmtResult Ret = {RetVal, nullptr}; 6528 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6529 return false; 6530 6531 // A union destructor does not implicitly destroy its members. 6532 if (RD->isUnion()) 6533 return true; 6534 6535 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6536 6537 // We don't have a good way to iterate fields in reverse, so collect all the 6538 // fields first and then walk them backwards. 6539 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6540 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6541 if (FD->isUnnamedBitfield()) 6542 continue; 6543 6544 LValue Subobject = This; 6545 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6546 return false; 6547 6548 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6549 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6550 FD->getType())) 6551 return false; 6552 } 6553 6554 if (BasesLeft != 0) 6555 EvalObj.startedDestroyingBases(); 6556 6557 // Destroy base classes in reverse order. 6558 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6559 --BasesLeft; 6560 6561 QualType BaseType = Base.getType(); 6562 LValue Subobject = This; 6563 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6564 BaseType->getAsCXXRecordDecl(), &Layout)) 6565 return false; 6566 6567 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6568 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6569 BaseType)) 6570 return false; 6571 } 6572 assert(BasesLeft == 0 && "NumBases was wrong?"); 6573 6574 // The period of destruction ends now. The object is gone. 6575 Value = APValue(); 6576 return true; 6577 } 6578 6579 namespace { 6580 struct DestroyObjectHandler { 6581 EvalInfo &Info; 6582 const Expr *E; 6583 const LValue &This; 6584 const AccessKinds AccessKind; 6585 6586 typedef bool result_type; 6587 bool failed() { return false; } 6588 bool found(APValue &Subobj, QualType SubobjType) { 6589 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6590 SubobjType); 6591 } 6592 bool found(APSInt &Value, QualType SubobjType) { 6593 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6594 return false; 6595 } 6596 bool found(APFloat &Value, QualType SubobjType) { 6597 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6598 return false; 6599 } 6600 }; 6601 } 6602 6603 /// Perform a destructor or pseudo-destructor call on the given object, which 6604 /// might in general not be a complete object. 6605 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6606 const LValue &This, QualType ThisType) { 6607 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6608 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6609 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6610 } 6611 6612 /// Destroy and end the lifetime of the given complete object. 6613 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6614 APValue::LValueBase LVBase, APValue &Value, 6615 QualType T) { 6616 // If we've had an unmodeled side-effect, we can't rely on mutable state 6617 // (such as the object we're about to destroy) being correct. 6618 if (Info.EvalStatus.HasSideEffects) 6619 return false; 6620 6621 LValue LV; 6622 LV.set({LVBase}); 6623 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6624 } 6625 6626 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6627 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6628 LValue &Result) { 6629 if (Info.checkingPotentialConstantExpression() || 6630 Info.SpeculativeEvaluationDepth) 6631 return false; 6632 6633 // This is permitted only within a call to std::allocator<T>::allocate. 6634 auto Caller = Info.getStdAllocatorCaller("allocate"); 6635 if (!Caller) { 6636 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6637 ? diag::note_constexpr_new_untyped 6638 : diag::note_constexpr_new); 6639 return false; 6640 } 6641 6642 QualType ElemType = Caller.ElemType; 6643 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6644 Info.FFDiag(E->getExprLoc(), 6645 diag::note_constexpr_new_not_complete_object_type) 6646 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6647 return false; 6648 } 6649 6650 APSInt ByteSize; 6651 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6652 return false; 6653 bool IsNothrow = false; 6654 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6655 EvaluateIgnoredValue(Info, E->getArg(I)); 6656 IsNothrow |= E->getType()->isNothrowT(); 6657 } 6658 6659 CharUnits ElemSize; 6660 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6661 return false; 6662 APInt Size, Remainder; 6663 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6664 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6665 if (Remainder != 0) { 6666 // This likely indicates a bug in the implementation of 'std::allocator'. 6667 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6668 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6669 return false; 6670 } 6671 6672 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6673 if (IsNothrow) { 6674 Result.setNull(Info.Ctx, E->getType()); 6675 return true; 6676 } 6677 6678 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6679 return false; 6680 } 6681 6682 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6683 ArrayType::Normal, 0); 6684 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6685 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6686 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6687 return true; 6688 } 6689 6690 static bool hasVirtualDestructor(QualType T) { 6691 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6692 if (CXXDestructorDecl *DD = RD->getDestructor()) 6693 return DD->isVirtual(); 6694 return false; 6695 } 6696 6697 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6698 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6699 if (CXXDestructorDecl *DD = RD->getDestructor()) 6700 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6701 return nullptr; 6702 } 6703 6704 /// Check that the given object is a suitable pointer to a heap allocation that 6705 /// still exists and is of the right kind for the purpose of a deletion. 6706 /// 6707 /// On success, returns the heap allocation to deallocate. On failure, produces 6708 /// a diagnostic and returns None. 6709 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6710 const LValue &Pointer, 6711 DynAlloc::Kind DeallocKind) { 6712 auto PointerAsString = [&] { 6713 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6714 }; 6715 6716 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6717 if (!DA) { 6718 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6719 << PointerAsString(); 6720 if (Pointer.Base) 6721 NoteLValueLocation(Info, Pointer.Base); 6722 return None; 6723 } 6724 6725 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6726 if (!Alloc) { 6727 Info.FFDiag(E, diag::note_constexpr_double_delete); 6728 return None; 6729 } 6730 6731 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6732 if (DeallocKind != (*Alloc)->getKind()) { 6733 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6734 << DeallocKind << (*Alloc)->getKind() << AllocType; 6735 NoteLValueLocation(Info, Pointer.Base); 6736 return None; 6737 } 6738 6739 bool Subobject = false; 6740 if (DeallocKind == DynAlloc::New) { 6741 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6742 Pointer.Designator.isOnePastTheEnd(); 6743 } else { 6744 Subobject = Pointer.Designator.Entries.size() != 1 || 6745 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6746 } 6747 if (Subobject) { 6748 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6749 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6750 return None; 6751 } 6752 6753 return Alloc; 6754 } 6755 6756 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6757 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6758 if (Info.checkingPotentialConstantExpression() || 6759 Info.SpeculativeEvaluationDepth) 6760 return false; 6761 6762 // This is permitted only within a call to std::allocator<T>::deallocate. 6763 if (!Info.getStdAllocatorCaller("deallocate")) { 6764 Info.FFDiag(E->getExprLoc()); 6765 return true; 6766 } 6767 6768 LValue Pointer; 6769 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6770 return false; 6771 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6772 EvaluateIgnoredValue(Info, E->getArg(I)); 6773 6774 if (Pointer.Designator.Invalid) 6775 return false; 6776 6777 // Deleting a null pointer would have no effect, but it's not permitted by 6778 // std::allocator<T>::deallocate's contract. 6779 if (Pointer.isNullPointer()) { 6780 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6781 return true; 6782 } 6783 6784 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6785 return false; 6786 6787 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6788 return true; 6789 } 6790 6791 //===----------------------------------------------------------------------===// 6792 // Generic Evaluation 6793 //===----------------------------------------------------------------------===// 6794 namespace { 6795 6796 class BitCastBuffer { 6797 // FIXME: We're going to need bit-level granularity when we support 6798 // bit-fields. 6799 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6800 // we don't support a host or target where that is the case. Still, we should 6801 // use a more generic type in case we ever do. 6802 SmallVector<Optional<unsigned char>, 32> Bytes; 6803 6804 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6805 "Need at least 8 bit unsigned char"); 6806 6807 bool TargetIsLittleEndian; 6808 6809 public: 6810 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6811 : Bytes(Width.getQuantity()), 6812 TargetIsLittleEndian(TargetIsLittleEndian) {} 6813 6814 LLVM_NODISCARD 6815 bool readObject(CharUnits Offset, CharUnits Width, 6816 SmallVectorImpl<unsigned char> &Output) const { 6817 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6818 // If a byte of an integer is uninitialized, then the whole integer is 6819 // uninitialized. 6820 if (!Bytes[I.getQuantity()]) 6821 return false; 6822 Output.push_back(*Bytes[I.getQuantity()]); 6823 } 6824 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6825 std::reverse(Output.begin(), Output.end()); 6826 return true; 6827 } 6828 6829 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6830 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6831 std::reverse(Input.begin(), Input.end()); 6832 6833 size_t Index = 0; 6834 for (unsigned char Byte : Input) { 6835 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6836 Bytes[Offset.getQuantity() + Index] = Byte; 6837 ++Index; 6838 } 6839 } 6840 6841 size_t size() { return Bytes.size(); } 6842 }; 6843 6844 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6845 /// target would represent the value at runtime. 6846 class APValueToBufferConverter { 6847 EvalInfo &Info; 6848 BitCastBuffer Buffer; 6849 const CastExpr *BCE; 6850 6851 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6852 const CastExpr *BCE) 6853 : Info(Info), 6854 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6855 BCE(BCE) {} 6856 6857 bool visit(const APValue &Val, QualType Ty) { 6858 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6859 } 6860 6861 // Write out Val with type Ty into Buffer starting at Offset. 6862 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6863 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6864 6865 // As a special case, nullptr_t has an indeterminate value. 6866 if (Ty->isNullPtrType()) 6867 return true; 6868 6869 // Dig through Src to find the byte at SrcOffset. 6870 switch (Val.getKind()) { 6871 case APValue::Indeterminate: 6872 case APValue::None: 6873 return true; 6874 6875 case APValue::Int: 6876 return visitInt(Val.getInt(), Ty, Offset); 6877 case APValue::Float: 6878 return visitFloat(Val.getFloat(), Ty, Offset); 6879 case APValue::Array: 6880 return visitArray(Val, Ty, Offset); 6881 case APValue::Struct: 6882 return visitRecord(Val, Ty, Offset); 6883 6884 case APValue::ComplexInt: 6885 case APValue::ComplexFloat: 6886 case APValue::Vector: 6887 case APValue::FixedPoint: 6888 // FIXME: We should support these. 6889 6890 case APValue::Union: 6891 case APValue::MemberPointer: 6892 case APValue::AddrLabelDiff: { 6893 Info.FFDiag(BCE->getBeginLoc(), 6894 diag::note_constexpr_bit_cast_unsupported_type) 6895 << Ty; 6896 return false; 6897 } 6898 6899 case APValue::LValue: 6900 llvm_unreachable("LValue subobject in bit_cast?"); 6901 } 6902 llvm_unreachable("Unhandled APValue::ValueKind"); 6903 } 6904 6905 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6906 const RecordDecl *RD = Ty->getAsRecordDecl(); 6907 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6908 6909 // Visit the base classes. 6910 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6911 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6912 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6913 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6914 6915 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6916 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6917 return false; 6918 } 6919 } 6920 6921 // Visit the fields. 6922 unsigned FieldIdx = 0; 6923 for (FieldDecl *FD : RD->fields()) { 6924 if (FD->isBitField()) { 6925 Info.FFDiag(BCE->getBeginLoc(), 6926 diag::note_constexpr_bit_cast_unsupported_bitfield); 6927 return false; 6928 } 6929 6930 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6931 6932 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6933 "only bit-fields can have sub-char alignment"); 6934 CharUnits FieldOffset = 6935 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6936 QualType FieldTy = FD->getType(); 6937 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6938 return false; 6939 ++FieldIdx; 6940 } 6941 6942 return true; 6943 } 6944 6945 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6946 const auto *CAT = 6947 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6948 if (!CAT) 6949 return false; 6950 6951 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6952 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6953 unsigned ArraySize = Val.getArraySize(); 6954 // First, initialize the initialized elements. 6955 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6956 const APValue &SubObj = Val.getArrayInitializedElt(I); 6957 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6958 return false; 6959 } 6960 6961 // Next, initialize the rest of the array using the filler. 6962 if (Val.hasArrayFiller()) { 6963 const APValue &Filler = Val.getArrayFiller(); 6964 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6965 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6966 return false; 6967 } 6968 } 6969 6970 return true; 6971 } 6972 6973 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6974 APSInt AdjustedVal = Val; 6975 unsigned Width = AdjustedVal.getBitWidth(); 6976 if (Ty->isBooleanType()) { 6977 Width = Info.Ctx.getTypeSize(Ty); 6978 AdjustedVal = AdjustedVal.extend(Width); 6979 } 6980 6981 SmallVector<unsigned char, 8> Bytes(Width / 8); 6982 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6983 Buffer.writeObject(Offset, Bytes); 6984 return true; 6985 } 6986 6987 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6988 APSInt AsInt(Val.bitcastToAPInt()); 6989 return visitInt(AsInt, Ty, Offset); 6990 } 6991 6992 public: 6993 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6994 const CastExpr *BCE) { 6995 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6996 APValueToBufferConverter Converter(Info, DstSize, BCE); 6997 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6998 return None; 6999 return Converter.Buffer; 7000 } 7001 }; 7002 7003 /// Write an BitCastBuffer into an APValue. 7004 class BufferToAPValueConverter { 7005 EvalInfo &Info; 7006 const BitCastBuffer &Buffer; 7007 const CastExpr *BCE; 7008 7009 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 7010 const CastExpr *BCE) 7011 : Info(Info), Buffer(Buffer), BCE(BCE) {} 7012 7013 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 7014 // with an invalid type, so anything left is a deficiency on our part (FIXME). 7015 // Ideally this will be unreachable. 7016 llvm::NoneType unsupportedType(QualType Ty) { 7017 Info.FFDiag(BCE->getBeginLoc(), 7018 diag::note_constexpr_bit_cast_unsupported_type) 7019 << Ty; 7020 return None; 7021 } 7022 7023 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 7024 Info.FFDiag(BCE->getBeginLoc(), 7025 diag::note_constexpr_bit_cast_unrepresentable_value) 7026 << Ty << toString(Val, /*Radix=*/10); 7027 return None; 7028 } 7029 7030 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 7031 const EnumType *EnumSugar = nullptr) { 7032 if (T->isNullPtrType()) { 7033 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 7034 return APValue((Expr *)nullptr, 7035 /*Offset=*/CharUnits::fromQuantity(NullValue), 7036 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 7037 } 7038 7039 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 7040 7041 // Work around floating point types that contain unused padding bytes. This 7042 // is really just `long double` on x86, which is the only fundamental type 7043 // with padding bytes. 7044 if (T->isRealFloatingType()) { 7045 const llvm::fltSemantics &Semantics = 7046 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7047 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 7048 assert(NumBits % 8 == 0); 7049 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 7050 if (NumBytes != SizeOf) 7051 SizeOf = NumBytes; 7052 } 7053 7054 SmallVector<uint8_t, 8> Bytes; 7055 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 7056 // If this is std::byte or unsigned char, then its okay to store an 7057 // indeterminate value. 7058 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7059 bool IsUChar = 7060 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7061 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7062 if (!IsStdByte && !IsUChar) { 7063 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7064 Info.FFDiag(BCE->getExprLoc(), 7065 diag::note_constexpr_bit_cast_indet_dest) 7066 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7067 return None; 7068 } 7069 7070 return APValue::IndeterminateValue(); 7071 } 7072 7073 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7074 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7075 7076 if (T->isIntegralOrEnumerationType()) { 7077 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7078 7079 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7080 if (IntWidth != Val.getBitWidth()) { 7081 APSInt Truncated = Val.trunc(IntWidth); 7082 if (Truncated.extend(Val.getBitWidth()) != Val) 7083 return unrepresentableValue(QualType(T, 0), Val); 7084 Val = Truncated; 7085 } 7086 7087 return APValue(Val); 7088 } 7089 7090 if (T->isRealFloatingType()) { 7091 const llvm::fltSemantics &Semantics = 7092 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7093 return APValue(APFloat(Semantics, Val)); 7094 } 7095 7096 return unsupportedType(QualType(T, 0)); 7097 } 7098 7099 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7100 const RecordDecl *RD = RTy->getAsRecordDecl(); 7101 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7102 7103 unsigned NumBases = 0; 7104 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7105 NumBases = CXXRD->getNumBases(); 7106 7107 APValue ResultVal(APValue::UninitStruct(), NumBases, 7108 std::distance(RD->field_begin(), RD->field_end())); 7109 7110 // Visit the base classes. 7111 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7112 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7113 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7114 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7115 if (BaseDecl->isEmpty() || 7116 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7117 continue; 7118 7119 Optional<APValue> SubObj = visitType( 7120 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7121 if (!SubObj) 7122 return None; 7123 ResultVal.getStructBase(I) = *SubObj; 7124 } 7125 } 7126 7127 // Visit the fields. 7128 unsigned FieldIdx = 0; 7129 for (FieldDecl *FD : RD->fields()) { 7130 // FIXME: We don't currently support bit-fields. A lot of the logic for 7131 // this is in CodeGen, so we need to factor it around. 7132 if (FD->isBitField()) { 7133 Info.FFDiag(BCE->getBeginLoc(), 7134 diag::note_constexpr_bit_cast_unsupported_bitfield); 7135 return None; 7136 } 7137 7138 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7139 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7140 7141 CharUnits FieldOffset = 7142 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7143 Offset; 7144 QualType FieldTy = FD->getType(); 7145 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7146 if (!SubObj) 7147 return None; 7148 ResultVal.getStructField(FieldIdx) = *SubObj; 7149 ++FieldIdx; 7150 } 7151 7152 return ResultVal; 7153 } 7154 7155 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7156 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7157 assert(!RepresentationType.isNull() && 7158 "enum forward decl should be caught by Sema"); 7159 const auto *AsBuiltin = 7160 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7161 // Recurse into the underlying type. Treat std::byte transparently as 7162 // unsigned char. 7163 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7164 } 7165 7166 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7167 size_t Size = Ty->getSize().getLimitedValue(); 7168 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7169 7170 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7171 for (size_t I = 0; I != Size; ++I) { 7172 Optional<APValue> ElementValue = 7173 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7174 if (!ElementValue) 7175 return None; 7176 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7177 } 7178 7179 return ArrayValue; 7180 } 7181 7182 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7183 return unsupportedType(QualType(Ty, 0)); 7184 } 7185 7186 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7187 QualType Can = Ty.getCanonicalType(); 7188 7189 switch (Can->getTypeClass()) { 7190 #define TYPE(Class, Base) \ 7191 case Type::Class: \ 7192 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7193 #define ABSTRACT_TYPE(Class, Base) 7194 #define NON_CANONICAL_TYPE(Class, Base) \ 7195 case Type::Class: \ 7196 llvm_unreachable("non-canonical type should be impossible!"); 7197 #define DEPENDENT_TYPE(Class, Base) \ 7198 case Type::Class: \ 7199 llvm_unreachable( \ 7200 "dependent types aren't supported in the constant evaluator!"); 7201 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7202 case Type::Class: \ 7203 llvm_unreachable("either dependent or not canonical!"); 7204 #include "clang/AST/TypeNodes.inc" 7205 } 7206 llvm_unreachable("Unhandled Type::TypeClass"); 7207 } 7208 7209 public: 7210 // Pull out a full value of type DstType. 7211 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7212 const CastExpr *BCE) { 7213 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7214 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7215 } 7216 }; 7217 7218 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7219 QualType Ty, EvalInfo *Info, 7220 const ASTContext &Ctx, 7221 bool CheckingDest) { 7222 Ty = Ty.getCanonicalType(); 7223 7224 auto diag = [&](int Reason) { 7225 if (Info) 7226 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7227 << CheckingDest << (Reason == 4) << Reason; 7228 return false; 7229 }; 7230 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7231 if (Info) 7232 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7233 << NoteTy << Construct << Ty; 7234 return false; 7235 }; 7236 7237 if (Ty->isUnionType()) 7238 return diag(0); 7239 if (Ty->isPointerType()) 7240 return diag(1); 7241 if (Ty->isMemberPointerType()) 7242 return diag(2); 7243 if (Ty.isVolatileQualified()) 7244 return diag(3); 7245 7246 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7247 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7248 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7249 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7250 CheckingDest)) 7251 return note(1, BS.getType(), BS.getBeginLoc()); 7252 } 7253 for (FieldDecl *FD : Record->fields()) { 7254 if (FD->getType()->isReferenceType()) 7255 return diag(4); 7256 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7257 CheckingDest)) 7258 return note(0, FD->getType(), FD->getBeginLoc()); 7259 } 7260 } 7261 7262 if (Ty->isArrayType() && 7263 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7264 Info, Ctx, CheckingDest)) 7265 return false; 7266 7267 return true; 7268 } 7269 7270 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7271 const ASTContext &Ctx, 7272 const CastExpr *BCE) { 7273 bool DestOK = checkBitCastConstexprEligibilityType( 7274 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7275 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7276 BCE->getBeginLoc(), 7277 BCE->getSubExpr()->getType(), Info, Ctx, false); 7278 return SourceOK; 7279 } 7280 7281 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7282 APValue &SourceValue, 7283 const CastExpr *BCE) { 7284 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7285 "no host or target supports non 8-bit chars"); 7286 assert(SourceValue.isLValue() && 7287 "LValueToRValueBitcast requires an lvalue operand!"); 7288 7289 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7290 return false; 7291 7292 LValue SourceLValue; 7293 APValue SourceRValue; 7294 SourceLValue.setFrom(Info.Ctx, SourceValue); 7295 if (!handleLValueToRValueConversion( 7296 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7297 SourceRValue, /*WantObjectRepresentation=*/true)) 7298 return false; 7299 7300 // Read out SourceValue into a char buffer. 7301 Optional<BitCastBuffer> Buffer = 7302 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7303 if (!Buffer) 7304 return false; 7305 7306 // Write out the buffer into a new APValue. 7307 Optional<APValue> MaybeDestValue = 7308 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7309 if (!MaybeDestValue) 7310 return false; 7311 7312 DestValue = std::move(*MaybeDestValue); 7313 return true; 7314 } 7315 7316 template <class Derived> 7317 class ExprEvaluatorBase 7318 : public ConstStmtVisitor<Derived, bool> { 7319 private: 7320 Derived &getDerived() { return static_cast<Derived&>(*this); } 7321 bool DerivedSuccess(const APValue &V, const Expr *E) { 7322 return getDerived().Success(V, E); 7323 } 7324 bool DerivedZeroInitialization(const Expr *E) { 7325 return getDerived().ZeroInitialization(E); 7326 } 7327 7328 // Check whether a conditional operator with a non-constant condition is a 7329 // potential constant expression. If neither arm is a potential constant 7330 // expression, then the conditional operator is not either. 7331 template<typename ConditionalOperator> 7332 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7333 assert(Info.checkingPotentialConstantExpression()); 7334 7335 // Speculatively evaluate both arms. 7336 SmallVector<PartialDiagnosticAt, 8> Diag; 7337 { 7338 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7339 StmtVisitorTy::Visit(E->getFalseExpr()); 7340 if (Diag.empty()) 7341 return; 7342 } 7343 7344 { 7345 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7346 Diag.clear(); 7347 StmtVisitorTy::Visit(E->getTrueExpr()); 7348 if (Diag.empty()) 7349 return; 7350 } 7351 7352 Error(E, diag::note_constexpr_conditional_never_const); 7353 } 7354 7355 7356 template<typename ConditionalOperator> 7357 bool HandleConditionalOperator(const ConditionalOperator *E) { 7358 bool BoolResult; 7359 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7360 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7361 CheckPotentialConstantConditional(E); 7362 return false; 7363 } 7364 if (Info.noteFailure()) { 7365 StmtVisitorTy::Visit(E->getTrueExpr()); 7366 StmtVisitorTy::Visit(E->getFalseExpr()); 7367 } 7368 return false; 7369 } 7370 7371 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7372 return StmtVisitorTy::Visit(EvalExpr); 7373 } 7374 7375 protected: 7376 EvalInfo &Info; 7377 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7378 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7379 7380 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7381 return Info.CCEDiag(E, D); 7382 } 7383 7384 bool ZeroInitialization(const Expr *E) { return Error(E); } 7385 7386 public: 7387 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7388 7389 EvalInfo &getEvalInfo() { return Info; } 7390 7391 /// Report an evaluation error. This should only be called when an error is 7392 /// first discovered. When propagating an error, just return false. 7393 bool Error(const Expr *E, diag::kind D) { 7394 Info.FFDiag(E, D); 7395 return false; 7396 } 7397 bool Error(const Expr *E) { 7398 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7399 } 7400 7401 bool VisitStmt(const Stmt *) { 7402 llvm_unreachable("Expression evaluator should not be called on stmts"); 7403 } 7404 bool VisitExpr(const Expr *E) { 7405 return Error(E); 7406 } 7407 7408 bool VisitConstantExpr(const ConstantExpr *E) { 7409 if (E->hasAPValueResult()) 7410 return DerivedSuccess(E->getAPValueResult(), E); 7411 7412 return StmtVisitorTy::Visit(E->getSubExpr()); 7413 } 7414 7415 bool VisitParenExpr(const ParenExpr *E) 7416 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7417 bool VisitUnaryExtension(const UnaryOperator *E) 7418 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7419 bool VisitUnaryPlus(const UnaryOperator *E) 7420 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7421 bool VisitChooseExpr(const ChooseExpr *E) 7422 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7423 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7424 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7425 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7426 { return StmtVisitorTy::Visit(E->getReplacement()); } 7427 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7428 TempVersionRAII RAII(*Info.CurrentCall); 7429 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7430 return StmtVisitorTy::Visit(E->getExpr()); 7431 } 7432 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7433 TempVersionRAII RAII(*Info.CurrentCall); 7434 // The initializer may not have been parsed yet, or might be erroneous. 7435 if (!E->getExpr()) 7436 return Error(E); 7437 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7438 return StmtVisitorTy::Visit(E->getExpr()); 7439 } 7440 7441 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7442 FullExpressionRAII Scope(Info); 7443 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7444 } 7445 7446 // Temporaries are registered when created, so we don't care about 7447 // CXXBindTemporaryExpr. 7448 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7449 return StmtVisitorTy::Visit(E->getSubExpr()); 7450 } 7451 7452 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7453 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7454 return static_cast<Derived*>(this)->VisitCastExpr(E); 7455 } 7456 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7457 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7458 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7459 return static_cast<Derived*>(this)->VisitCastExpr(E); 7460 } 7461 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7462 return static_cast<Derived*>(this)->VisitCastExpr(E); 7463 } 7464 7465 bool VisitBinaryOperator(const BinaryOperator *E) { 7466 switch (E->getOpcode()) { 7467 default: 7468 return Error(E); 7469 7470 case BO_Comma: 7471 VisitIgnoredValue(E->getLHS()); 7472 return StmtVisitorTy::Visit(E->getRHS()); 7473 7474 case BO_PtrMemD: 7475 case BO_PtrMemI: { 7476 LValue Obj; 7477 if (!HandleMemberPointerAccess(Info, E, Obj)) 7478 return false; 7479 APValue Result; 7480 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7481 return false; 7482 return DerivedSuccess(Result, E); 7483 } 7484 } 7485 } 7486 7487 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7488 return StmtVisitorTy::Visit(E->getSemanticForm()); 7489 } 7490 7491 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7492 // Evaluate and cache the common expression. We treat it as a temporary, 7493 // even though it's not quite the same thing. 7494 LValue CommonLV; 7495 if (!Evaluate(Info.CurrentCall->createTemporary( 7496 E->getOpaqueValue(), 7497 getStorageType(Info.Ctx, E->getOpaqueValue()), 7498 ScopeKind::FullExpression, CommonLV), 7499 Info, E->getCommon())) 7500 return false; 7501 7502 return HandleConditionalOperator(E); 7503 } 7504 7505 bool VisitConditionalOperator(const ConditionalOperator *E) { 7506 bool IsBcpCall = false; 7507 // If the condition (ignoring parens) is a __builtin_constant_p call, 7508 // the result is a constant expression if it can be folded without 7509 // side-effects. This is an important GNU extension. See GCC PR38377 7510 // for discussion. 7511 if (const CallExpr *CallCE = 7512 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7513 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7514 IsBcpCall = true; 7515 7516 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7517 // constant expression; we can't check whether it's potentially foldable. 7518 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7519 // it would return 'false' in this mode. 7520 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7521 return false; 7522 7523 FoldConstant Fold(Info, IsBcpCall); 7524 if (!HandleConditionalOperator(E)) { 7525 Fold.keepDiagnostics(); 7526 return false; 7527 } 7528 7529 return true; 7530 } 7531 7532 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7533 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7534 return DerivedSuccess(*Value, E); 7535 7536 const Expr *Source = E->getSourceExpr(); 7537 if (!Source) 7538 return Error(E); 7539 if (Source == E) { 7540 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7541 return Error(E); 7542 } 7543 return StmtVisitorTy::Visit(Source); 7544 } 7545 7546 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7547 for (const Expr *SemE : E->semantics()) { 7548 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7549 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7550 // result expression: there could be two different LValues that would 7551 // refer to the same object in that case, and we can't model that. 7552 if (SemE == E->getResultExpr()) 7553 return Error(E); 7554 7555 // Unique OVEs get evaluated if and when we encounter them when 7556 // emitting the rest of the semantic form, rather than eagerly. 7557 if (OVE->isUnique()) 7558 continue; 7559 7560 LValue LV; 7561 if (!Evaluate(Info.CurrentCall->createTemporary( 7562 OVE, getStorageType(Info.Ctx, OVE), 7563 ScopeKind::FullExpression, LV), 7564 Info, OVE->getSourceExpr())) 7565 return false; 7566 } else if (SemE == E->getResultExpr()) { 7567 if (!StmtVisitorTy::Visit(SemE)) 7568 return false; 7569 } else { 7570 if (!EvaluateIgnoredValue(Info, SemE)) 7571 return false; 7572 } 7573 } 7574 return true; 7575 } 7576 7577 bool VisitCallExpr(const CallExpr *E) { 7578 APValue Result; 7579 if (!handleCallExpr(E, Result, nullptr)) 7580 return false; 7581 return DerivedSuccess(Result, E); 7582 } 7583 7584 bool handleCallExpr(const CallExpr *E, APValue &Result, 7585 const LValue *ResultSlot) { 7586 CallScopeRAII CallScope(Info); 7587 7588 const Expr *Callee = E->getCallee()->IgnoreParens(); 7589 QualType CalleeType = Callee->getType(); 7590 7591 const FunctionDecl *FD = nullptr; 7592 LValue *This = nullptr, ThisVal; 7593 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7594 bool HasQualifier = false; 7595 7596 CallRef Call; 7597 7598 // Extract function decl and 'this' pointer from the callee. 7599 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7600 const CXXMethodDecl *Member = nullptr; 7601 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7602 // Explicit bound member calls, such as x.f() or p->g(); 7603 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7604 return false; 7605 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7606 if (!Member) 7607 return Error(Callee); 7608 This = &ThisVal; 7609 HasQualifier = ME->hasQualifier(); 7610 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7611 // Indirect bound member calls ('.*' or '->*'). 7612 const ValueDecl *D = 7613 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7614 if (!D) 7615 return false; 7616 Member = dyn_cast<CXXMethodDecl>(D); 7617 if (!Member) 7618 return Error(Callee); 7619 This = &ThisVal; 7620 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7621 if (!Info.getLangOpts().CPlusPlus20) 7622 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7623 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7624 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7625 } else 7626 return Error(Callee); 7627 FD = Member; 7628 } else if (CalleeType->isFunctionPointerType()) { 7629 LValue CalleeLV; 7630 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7631 return false; 7632 7633 if (!CalleeLV.getLValueOffset().isZero()) 7634 return Error(Callee); 7635 FD = dyn_cast_or_null<FunctionDecl>( 7636 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7637 if (!FD) 7638 return Error(Callee); 7639 // Don't call function pointers which have been cast to some other type. 7640 // Per DR (no number yet), the caller and callee can differ in noexcept. 7641 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7642 CalleeType->getPointeeType(), FD->getType())) { 7643 return Error(E); 7644 } 7645 7646 // For an (overloaded) assignment expression, evaluate the RHS before the 7647 // LHS. 7648 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7649 if (OCE && OCE->isAssignmentOp()) { 7650 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7651 Call = Info.CurrentCall->createCall(FD); 7652 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7653 Info, FD, /*RightToLeft=*/true)) 7654 return false; 7655 } 7656 7657 // Overloaded operator calls to member functions are represented as normal 7658 // calls with '*this' as the first argument. 7659 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7660 if (MD && !MD->isStatic()) { 7661 // FIXME: When selecting an implicit conversion for an overloaded 7662 // operator delete, we sometimes try to evaluate calls to conversion 7663 // operators without a 'this' parameter! 7664 if (Args.empty()) 7665 return Error(E); 7666 7667 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7668 return false; 7669 This = &ThisVal; 7670 7671 // If this is syntactically a simple assignment using a trivial 7672 // assignment operator, start the lifetimes of union members as needed, 7673 // per C++20 [class.union]5. 7674 if (Info.getLangOpts().CPlusPlus20 && OCE && 7675 OCE->getOperator() == OO_Equal && MD->isTrivial() && 7676 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal)) 7677 return false; 7678 7679 Args = Args.slice(1); 7680 } else if (MD && MD->isLambdaStaticInvoker()) { 7681 // Map the static invoker for the lambda back to the call operator. 7682 // Conveniently, we don't have to slice out the 'this' argument (as is 7683 // being done for the non-static case), since a static member function 7684 // doesn't have an implicit argument passed in. 7685 const CXXRecordDecl *ClosureClass = MD->getParent(); 7686 assert( 7687 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7688 "Number of captures must be zero for conversion to function-ptr"); 7689 7690 const CXXMethodDecl *LambdaCallOp = 7691 ClosureClass->getLambdaCallOperator(); 7692 7693 // Set 'FD', the function that will be called below, to the call 7694 // operator. If the closure object represents a generic lambda, find 7695 // the corresponding specialization of the call operator. 7696 7697 if (ClosureClass->isGenericLambda()) { 7698 assert(MD->isFunctionTemplateSpecialization() && 7699 "A generic lambda's static-invoker function must be a " 7700 "template specialization"); 7701 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7702 FunctionTemplateDecl *CallOpTemplate = 7703 LambdaCallOp->getDescribedFunctionTemplate(); 7704 void *InsertPos = nullptr; 7705 FunctionDecl *CorrespondingCallOpSpecialization = 7706 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7707 assert(CorrespondingCallOpSpecialization && 7708 "We must always have a function call operator specialization " 7709 "that corresponds to our static invoker specialization"); 7710 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7711 } else 7712 FD = LambdaCallOp; 7713 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7714 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7715 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7716 LValue Ptr; 7717 if (!HandleOperatorNewCall(Info, E, Ptr)) 7718 return false; 7719 Ptr.moveInto(Result); 7720 return CallScope.destroy(); 7721 } else { 7722 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7723 } 7724 } 7725 } else 7726 return Error(E); 7727 7728 // Evaluate the arguments now if we've not already done so. 7729 if (!Call) { 7730 Call = Info.CurrentCall->createCall(FD); 7731 if (!EvaluateArgs(Args, Call, Info, FD)) 7732 return false; 7733 } 7734 7735 SmallVector<QualType, 4> CovariantAdjustmentPath; 7736 if (This) { 7737 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7738 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7739 // Perform virtual dispatch, if necessary. 7740 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7741 CovariantAdjustmentPath); 7742 if (!FD) 7743 return false; 7744 } else { 7745 // Check that the 'this' pointer points to an object of the right type. 7746 // FIXME: If this is an assignment operator call, we may need to change 7747 // the active union member before we check this. 7748 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7749 return false; 7750 } 7751 } 7752 7753 // Destructor calls are different enough that they have their own codepath. 7754 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7755 assert(This && "no 'this' pointer for destructor call"); 7756 return HandleDestruction(Info, E, *This, 7757 Info.Ctx.getRecordType(DD->getParent())) && 7758 CallScope.destroy(); 7759 } 7760 7761 const FunctionDecl *Definition = nullptr; 7762 Stmt *Body = FD->getBody(Definition); 7763 7764 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7765 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7766 Body, Info, Result, ResultSlot)) 7767 return false; 7768 7769 if (!CovariantAdjustmentPath.empty() && 7770 !HandleCovariantReturnAdjustment(Info, E, Result, 7771 CovariantAdjustmentPath)) 7772 return false; 7773 7774 return CallScope.destroy(); 7775 } 7776 7777 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7778 return StmtVisitorTy::Visit(E->getInitializer()); 7779 } 7780 bool VisitInitListExpr(const InitListExpr *E) { 7781 if (E->getNumInits() == 0) 7782 return DerivedZeroInitialization(E); 7783 if (E->getNumInits() == 1) 7784 return StmtVisitorTy::Visit(E->getInit(0)); 7785 return Error(E); 7786 } 7787 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7788 return DerivedZeroInitialization(E); 7789 } 7790 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7791 return DerivedZeroInitialization(E); 7792 } 7793 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7794 return DerivedZeroInitialization(E); 7795 } 7796 7797 /// A member expression where the object is a prvalue is itself a prvalue. 7798 bool VisitMemberExpr(const MemberExpr *E) { 7799 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7800 "missing temporary materialization conversion"); 7801 assert(!E->isArrow() && "missing call to bound member function?"); 7802 7803 APValue Val; 7804 if (!Evaluate(Val, Info, E->getBase())) 7805 return false; 7806 7807 QualType BaseTy = E->getBase()->getType(); 7808 7809 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7810 if (!FD) return Error(E); 7811 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7812 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7813 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7814 7815 // Note: there is no lvalue base here. But this case should only ever 7816 // happen in C or in C++98, where we cannot be evaluating a constexpr 7817 // constructor, which is the only case the base matters. 7818 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7819 SubobjectDesignator Designator(BaseTy); 7820 Designator.addDeclUnchecked(FD); 7821 7822 APValue Result; 7823 return extractSubobject(Info, E, Obj, Designator, Result) && 7824 DerivedSuccess(Result, E); 7825 } 7826 7827 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7828 APValue Val; 7829 if (!Evaluate(Val, Info, E->getBase())) 7830 return false; 7831 7832 if (Val.isVector()) { 7833 SmallVector<uint32_t, 4> Indices; 7834 E->getEncodedElementAccess(Indices); 7835 if (Indices.size() == 1) { 7836 // Return scalar. 7837 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7838 } else { 7839 // Construct new APValue vector. 7840 SmallVector<APValue, 4> Elts; 7841 for (unsigned I = 0; I < Indices.size(); ++I) { 7842 Elts.push_back(Val.getVectorElt(Indices[I])); 7843 } 7844 APValue VecResult(Elts.data(), Indices.size()); 7845 return DerivedSuccess(VecResult, E); 7846 } 7847 } 7848 7849 return false; 7850 } 7851 7852 bool VisitCastExpr(const CastExpr *E) { 7853 switch (E->getCastKind()) { 7854 default: 7855 break; 7856 7857 case CK_AtomicToNonAtomic: { 7858 APValue AtomicVal; 7859 // This does not need to be done in place even for class/array types: 7860 // atomic-to-non-atomic conversion implies copying the object 7861 // representation. 7862 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7863 return false; 7864 return DerivedSuccess(AtomicVal, E); 7865 } 7866 7867 case CK_NoOp: 7868 case CK_UserDefinedConversion: 7869 return StmtVisitorTy::Visit(E->getSubExpr()); 7870 7871 case CK_LValueToRValue: { 7872 LValue LVal; 7873 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7874 return false; 7875 APValue RVal; 7876 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7877 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7878 LVal, RVal)) 7879 return false; 7880 return DerivedSuccess(RVal, E); 7881 } 7882 case CK_LValueToRValueBitCast: { 7883 APValue DestValue, SourceValue; 7884 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7885 return false; 7886 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7887 return false; 7888 return DerivedSuccess(DestValue, E); 7889 } 7890 7891 case CK_AddressSpaceConversion: { 7892 APValue Value; 7893 if (!Evaluate(Value, Info, E->getSubExpr())) 7894 return false; 7895 return DerivedSuccess(Value, E); 7896 } 7897 } 7898 7899 return Error(E); 7900 } 7901 7902 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7903 return VisitUnaryPostIncDec(UO); 7904 } 7905 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7906 return VisitUnaryPostIncDec(UO); 7907 } 7908 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7909 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7910 return Error(UO); 7911 7912 LValue LVal; 7913 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7914 return false; 7915 APValue RVal; 7916 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7917 UO->isIncrementOp(), &RVal)) 7918 return false; 7919 return DerivedSuccess(RVal, UO); 7920 } 7921 7922 bool VisitStmtExpr(const StmtExpr *E) { 7923 // We will have checked the full-expressions inside the statement expression 7924 // when they were completed, and don't need to check them again now. 7925 llvm::SaveAndRestore<bool> NotCheckingForUB( 7926 Info.CheckingForUndefinedBehavior, false); 7927 7928 const CompoundStmt *CS = E->getSubStmt(); 7929 if (CS->body_empty()) 7930 return true; 7931 7932 BlockScopeRAII Scope(Info); 7933 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7934 BE = CS->body_end(); 7935 /**/; ++BI) { 7936 if (BI + 1 == BE) { 7937 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7938 if (!FinalExpr) { 7939 Info.FFDiag((*BI)->getBeginLoc(), 7940 diag::note_constexpr_stmt_expr_unsupported); 7941 return false; 7942 } 7943 return this->Visit(FinalExpr) && Scope.destroy(); 7944 } 7945 7946 APValue ReturnValue; 7947 StmtResult Result = { ReturnValue, nullptr }; 7948 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7949 if (ESR != ESR_Succeeded) { 7950 // FIXME: If the statement-expression terminated due to 'return', 7951 // 'break', or 'continue', it would be nice to propagate that to 7952 // the outer statement evaluation rather than bailing out. 7953 if (ESR != ESR_Failed) 7954 Info.FFDiag((*BI)->getBeginLoc(), 7955 diag::note_constexpr_stmt_expr_unsupported); 7956 return false; 7957 } 7958 } 7959 7960 llvm_unreachable("Return from function from the loop above."); 7961 } 7962 7963 /// Visit a value which is evaluated, but whose value is ignored. 7964 void VisitIgnoredValue(const Expr *E) { 7965 EvaluateIgnoredValue(Info, E); 7966 } 7967 7968 /// Potentially visit a MemberExpr's base expression. 7969 void VisitIgnoredBaseExpression(const Expr *E) { 7970 // While MSVC doesn't evaluate the base expression, it does diagnose the 7971 // presence of side-effecting behavior. 7972 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7973 return; 7974 VisitIgnoredValue(E); 7975 } 7976 }; 7977 7978 } // namespace 7979 7980 //===----------------------------------------------------------------------===// 7981 // Common base class for lvalue and temporary evaluation. 7982 //===----------------------------------------------------------------------===// 7983 namespace { 7984 template<class Derived> 7985 class LValueExprEvaluatorBase 7986 : public ExprEvaluatorBase<Derived> { 7987 protected: 7988 LValue &Result; 7989 bool InvalidBaseOK; 7990 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7991 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7992 7993 bool Success(APValue::LValueBase B) { 7994 Result.set(B); 7995 return true; 7996 } 7997 7998 bool evaluatePointer(const Expr *E, LValue &Result) { 7999 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 8000 } 8001 8002 public: 8003 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 8004 : ExprEvaluatorBaseTy(Info), Result(Result), 8005 InvalidBaseOK(InvalidBaseOK) {} 8006 8007 bool Success(const APValue &V, const Expr *E) { 8008 Result.setFrom(this->Info.Ctx, V); 8009 return true; 8010 } 8011 8012 bool VisitMemberExpr(const MemberExpr *E) { 8013 // Handle non-static data members. 8014 QualType BaseTy; 8015 bool EvalOK; 8016 if (E->isArrow()) { 8017 EvalOK = evaluatePointer(E->getBase(), Result); 8018 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 8019 } else if (E->getBase()->isPRValue()) { 8020 assert(E->getBase()->getType()->isRecordType()); 8021 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 8022 BaseTy = E->getBase()->getType(); 8023 } else { 8024 EvalOK = this->Visit(E->getBase()); 8025 BaseTy = E->getBase()->getType(); 8026 } 8027 if (!EvalOK) { 8028 if (!InvalidBaseOK) 8029 return false; 8030 Result.setInvalid(E); 8031 return true; 8032 } 8033 8034 const ValueDecl *MD = E->getMemberDecl(); 8035 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 8036 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 8037 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 8038 (void)BaseTy; 8039 if (!HandleLValueMember(this->Info, E, Result, FD)) 8040 return false; 8041 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 8042 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 8043 return false; 8044 } else 8045 return this->Error(E); 8046 8047 if (MD->getType()->isReferenceType()) { 8048 APValue RefValue; 8049 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 8050 RefValue)) 8051 return false; 8052 return Success(RefValue, E); 8053 } 8054 return true; 8055 } 8056 8057 bool VisitBinaryOperator(const BinaryOperator *E) { 8058 switch (E->getOpcode()) { 8059 default: 8060 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8061 8062 case BO_PtrMemD: 8063 case BO_PtrMemI: 8064 return HandleMemberPointerAccess(this->Info, E, Result); 8065 } 8066 } 8067 8068 bool VisitCastExpr(const CastExpr *E) { 8069 switch (E->getCastKind()) { 8070 default: 8071 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8072 8073 case CK_DerivedToBase: 8074 case CK_UncheckedDerivedToBase: 8075 if (!this->Visit(E->getSubExpr())) 8076 return false; 8077 8078 // Now figure out the necessary offset to add to the base LV to get from 8079 // the derived class to the base class. 8080 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8081 Result); 8082 } 8083 } 8084 }; 8085 } 8086 8087 //===----------------------------------------------------------------------===// 8088 // LValue Evaluation 8089 // 8090 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8091 // function designators (in C), decl references to void objects (in C), and 8092 // temporaries (if building with -Wno-address-of-temporary). 8093 // 8094 // LValue evaluation produces values comprising a base expression of one of the 8095 // following types: 8096 // - Declarations 8097 // * VarDecl 8098 // * FunctionDecl 8099 // - Literals 8100 // * CompoundLiteralExpr in C (and in global scope in C++) 8101 // * StringLiteral 8102 // * PredefinedExpr 8103 // * ObjCStringLiteralExpr 8104 // * ObjCEncodeExpr 8105 // * AddrLabelExpr 8106 // * BlockExpr 8107 // * CallExpr for a MakeStringConstant builtin 8108 // - typeid(T) expressions, as TypeInfoLValues 8109 // - Locals and temporaries 8110 // * MaterializeTemporaryExpr 8111 // * Any Expr, with a CallIndex indicating the function in which the temporary 8112 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8113 // from the AST (FIXME). 8114 // * A MaterializeTemporaryExpr that has static storage duration, with no 8115 // CallIndex, for a lifetime-extended temporary. 8116 // * The ConstantExpr that is currently being evaluated during evaluation of an 8117 // immediate invocation. 8118 // plus an offset in bytes. 8119 //===----------------------------------------------------------------------===// 8120 namespace { 8121 class LValueExprEvaluator 8122 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8123 public: 8124 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8125 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8126 8127 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8128 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8129 8130 bool VisitDeclRefExpr(const DeclRefExpr *E); 8131 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8132 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8133 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8134 bool VisitMemberExpr(const MemberExpr *E); 8135 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8136 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8137 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8138 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8139 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8140 bool VisitUnaryDeref(const UnaryOperator *E); 8141 bool VisitUnaryReal(const UnaryOperator *E); 8142 bool VisitUnaryImag(const UnaryOperator *E); 8143 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8144 return VisitUnaryPreIncDec(UO); 8145 } 8146 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8147 return VisitUnaryPreIncDec(UO); 8148 } 8149 bool VisitBinAssign(const BinaryOperator *BO); 8150 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8151 8152 bool VisitCastExpr(const CastExpr *E) { 8153 switch (E->getCastKind()) { 8154 default: 8155 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8156 8157 case CK_LValueBitCast: 8158 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8159 if (!Visit(E->getSubExpr())) 8160 return false; 8161 Result.Designator.setInvalid(); 8162 return true; 8163 8164 case CK_BaseToDerived: 8165 if (!Visit(E->getSubExpr())) 8166 return false; 8167 return HandleBaseToDerivedCast(Info, E, Result); 8168 8169 case CK_Dynamic: 8170 if (!Visit(E->getSubExpr())) 8171 return false; 8172 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8173 } 8174 } 8175 }; 8176 } // end anonymous namespace 8177 8178 /// Evaluate an expression as an lvalue. This can be legitimately called on 8179 /// expressions which are not glvalues, in three cases: 8180 /// * function designators in C, and 8181 /// * "extern void" objects 8182 /// * @selector() expressions in Objective-C 8183 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8184 bool InvalidBaseOK) { 8185 assert(!E->isValueDependent()); 8186 assert(E->isGLValue() || E->getType()->isFunctionType() || 8187 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8188 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8189 } 8190 8191 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8192 const NamedDecl *D = E->getDecl(); 8193 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl, 8194 UnnamedGlobalConstantDecl>(D)) 8195 return Success(cast<ValueDecl>(D)); 8196 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8197 return VisitVarDecl(E, VD); 8198 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8199 return Visit(BD->getBinding()); 8200 return Error(E); 8201 } 8202 8203 8204 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8205 8206 // If we are within a lambda's call operator, check whether the 'VD' referred 8207 // to within 'E' actually represents a lambda-capture that maps to a 8208 // data-member/field within the closure object, and if so, evaluate to the 8209 // field or what the field refers to. 8210 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8211 isa<DeclRefExpr>(E) && 8212 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8213 // We don't always have a complete capture-map when checking or inferring if 8214 // the function call operator meets the requirements of a constexpr function 8215 // - but we don't need to evaluate the captures to determine constexprness 8216 // (dcl.constexpr C++17). 8217 if (Info.checkingPotentialConstantExpression()) 8218 return false; 8219 8220 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8221 // Start with 'Result' referring to the complete closure object... 8222 Result = *Info.CurrentCall->This; 8223 // ... then update it to refer to the field of the closure object 8224 // that represents the capture. 8225 if (!HandleLValueMember(Info, E, Result, FD)) 8226 return false; 8227 // And if the field is of reference type, update 'Result' to refer to what 8228 // the field refers to. 8229 if (FD->getType()->isReferenceType()) { 8230 APValue RVal; 8231 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8232 RVal)) 8233 return false; 8234 Result.setFrom(Info.Ctx, RVal); 8235 } 8236 return true; 8237 } 8238 } 8239 8240 CallStackFrame *Frame = nullptr; 8241 unsigned Version = 0; 8242 if (VD->hasLocalStorage()) { 8243 // Only if a local variable was declared in the function currently being 8244 // evaluated, do we expect to be able to find its value in the current 8245 // frame. (Otherwise it was likely declared in an enclosing context and 8246 // could either have a valid evaluatable value (for e.g. a constexpr 8247 // variable) or be ill-formed (and trigger an appropriate evaluation 8248 // diagnostic)). 8249 CallStackFrame *CurrFrame = Info.CurrentCall; 8250 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8251 // Function parameters are stored in some caller's frame. (Usually the 8252 // immediate caller, but for an inherited constructor they may be more 8253 // distant.) 8254 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8255 if (CurrFrame->Arguments) { 8256 VD = CurrFrame->Arguments.getOrigParam(PVD); 8257 Frame = 8258 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8259 Version = CurrFrame->Arguments.Version; 8260 } 8261 } else { 8262 Frame = CurrFrame; 8263 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8264 } 8265 } 8266 } 8267 8268 if (!VD->getType()->isReferenceType()) { 8269 if (Frame) { 8270 Result.set({VD, Frame->Index, Version}); 8271 return true; 8272 } 8273 return Success(VD); 8274 } 8275 8276 if (!Info.getLangOpts().CPlusPlus11) { 8277 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8278 << VD << VD->getType(); 8279 Info.Note(VD->getLocation(), diag::note_declared_at); 8280 } 8281 8282 APValue *V; 8283 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8284 return false; 8285 if (!V->hasValue()) { 8286 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8287 // adjust the diagnostic to say that. 8288 if (!Info.checkingPotentialConstantExpression()) 8289 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8290 return false; 8291 } 8292 return Success(*V, E); 8293 } 8294 8295 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8296 const MaterializeTemporaryExpr *E) { 8297 // Walk through the expression to find the materialized temporary itself. 8298 SmallVector<const Expr *, 2> CommaLHSs; 8299 SmallVector<SubobjectAdjustment, 2> Adjustments; 8300 const Expr *Inner = 8301 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8302 8303 // If we passed any comma operators, evaluate their LHSs. 8304 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8305 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8306 return false; 8307 8308 // A materialized temporary with static storage duration can appear within the 8309 // result of a constant expression evaluation, so we need to preserve its 8310 // value for use outside this evaluation. 8311 APValue *Value; 8312 if (E->getStorageDuration() == SD_Static) { 8313 // FIXME: What about SD_Thread? 8314 Value = E->getOrCreateValue(true); 8315 *Value = APValue(); 8316 Result.set(E); 8317 } else { 8318 Value = &Info.CurrentCall->createTemporary( 8319 E, E->getType(), 8320 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8321 : ScopeKind::Block, 8322 Result); 8323 } 8324 8325 QualType Type = Inner->getType(); 8326 8327 // Materialize the temporary itself. 8328 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8329 *Value = APValue(); 8330 return false; 8331 } 8332 8333 // Adjust our lvalue to refer to the desired subobject. 8334 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8335 --I; 8336 switch (Adjustments[I].Kind) { 8337 case SubobjectAdjustment::DerivedToBaseAdjustment: 8338 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8339 Type, Result)) 8340 return false; 8341 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8342 break; 8343 8344 case SubobjectAdjustment::FieldAdjustment: 8345 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8346 return false; 8347 Type = Adjustments[I].Field->getType(); 8348 break; 8349 8350 case SubobjectAdjustment::MemberPointerAdjustment: 8351 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8352 Adjustments[I].Ptr.RHS)) 8353 return false; 8354 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8355 break; 8356 } 8357 } 8358 8359 return true; 8360 } 8361 8362 bool 8363 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8364 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8365 "lvalue compound literal in c++?"); 8366 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8367 // only see this when folding in C, so there's no standard to follow here. 8368 return Success(E); 8369 } 8370 8371 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8372 TypeInfoLValue TypeInfo; 8373 8374 if (!E->isPotentiallyEvaluated()) { 8375 if (E->isTypeOperand()) 8376 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8377 else 8378 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8379 } else { 8380 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8381 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8382 << E->getExprOperand()->getType() 8383 << E->getExprOperand()->getSourceRange(); 8384 } 8385 8386 if (!Visit(E->getExprOperand())) 8387 return false; 8388 8389 Optional<DynamicType> DynType = 8390 ComputeDynamicType(Info, E, Result, AK_TypeId); 8391 if (!DynType) 8392 return false; 8393 8394 TypeInfo = 8395 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8396 } 8397 8398 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8399 } 8400 8401 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8402 return Success(E->getGuidDecl()); 8403 } 8404 8405 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8406 // Handle static data members. 8407 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8408 VisitIgnoredBaseExpression(E->getBase()); 8409 return VisitVarDecl(E, VD); 8410 } 8411 8412 // Handle static member functions. 8413 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8414 if (MD->isStatic()) { 8415 VisitIgnoredBaseExpression(E->getBase()); 8416 return Success(MD); 8417 } 8418 } 8419 8420 // Handle non-static data members. 8421 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8422 } 8423 8424 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8425 // FIXME: Deal with vectors as array subscript bases. 8426 if (E->getBase()->getType()->isVectorType() || 8427 E->getBase()->getType()->isVLSTBuiltinType()) 8428 return Error(E); 8429 8430 APSInt Index; 8431 bool Success = true; 8432 8433 // C++17's rules require us to evaluate the LHS first, regardless of which 8434 // side is the base. 8435 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8436 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8437 : !EvaluateInteger(SubExpr, Index, Info)) { 8438 if (!Info.noteFailure()) 8439 return false; 8440 Success = false; 8441 } 8442 } 8443 8444 return Success && 8445 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8446 } 8447 8448 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8449 return evaluatePointer(E->getSubExpr(), Result); 8450 } 8451 8452 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8453 if (!Visit(E->getSubExpr())) 8454 return false; 8455 // __real is a no-op on scalar lvalues. 8456 if (E->getSubExpr()->getType()->isAnyComplexType()) 8457 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8458 return true; 8459 } 8460 8461 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8462 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8463 "lvalue __imag__ on scalar?"); 8464 if (!Visit(E->getSubExpr())) 8465 return false; 8466 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8467 return true; 8468 } 8469 8470 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8471 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8472 return Error(UO); 8473 8474 if (!this->Visit(UO->getSubExpr())) 8475 return false; 8476 8477 return handleIncDec( 8478 this->Info, UO, Result, UO->getSubExpr()->getType(), 8479 UO->isIncrementOp(), nullptr); 8480 } 8481 8482 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8483 const CompoundAssignOperator *CAO) { 8484 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8485 return Error(CAO); 8486 8487 bool Success = true; 8488 8489 // C++17 onwards require that we evaluate the RHS first. 8490 APValue RHS; 8491 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8492 if (!Info.noteFailure()) 8493 return false; 8494 Success = false; 8495 } 8496 8497 // The overall lvalue result is the result of evaluating the LHS. 8498 if (!this->Visit(CAO->getLHS()) || !Success) 8499 return false; 8500 8501 return handleCompoundAssignment( 8502 this->Info, CAO, 8503 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8504 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8505 } 8506 8507 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8508 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8509 return Error(E); 8510 8511 bool Success = true; 8512 8513 // C++17 onwards require that we evaluate the RHS first. 8514 APValue NewVal; 8515 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8516 if (!Info.noteFailure()) 8517 return false; 8518 Success = false; 8519 } 8520 8521 if (!this->Visit(E->getLHS()) || !Success) 8522 return false; 8523 8524 if (Info.getLangOpts().CPlusPlus20 && 8525 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8526 return false; 8527 8528 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8529 NewVal); 8530 } 8531 8532 //===----------------------------------------------------------------------===// 8533 // Pointer Evaluation 8534 //===----------------------------------------------------------------------===// 8535 8536 /// Attempts to compute the number of bytes available at the pointer 8537 /// returned by a function with the alloc_size attribute. Returns true if we 8538 /// were successful. Places an unsigned number into `Result`. 8539 /// 8540 /// This expects the given CallExpr to be a call to a function with an 8541 /// alloc_size attribute. 8542 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8543 const CallExpr *Call, 8544 llvm::APInt &Result) { 8545 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8546 8547 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8548 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8549 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8550 if (Call->getNumArgs() <= SizeArgNo) 8551 return false; 8552 8553 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8554 Expr::EvalResult ExprResult; 8555 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8556 return false; 8557 Into = ExprResult.Val.getInt(); 8558 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8559 return false; 8560 Into = Into.zextOrSelf(BitsInSizeT); 8561 return true; 8562 }; 8563 8564 APSInt SizeOfElem; 8565 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8566 return false; 8567 8568 if (!AllocSize->getNumElemsParam().isValid()) { 8569 Result = std::move(SizeOfElem); 8570 return true; 8571 } 8572 8573 APSInt NumberOfElems; 8574 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8575 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8576 return false; 8577 8578 bool Overflow; 8579 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8580 if (Overflow) 8581 return false; 8582 8583 Result = std::move(BytesAvailable); 8584 return true; 8585 } 8586 8587 /// Convenience function. LVal's base must be a call to an alloc_size 8588 /// function. 8589 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8590 const LValue &LVal, 8591 llvm::APInt &Result) { 8592 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8593 "Can't get the size of a non alloc_size function"); 8594 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8595 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8596 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8597 } 8598 8599 /// Attempts to evaluate the given LValueBase as the result of a call to 8600 /// a function with the alloc_size attribute. If it was possible to do so, this 8601 /// function will return true, make Result's Base point to said function call, 8602 /// and mark Result's Base as invalid. 8603 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8604 LValue &Result) { 8605 if (Base.isNull()) 8606 return false; 8607 8608 // Because we do no form of static analysis, we only support const variables. 8609 // 8610 // Additionally, we can't support parameters, nor can we support static 8611 // variables (in the latter case, use-before-assign isn't UB; in the former, 8612 // we have no clue what they'll be assigned to). 8613 const auto *VD = 8614 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8615 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8616 return false; 8617 8618 const Expr *Init = VD->getAnyInitializer(); 8619 if (!Init) 8620 return false; 8621 8622 const Expr *E = Init->IgnoreParens(); 8623 if (!tryUnwrapAllocSizeCall(E)) 8624 return false; 8625 8626 // Store E instead of E unwrapped so that the type of the LValue's base is 8627 // what the user wanted. 8628 Result.setInvalid(E); 8629 8630 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8631 Result.addUnsizedArray(Info, E, Pointee); 8632 return true; 8633 } 8634 8635 namespace { 8636 class PointerExprEvaluator 8637 : public ExprEvaluatorBase<PointerExprEvaluator> { 8638 LValue &Result; 8639 bool InvalidBaseOK; 8640 8641 bool Success(const Expr *E) { 8642 Result.set(E); 8643 return true; 8644 } 8645 8646 bool evaluateLValue(const Expr *E, LValue &Result) { 8647 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8648 } 8649 8650 bool evaluatePointer(const Expr *E, LValue &Result) { 8651 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8652 } 8653 8654 bool visitNonBuiltinCallExpr(const CallExpr *E); 8655 public: 8656 8657 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8658 : ExprEvaluatorBaseTy(info), Result(Result), 8659 InvalidBaseOK(InvalidBaseOK) {} 8660 8661 bool Success(const APValue &V, const Expr *E) { 8662 Result.setFrom(Info.Ctx, V); 8663 return true; 8664 } 8665 bool ZeroInitialization(const Expr *E) { 8666 Result.setNull(Info.Ctx, E->getType()); 8667 return true; 8668 } 8669 8670 bool VisitBinaryOperator(const BinaryOperator *E); 8671 bool VisitCastExpr(const CastExpr* E); 8672 bool VisitUnaryAddrOf(const UnaryOperator *E); 8673 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8674 { return Success(E); } 8675 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8676 if (E->isExpressibleAsConstantInitializer()) 8677 return Success(E); 8678 if (Info.noteFailure()) 8679 EvaluateIgnoredValue(Info, E->getSubExpr()); 8680 return Error(E); 8681 } 8682 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8683 { return Success(E); } 8684 bool VisitCallExpr(const CallExpr *E); 8685 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8686 bool VisitBlockExpr(const BlockExpr *E) { 8687 if (!E->getBlockDecl()->hasCaptures()) 8688 return Success(E); 8689 return Error(E); 8690 } 8691 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8692 // Can't look at 'this' when checking a potential constant expression. 8693 if (Info.checkingPotentialConstantExpression()) 8694 return false; 8695 if (!Info.CurrentCall->This) { 8696 if (Info.getLangOpts().CPlusPlus11) 8697 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8698 else 8699 Info.FFDiag(E); 8700 return false; 8701 } 8702 Result = *Info.CurrentCall->This; 8703 // If we are inside a lambda's call operator, the 'this' expression refers 8704 // to the enclosing '*this' object (either by value or reference) which is 8705 // either copied into the closure object's field that represents the '*this' 8706 // or refers to '*this'. 8707 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8708 // Ensure we actually have captured 'this'. (an error will have 8709 // been previously reported if not). 8710 if (!Info.CurrentCall->LambdaThisCaptureField) 8711 return false; 8712 8713 // Update 'Result' to refer to the data member/field of the closure object 8714 // that represents the '*this' capture. 8715 if (!HandleLValueMember(Info, E, Result, 8716 Info.CurrentCall->LambdaThisCaptureField)) 8717 return false; 8718 // If we captured '*this' by reference, replace the field with its referent. 8719 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8720 ->isPointerType()) { 8721 APValue RVal; 8722 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8723 RVal)) 8724 return false; 8725 8726 Result.setFrom(Info.Ctx, RVal); 8727 } 8728 } 8729 return true; 8730 } 8731 8732 bool VisitCXXNewExpr(const CXXNewExpr *E); 8733 8734 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8735 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?"); 8736 APValue LValResult = E->EvaluateInContext( 8737 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8738 Result.setFrom(Info.Ctx, LValResult); 8739 return true; 8740 } 8741 8742 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8743 std::string ResultStr = E->ComputeName(Info.Ctx); 8744 8745 QualType CharTy = Info.Ctx.CharTy.withConst(); 8746 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8747 ResultStr.size() + 1); 8748 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8749 ArrayType::Normal, 0); 8750 8751 StringLiteral *SL = 8752 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8753 /*Pascal*/ false, ArrayTy, E->getLocation()); 8754 8755 evaluateLValue(SL, Result); 8756 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8757 return true; 8758 } 8759 8760 // FIXME: Missing: @protocol, @selector 8761 }; 8762 } // end anonymous namespace 8763 8764 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8765 bool InvalidBaseOK) { 8766 assert(!E->isValueDependent()); 8767 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 8768 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8769 } 8770 8771 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8772 if (E->getOpcode() != BO_Add && 8773 E->getOpcode() != BO_Sub) 8774 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8775 8776 const Expr *PExp = E->getLHS(); 8777 const Expr *IExp = E->getRHS(); 8778 if (IExp->getType()->isPointerType()) 8779 std::swap(PExp, IExp); 8780 8781 bool EvalPtrOK = evaluatePointer(PExp, Result); 8782 if (!EvalPtrOK && !Info.noteFailure()) 8783 return false; 8784 8785 llvm::APSInt Offset; 8786 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8787 return false; 8788 8789 if (E->getOpcode() == BO_Sub) 8790 negateAsSigned(Offset); 8791 8792 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8793 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8794 } 8795 8796 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8797 return evaluateLValue(E->getSubExpr(), Result); 8798 } 8799 8800 // Is the provided decl 'std::source_location::current'? 8801 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) { 8802 if (!FD) 8803 return false; 8804 const IdentifierInfo *FnII = FD->getIdentifier(); 8805 if (!FnII || !FnII->isStr("current")) 8806 return false; 8807 8808 const auto *RD = dyn_cast<RecordDecl>(FD->getParent()); 8809 if (!RD) 8810 return false; 8811 8812 const IdentifierInfo *ClassII = RD->getIdentifier(); 8813 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location"); 8814 } 8815 8816 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8817 const Expr *SubExpr = E->getSubExpr(); 8818 8819 switch (E->getCastKind()) { 8820 default: 8821 break; 8822 case CK_BitCast: 8823 case CK_CPointerToObjCPointerCast: 8824 case CK_BlockPointerToObjCPointerCast: 8825 case CK_AnyPointerToBlockPointerCast: 8826 case CK_AddressSpaceConversion: 8827 if (!Visit(SubExpr)) 8828 return false; 8829 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8830 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8831 // also static_casts, but we disallow them as a resolution to DR1312. 8832 if (!E->getType()->isVoidPointerType()) { 8833 // In some circumstances, we permit casting from void* to cv1 T*, when the 8834 // actual pointee object is actually a cv2 T. 8835 bool VoidPtrCastMaybeOK = 8836 !Result.InvalidBase && !Result.Designator.Invalid && 8837 !Result.IsNullPtr && 8838 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8839 E->getType()->getPointeeType()); 8840 // 1. We'll allow it in std::allocator::allocate, and anything which that 8841 // calls. 8842 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s 8843 // <source_location> header. Fixed in GCC 12 and later (2022-04-??). 8844 // We'll allow it in the body of std::source_location::current. GCC's 8845 // implementation had a parameter of type `void*`, and casts from 8846 // that back to `const __impl*` in its body. 8847 if (VoidPtrCastMaybeOK && 8848 (Info.getStdAllocatorCaller("allocate") || 8849 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) { 8850 // Permitted. 8851 } else { 8852 Result.Designator.setInvalid(); 8853 if (SubExpr->getType()->isVoidPointerType()) 8854 CCEDiag(E, diag::note_constexpr_invalid_cast) 8855 << 3 << SubExpr->getType(); 8856 else 8857 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8858 } 8859 } 8860 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8861 ZeroInitialization(E); 8862 return true; 8863 8864 case CK_DerivedToBase: 8865 case CK_UncheckedDerivedToBase: 8866 if (!evaluatePointer(E->getSubExpr(), Result)) 8867 return false; 8868 if (!Result.Base && Result.Offset.isZero()) 8869 return true; 8870 8871 // Now figure out the necessary offset to add to the base LV to get from 8872 // the derived class to the base class. 8873 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8874 castAs<PointerType>()->getPointeeType(), 8875 Result); 8876 8877 case CK_BaseToDerived: 8878 if (!Visit(E->getSubExpr())) 8879 return false; 8880 if (!Result.Base && Result.Offset.isZero()) 8881 return true; 8882 return HandleBaseToDerivedCast(Info, E, Result); 8883 8884 case CK_Dynamic: 8885 if (!Visit(E->getSubExpr())) 8886 return false; 8887 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8888 8889 case CK_NullToPointer: 8890 VisitIgnoredValue(E->getSubExpr()); 8891 return ZeroInitialization(E); 8892 8893 case CK_IntegralToPointer: { 8894 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8895 8896 APValue Value; 8897 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8898 break; 8899 8900 if (Value.isInt()) { 8901 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8902 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8903 Result.Base = (Expr*)nullptr; 8904 Result.InvalidBase = false; 8905 Result.Offset = CharUnits::fromQuantity(N); 8906 Result.Designator.setInvalid(); 8907 Result.IsNullPtr = false; 8908 return true; 8909 } else { 8910 // Cast is of an lvalue, no need to change value. 8911 Result.setFrom(Info.Ctx, Value); 8912 return true; 8913 } 8914 } 8915 8916 case CK_ArrayToPointerDecay: { 8917 if (SubExpr->isGLValue()) { 8918 if (!evaluateLValue(SubExpr, Result)) 8919 return false; 8920 } else { 8921 APValue &Value = Info.CurrentCall->createTemporary( 8922 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8923 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8924 return false; 8925 } 8926 // The result is a pointer to the first element of the array. 8927 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8928 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8929 Result.addArray(Info, E, CAT); 8930 else 8931 Result.addUnsizedArray(Info, E, AT->getElementType()); 8932 return true; 8933 } 8934 8935 case CK_FunctionToPointerDecay: 8936 return evaluateLValue(SubExpr, Result); 8937 8938 case CK_LValueToRValue: { 8939 LValue LVal; 8940 if (!evaluateLValue(E->getSubExpr(), LVal)) 8941 return false; 8942 8943 APValue RVal; 8944 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8945 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8946 LVal, RVal)) 8947 return InvalidBaseOK && 8948 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8949 return Success(RVal, E); 8950 } 8951 } 8952 8953 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8954 } 8955 8956 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8957 UnaryExprOrTypeTrait ExprKind) { 8958 // C++ [expr.alignof]p3: 8959 // When alignof is applied to a reference type, the result is the 8960 // alignment of the referenced type. 8961 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8962 T = Ref->getPointeeType(); 8963 8964 if (T.getQualifiers().hasUnaligned()) 8965 return CharUnits::One(); 8966 8967 const bool AlignOfReturnsPreferred = 8968 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8969 8970 // __alignof is defined to return the preferred alignment. 8971 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8972 // as well. 8973 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8974 return Info.Ctx.toCharUnitsFromBits( 8975 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8976 // alignof and _Alignof are defined to return the ABI alignment. 8977 else if (ExprKind == UETT_AlignOf) 8978 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8979 else 8980 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8981 } 8982 8983 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8984 UnaryExprOrTypeTrait ExprKind) { 8985 E = E->IgnoreParens(); 8986 8987 // The kinds of expressions that we have special-case logic here for 8988 // should be kept up to date with the special checks for those 8989 // expressions in Sema. 8990 8991 // alignof decl is always accepted, even if it doesn't make sense: we default 8992 // to 1 in those cases. 8993 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8994 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8995 /*RefAsPointee*/true); 8996 8997 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8998 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8999 /*RefAsPointee*/true); 9000 9001 return GetAlignOfType(Info, E->getType(), ExprKind); 9002 } 9003 9004 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 9005 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 9006 return Info.Ctx.getDeclAlign(VD); 9007 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 9008 return GetAlignOfExpr(Info, E, UETT_AlignOf); 9009 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 9010 } 9011 9012 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 9013 /// __builtin_is_aligned and __builtin_assume_aligned. 9014 static bool getAlignmentArgument(const Expr *E, QualType ForType, 9015 EvalInfo &Info, APSInt &Alignment) { 9016 if (!EvaluateInteger(E, Alignment, Info)) 9017 return false; 9018 if (Alignment < 0 || !Alignment.isPowerOf2()) { 9019 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 9020 return false; 9021 } 9022 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 9023 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 9024 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 9025 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 9026 << MaxValue << ForType << Alignment; 9027 return false; 9028 } 9029 // Ensure both alignment and source value have the same bit width so that we 9030 // don't assert when computing the resulting value. 9031 APSInt ExtAlignment = 9032 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 9033 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 9034 "Alignment should not be changed by ext/trunc"); 9035 Alignment = ExtAlignment; 9036 assert(Alignment.getBitWidth() == SrcWidth); 9037 return true; 9038 } 9039 9040 // To be clear: this happily visits unsupported builtins. Better name welcomed. 9041 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 9042 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 9043 return true; 9044 9045 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 9046 return false; 9047 9048 Result.setInvalid(E); 9049 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 9050 Result.addUnsizedArray(Info, E, PointeeTy); 9051 return true; 9052 } 9053 9054 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 9055 if (IsConstantCall(E)) 9056 return Success(E); 9057 9058 if (unsigned BuiltinOp = E->getBuiltinCallee()) 9059 return VisitBuiltinCallExpr(E, BuiltinOp); 9060 9061 return visitNonBuiltinCallExpr(E); 9062 } 9063 9064 // Determine if T is a character type for which we guarantee that 9065 // sizeof(T) == 1. 9066 static bool isOneByteCharacterType(QualType T) { 9067 return T->isCharType() || T->isChar8Type(); 9068 } 9069 9070 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9071 unsigned BuiltinOp) { 9072 switch (BuiltinOp) { 9073 case Builtin::BI__builtin_addressof: 9074 return evaluateLValue(E->getArg(0), Result); 9075 case Builtin::BI__builtin_assume_aligned: { 9076 // We need to be very careful here because: if the pointer does not have the 9077 // asserted alignment, then the behavior is undefined, and undefined 9078 // behavior is non-constant. 9079 if (!evaluatePointer(E->getArg(0), Result)) 9080 return false; 9081 9082 LValue OffsetResult(Result); 9083 APSInt Alignment; 9084 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9085 Alignment)) 9086 return false; 9087 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 9088 9089 if (E->getNumArgs() > 2) { 9090 APSInt Offset; 9091 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 9092 return false; 9093 9094 int64_t AdditionalOffset = -Offset.getZExtValue(); 9095 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9096 } 9097 9098 // If there is a base object, then it must have the correct alignment. 9099 if (OffsetResult.Base) { 9100 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9101 9102 if (BaseAlignment < Align) { 9103 Result.Designator.setInvalid(); 9104 // FIXME: Add support to Diagnostic for long / long long. 9105 CCEDiag(E->getArg(0), 9106 diag::note_constexpr_baa_insufficient_alignment) << 0 9107 << (unsigned)BaseAlignment.getQuantity() 9108 << (unsigned)Align.getQuantity(); 9109 return false; 9110 } 9111 } 9112 9113 // The offset must also have the correct alignment. 9114 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9115 Result.Designator.setInvalid(); 9116 9117 (OffsetResult.Base 9118 ? CCEDiag(E->getArg(0), 9119 diag::note_constexpr_baa_insufficient_alignment) << 1 9120 : CCEDiag(E->getArg(0), 9121 diag::note_constexpr_baa_value_insufficient_alignment)) 9122 << (int)OffsetResult.Offset.getQuantity() 9123 << (unsigned)Align.getQuantity(); 9124 return false; 9125 } 9126 9127 return true; 9128 } 9129 case Builtin::BI__builtin_align_up: 9130 case Builtin::BI__builtin_align_down: { 9131 if (!evaluatePointer(E->getArg(0), Result)) 9132 return false; 9133 APSInt Alignment; 9134 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9135 Alignment)) 9136 return false; 9137 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9138 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9139 // For align_up/align_down, we can return the same value if the alignment 9140 // is known to be greater or equal to the requested value. 9141 if (PtrAlign.getQuantity() >= Alignment) 9142 return true; 9143 9144 // The alignment could be greater than the minimum at run-time, so we cannot 9145 // infer much about the resulting pointer value. One case is possible: 9146 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9147 // can infer the correct index if the requested alignment is smaller than 9148 // the base alignment so we can perform the computation on the offset. 9149 if (BaseAlignment.getQuantity() >= Alignment) { 9150 assert(Alignment.getBitWidth() <= 64 && 9151 "Cannot handle > 64-bit address-space"); 9152 uint64_t Alignment64 = Alignment.getZExtValue(); 9153 CharUnits NewOffset = CharUnits::fromQuantity( 9154 BuiltinOp == Builtin::BI__builtin_align_down 9155 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9156 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9157 Result.adjustOffset(NewOffset - Result.Offset); 9158 // TODO: diagnose out-of-bounds values/only allow for arrays? 9159 return true; 9160 } 9161 // Otherwise, we cannot constant-evaluate the result. 9162 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9163 << Alignment; 9164 return false; 9165 } 9166 case Builtin::BI__builtin_operator_new: 9167 return HandleOperatorNewCall(Info, E, Result); 9168 case Builtin::BI__builtin_launder: 9169 return evaluatePointer(E->getArg(0), Result); 9170 case Builtin::BIstrchr: 9171 case Builtin::BIwcschr: 9172 case Builtin::BImemchr: 9173 case Builtin::BIwmemchr: 9174 if (Info.getLangOpts().CPlusPlus11) 9175 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9176 << /*isConstexpr*/0 << /*isConstructor*/0 9177 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9178 else 9179 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9180 LLVM_FALLTHROUGH; 9181 case Builtin::BI__builtin_strchr: 9182 case Builtin::BI__builtin_wcschr: 9183 case Builtin::BI__builtin_memchr: 9184 case Builtin::BI__builtin_char_memchr: 9185 case Builtin::BI__builtin_wmemchr: { 9186 if (!Visit(E->getArg(0))) 9187 return false; 9188 APSInt Desired; 9189 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9190 return false; 9191 uint64_t MaxLength = uint64_t(-1); 9192 if (BuiltinOp != Builtin::BIstrchr && 9193 BuiltinOp != Builtin::BIwcschr && 9194 BuiltinOp != Builtin::BI__builtin_strchr && 9195 BuiltinOp != Builtin::BI__builtin_wcschr) { 9196 APSInt N; 9197 if (!EvaluateInteger(E->getArg(2), N, Info)) 9198 return false; 9199 MaxLength = N.getExtValue(); 9200 } 9201 // We cannot find the value if there are no candidates to match against. 9202 if (MaxLength == 0u) 9203 return ZeroInitialization(E); 9204 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9205 Result.Designator.Invalid) 9206 return false; 9207 QualType CharTy = Result.Designator.getType(Info.Ctx); 9208 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9209 BuiltinOp == Builtin::BI__builtin_memchr; 9210 assert(IsRawByte || 9211 Info.Ctx.hasSameUnqualifiedType( 9212 CharTy, E->getArg(0)->getType()->getPointeeType())); 9213 // Pointers to const void may point to objects of incomplete type. 9214 if (IsRawByte && CharTy->isIncompleteType()) { 9215 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9216 return false; 9217 } 9218 // Give up on byte-oriented matching against multibyte elements. 9219 // FIXME: We can compare the bytes in the correct order. 9220 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9221 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9222 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9223 << CharTy; 9224 return false; 9225 } 9226 // Figure out what value we're actually looking for (after converting to 9227 // the corresponding unsigned type if necessary). 9228 uint64_t DesiredVal; 9229 bool StopAtNull = false; 9230 switch (BuiltinOp) { 9231 case Builtin::BIstrchr: 9232 case Builtin::BI__builtin_strchr: 9233 // strchr compares directly to the passed integer, and therefore 9234 // always fails if given an int that is not a char. 9235 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9236 E->getArg(1)->getType(), 9237 Desired), 9238 Desired)) 9239 return ZeroInitialization(E); 9240 StopAtNull = true; 9241 LLVM_FALLTHROUGH; 9242 case Builtin::BImemchr: 9243 case Builtin::BI__builtin_memchr: 9244 case Builtin::BI__builtin_char_memchr: 9245 // memchr compares by converting both sides to unsigned char. That's also 9246 // correct for strchr if we get this far (to cope with plain char being 9247 // unsigned in the strchr case). 9248 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9249 break; 9250 9251 case Builtin::BIwcschr: 9252 case Builtin::BI__builtin_wcschr: 9253 StopAtNull = true; 9254 LLVM_FALLTHROUGH; 9255 case Builtin::BIwmemchr: 9256 case Builtin::BI__builtin_wmemchr: 9257 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9258 DesiredVal = Desired.getZExtValue(); 9259 break; 9260 } 9261 9262 for (; MaxLength; --MaxLength) { 9263 APValue Char; 9264 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9265 !Char.isInt()) 9266 return false; 9267 if (Char.getInt().getZExtValue() == DesiredVal) 9268 return true; 9269 if (StopAtNull && !Char.getInt()) 9270 break; 9271 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9272 return false; 9273 } 9274 // Not found: return nullptr. 9275 return ZeroInitialization(E); 9276 } 9277 9278 case Builtin::BImemcpy: 9279 case Builtin::BImemmove: 9280 case Builtin::BIwmemcpy: 9281 case Builtin::BIwmemmove: 9282 if (Info.getLangOpts().CPlusPlus11) 9283 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9284 << /*isConstexpr*/0 << /*isConstructor*/0 9285 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9286 else 9287 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9288 LLVM_FALLTHROUGH; 9289 case Builtin::BI__builtin_memcpy: 9290 case Builtin::BI__builtin_memmove: 9291 case Builtin::BI__builtin_wmemcpy: 9292 case Builtin::BI__builtin_wmemmove: { 9293 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9294 BuiltinOp == Builtin::BIwmemmove || 9295 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9296 BuiltinOp == Builtin::BI__builtin_wmemmove; 9297 bool Move = BuiltinOp == Builtin::BImemmove || 9298 BuiltinOp == Builtin::BIwmemmove || 9299 BuiltinOp == Builtin::BI__builtin_memmove || 9300 BuiltinOp == Builtin::BI__builtin_wmemmove; 9301 9302 // The result of mem* is the first argument. 9303 if (!Visit(E->getArg(0))) 9304 return false; 9305 LValue Dest = Result; 9306 9307 LValue Src; 9308 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9309 return false; 9310 9311 APSInt N; 9312 if (!EvaluateInteger(E->getArg(2), N, Info)) 9313 return false; 9314 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9315 9316 // If the size is zero, we treat this as always being a valid no-op. 9317 // (Even if one of the src and dest pointers is null.) 9318 if (!N) 9319 return true; 9320 9321 // Otherwise, if either of the operands is null, we can't proceed. Don't 9322 // try to determine the type of the copied objects, because there aren't 9323 // any. 9324 if (!Src.Base || !Dest.Base) { 9325 APValue Val; 9326 (!Src.Base ? Src : Dest).moveInto(Val); 9327 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9328 << Move << WChar << !!Src.Base 9329 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9330 return false; 9331 } 9332 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9333 return false; 9334 9335 // We require that Src and Dest are both pointers to arrays of 9336 // trivially-copyable type. (For the wide version, the designator will be 9337 // invalid if the designated object is not a wchar_t.) 9338 QualType T = Dest.Designator.getType(Info.Ctx); 9339 QualType SrcT = Src.Designator.getType(Info.Ctx); 9340 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9341 // FIXME: Consider using our bit_cast implementation to support this. 9342 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9343 return false; 9344 } 9345 if (T->isIncompleteType()) { 9346 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9347 return false; 9348 } 9349 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9350 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9351 return false; 9352 } 9353 9354 // Figure out how many T's we're copying. 9355 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9356 if (!WChar) { 9357 uint64_t Remainder; 9358 llvm::APInt OrigN = N; 9359 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9360 if (Remainder) { 9361 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9362 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) 9363 << (unsigned)TSize; 9364 return false; 9365 } 9366 } 9367 9368 // Check that the copying will remain within the arrays, just so that we 9369 // can give a more meaningful diagnostic. This implicitly also checks that 9370 // N fits into 64 bits. 9371 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9372 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9373 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9374 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9375 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9376 << toString(N, 10, /*Signed*/false); 9377 return false; 9378 } 9379 uint64_t NElems = N.getZExtValue(); 9380 uint64_t NBytes = NElems * TSize; 9381 9382 // Check for overlap. 9383 int Direction = 1; 9384 if (HasSameBase(Src, Dest)) { 9385 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9386 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9387 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9388 // Dest is inside the source region. 9389 if (!Move) { 9390 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9391 return false; 9392 } 9393 // For memmove and friends, copy backwards. 9394 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9395 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9396 return false; 9397 Direction = -1; 9398 } else if (!Move && SrcOffset >= DestOffset && 9399 SrcOffset - DestOffset < NBytes) { 9400 // Src is inside the destination region for memcpy: invalid. 9401 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9402 return false; 9403 } 9404 } 9405 9406 while (true) { 9407 APValue Val; 9408 // FIXME: Set WantObjectRepresentation to true if we're copying a 9409 // char-like type? 9410 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9411 !handleAssignment(Info, E, Dest, T, Val)) 9412 return false; 9413 // Do not iterate past the last element; if we're copying backwards, that 9414 // might take us off the start of the array. 9415 if (--NElems == 0) 9416 return true; 9417 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9418 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9419 return false; 9420 } 9421 } 9422 9423 default: 9424 break; 9425 } 9426 9427 return visitNonBuiltinCallExpr(E); 9428 } 9429 9430 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9431 APValue &Result, const InitListExpr *ILE, 9432 QualType AllocType); 9433 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9434 APValue &Result, 9435 const CXXConstructExpr *CCE, 9436 QualType AllocType); 9437 9438 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9439 if (!Info.getLangOpts().CPlusPlus20) 9440 Info.CCEDiag(E, diag::note_constexpr_new); 9441 9442 // We cannot speculatively evaluate a delete expression. 9443 if (Info.SpeculativeEvaluationDepth) 9444 return false; 9445 9446 FunctionDecl *OperatorNew = E->getOperatorNew(); 9447 9448 bool IsNothrow = false; 9449 bool IsPlacement = false; 9450 if (OperatorNew->isReservedGlobalPlacementOperator() && 9451 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9452 // FIXME Support array placement new. 9453 assert(E->getNumPlacementArgs() == 1); 9454 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9455 return false; 9456 if (Result.Designator.Invalid) 9457 return false; 9458 IsPlacement = true; 9459 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9460 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9461 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9462 return false; 9463 } else if (E->getNumPlacementArgs()) { 9464 // The only new-placement list we support is of the form (std::nothrow). 9465 // 9466 // FIXME: There is no restriction on this, but it's not clear that any 9467 // other form makes any sense. We get here for cases such as: 9468 // 9469 // new (std::align_val_t{N}) X(int) 9470 // 9471 // (which should presumably be valid only if N is a multiple of 9472 // alignof(int), and in any case can't be deallocated unless N is 9473 // alignof(X) and X has new-extended alignment). 9474 if (E->getNumPlacementArgs() != 1 || 9475 !E->getPlacementArg(0)->getType()->isNothrowT()) 9476 return Error(E, diag::note_constexpr_new_placement); 9477 9478 LValue Nothrow; 9479 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9480 return false; 9481 IsNothrow = true; 9482 } 9483 9484 const Expr *Init = E->getInitializer(); 9485 const InitListExpr *ResizedArrayILE = nullptr; 9486 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9487 bool ValueInit = false; 9488 9489 QualType AllocType = E->getAllocatedType(); 9490 if (Optional<const Expr *> ArraySize = E->getArraySize()) { 9491 const Expr *Stripped = *ArraySize; 9492 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9493 Stripped = ICE->getSubExpr()) 9494 if (ICE->getCastKind() != CK_NoOp && 9495 ICE->getCastKind() != CK_IntegralCast) 9496 break; 9497 9498 llvm::APSInt ArrayBound; 9499 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9500 return false; 9501 9502 // C++ [expr.new]p9: 9503 // The expression is erroneous if: 9504 // -- [...] its value before converting to size_t [or] applying the 9505 // second standard conversion sequence is less than zero 9506 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9507 if (IsNothrow) 9508 return ZeroInitialization(E); 9509 9510 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9511 << ArrayBound << (*ArraySize)->getSourceRange(); 9512 return false; 9513 } 9514 9515 // -- its value is such that the size of the allocated object would 9516 // exceed the implementation-defined limit 9517 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9518 ArrayBound) > 9519 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9520 if (IsNothrow) 9521 return ZeroInitialization(E); 9522 9523 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9524 << ArrayBound << (*ArraySize)->getSourceRange(); 9525 return false; 9526 } 9527 9528 // -- the new-initializer is a braced-init-list and the number of 9529 // array elements for which initializers are provided [...] 9530 // exceeds the number of elements to initialize 9531 if (!Init) { 9532 // No initialization is performed. 9533 } else if (isa<CXXScalarValueInitExpr>(Init) || 9534 isa<ImplicitValueInitExpr>(Init)) { 9535 ValueInit = true; 9536 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9537 ResizedArrayCCE = CCE; 9538 } else { 9539 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9540 assert(CAT && "unexpected type for array initializer"); 9541 9542 unsigned Bits = 9543 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9544 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9545 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9546 if (InitBound.ugt(AllocBound)) { 9547 if (IsNothrow) 9548 return ZeroInitialization(E); 9549 9550 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9551 << toString(AllocBound, 10, /*Signed=*/false) 9552 << toString(InitBound, 10, /*Signed=*/false) 9553 << (*ArraySize)->getSourceRange(); 9554 return false; 9555 } 9556 9557 // If the sizes differ, we must have an initializer list, and we need 9558 // special handling for this case when we initialize. 9559 if (InitBound != AllocBound) 9560 ResizedArrayILE = cast<InitListExpr>(Init); 9561 } 9562 9563 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9564 ArrayType::Normal, 0); 9565 } else { 9566 assert(!AllocType->isArrayType() && 9567 "array allocation with non-array new"); 9568 } 9569 9570 APValue *Val; 9571 if (IsPlacement) { 9572 AccessKinds AK = AK_Construct; 9573 struct FindObjectHandler { 9574 EvalInfo &Info; 9575 const Expr *E; 9576 QualType AllocType; 9577 const AccessKinds AccessKind; 9578 APValue *Value; 9579 9580 typedef bool result_type; 9581 bool failed() { return false; } 9582 bool found(APValue &Subobj, QualType SubobjType) { 9583 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9584 // old name of the object to be used to name the new object. 9585 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9586 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9587 SubobjType << AllocType; 9588 return false; 9589 } 9590 Value = &Subobj; 9591 return true; 9592 } 9593 bool found(APSInt &Value, QualType SubobjType) { 9594 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9595 return false; 9596 } 9597 bool found(APFloat &Value, QualType SubobjType) { 9598 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9599 return false; 9600 } 9601 } Handler = {Info, E, AllocType, AK, nullptr}; 9602 9603 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9604 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9605 return false; 9606 9607 Val = Handler.Value; 9608 9609 // [basic.life]p1: 9610 // The lifetime of an object o of type T ends when [...] the storage 9611 // which the object occupies is [...] reused by an object that is not 9612 // nested within o (6.6.2). 9613 *Val = APValue(); 9614 } else { 9615 // Perform the allocation and obtain a pointer to the resulting object. 9616 Val = Info.createHeapAlloc(E, AllocType, Result); 9617 if (!Val) 9618 return false; 9619 } 9620 9621 if (ValueInit) { 9622 ImplicitValueInitExpr VIE(AllocType); 9623 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9624 return false; 9625 } else if (ResizedArrayILE) { 9626 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9627 AllocType)) 9628 return false; 9629 } else if (ResizedArrayCCE) { 9630 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9631 AllocType)) 9632 return false; 9633 } else if (Init) { 9634 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9635 return false; 9636 } else if (!getDefaultInitValue(AllocType, *Val)) { 9637 return false; 9638 } 9639 9640 // Array new returns a pointer to the first element, not a pointer to the 9641 // array. 9642 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9643 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9644 9645 return true; 9646 } 9647 //===----------------------------------------------------------------------===// 9648 // Member Pointer Evaluation 9649 //===----------------------------------------------------------------------===// 9650 9651 namespace { 9652 class MemberPointerExprEvaluator 9653 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9654 MemberPtr &Result; 9655 9656 bool Success(const ValueDecl *D) { 9657 Result = MemberPtr(D); 9658 return true; 9659 } 9660 public: 9661 9662 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9663 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9664 9665 bool Success(const APValue &V, const Expr *E) { 9666 Result.setFrom(V); 9667 return true; 9668 } 9669 bool ZeroInitialization(const Expr *E) { 9670 return Success((const ValueDecl*)nullptr); 9671 } 9672 9673 bool VisitCastExpr(const CastExpr *E); 9674 bool VisitUnaryAddrOf(const UnaryOperator *E); 9675 }; 9676 } // end anonymous namespace 9677 9678 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9679 EvalInfo &Info) { 9680 assert(!E->isValueDependent()); 9681 assert(E->isPRValue() && E->getType()->isMemberPointerType()); 9682 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9683 } 9684 9685 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9686 switch (E->getCastKind()) { 9687 default: 9688 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9689 9690 case CK_NullToMemberPointer: 9691 VisitIgnoredValue(E->getSubExpr()); 9692 return ZeroInitialization(E); 9693 9694 case CK_BaseToDerivedMemberPointer: { 9695 if (!Visit(E->getSubExpr())) 9696 return false; 9697 if (E->path_empty()) 9698 return true; 9699 // Base-to-derived member pointer casts store the path in derived-to-base 9700 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9701 // the wrong end of the derived->base arc, so stagger the path by one class. 9702 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9703 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9704 PathI != PathE; ++PathI) { 9705 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9706 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9707 if (!Result.castToDerived(Derived)) 9708 return Error(E); 9709 } 9710 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9711 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9712 return Error(E); 9713 return true; 9714 } 9715 9716 case CK_DerivedToBaseMemberPointer: 9717 if (!Visit(E->getSubExpr())) 9718 return false; 9719 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9720 PathE = E->path_end(); PathI != PathE; ++PathI) { 9721 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9722 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9723 if (!Result.castToBase(Base)) 9724 return Error(E); 9725 } 9726 return true; 9727 } 9728 } 9729 9730 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9731 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9732 // member can be formed. 9733 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9734 } 9735 9736 //===----------------------------------------------------------------------===// 9737 // Record Evaluation 9738 //===----------------------------------------------------------------------===// 9739 9740 namespace { 9741 class RecordExprEvaluator 9742 : public ExprEvaluatorBase<RecordExprEvaluator> { 9743 const LValue &This; 9744 APValue &Result; 9745 public: 9746 9747 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9748 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9749 9750 bool Success(const APValue &V, const Expr *E) { 9751 Result = V; 9752 return true; 9753 } 9754 bool ZeroInitialization(const Expr *E) { 9755 return ZeroInitialization(E, E->getType()); 9756 } 9757 bool ZeroInitialization(const Expr *E, QualType T); 9758 9759 bool VisitCallExpr(const CallExpr *E) { 9760 return handleCallExpr(E, Result, &This); 9761 } 9762 bool VisitCastExpr(const CastExpr *E); 9763 bool VisitInitListExpr(const InitListExpr *E); 9764 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9765 return VisitCXXConstructExpr(E, E->getType()); 9766 } 9767 bool VisitLambdaExpr(const LambdaExpr *E); 9768 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9769 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9770 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9771 bool VisitBinCmp(const BinaryOperator *E); 9772 }; 9773 } 9774 9775 /// Perform zero-initialization on an object of non-union class type. 9776 /// C++11 [dcl.init]p5: 9777 /// To zero-initialize an object or reference of type T means: 9778 /// [...] 9779 /// -- if T is a (possibly cv-qualified) non-union class type, 9780 /// each non-static data member and each base-class subobject is 9781 /// zero-initialized 9782 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9783 const RecordDecl *RD, 9784 const LValue &This, APValue &Result) { 9785 assert(!RD->isUnion() && "Expected non-union class type"); 9786 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9787 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9788 std::distance(RD->field_begin(), RD->field_end())); 9789 9790 if (RD->isInvalidDecl()) return false; 9791 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9792 9793 if (CD) { 9794 unsigned Index = 0; 9795 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9796 End = CD->bases_end(); I != End; ++I, ++Index) { 9797 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9798 LValue Subobject = This; 9799 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9800 return false; 9801 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9802 Result.getStructBase(Index))) 9803 return false; 9804 } 9805 } 9806 9807 for (const auto *I : RD->fields()) { 9808 // -- if T is a reference type, no initialization is performed. 9809 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9810 continue; 9811 9812 LValue Subobject = This; 9813 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9814 return false; 9815 9816 ImplicitValueInitExpr VIE(I->getType()); 9817 if (!EvaluateInPlace( 9818 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9819 return false; 9820 } 9821 9822 return true; 9823 } 9824 9825 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9826 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9827 if (RD->isInvalidDecl()) return false; 9828 if (RD->isUnion()) { 9829 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9830 // object's first non-static named data member is zero-initialized 9831 RecordDecl::field_iterator I = RD->field_begin(); 9832 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9833 ++I; 9834 if (I == RD->field_end()) { 9835 Result = APValue((const FieldDecl*)nullptr); 9836 return true; 9837 } 9838 9839 LValue Subobject = This; 9840 if (!HandleLValueMember(Info, E, Subobject, *I)) 9841 return false; 9842 Result = APValue(*I); 9843 ImplicitValueInitExpr VIE(I->getType()); 9844 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9845 } 9846 9847 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9848 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9849 return false; 9850 } 9851 9852 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9853 } 9854 9855 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9856 switch (E->getCastKind()) { 9857 default: 9858 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9859 9860 case CK_ConstructorConversion: 9861 return Visit(E->getSubExpr()); 9862 9863 case CK_DerivedToBase: 9864 case CK_UncheckedDerivedToBase: { 9865 APValue DerivedObject; 9866 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9867 return false; 9868 if (!DerivedObject.isStruct()) 9869 return Error(E->getSubExpr()); 9870 9871 // Derived-to-base rvalue conversion: just slice off the derived part. 9872 APValue *Value = &DerivedObject; 9873 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9874 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9875 PathE = E->path_end(); PathI != PathE; ++PathI) { 9876 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9877 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9878 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9879 RD = Base; 9880 } 9881 Result = *Value; 9882 return true; 9883 } 9884 } 9885 } 9886 9887 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9888 if (E->isTransparent()) 9889 return Visit(E->getInit(0)); 9890 9891 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9892 if (RD->isInvalidDecl()) return false; 9893 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9894 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9895 9896 EvalInfo::EvaluatingConstructorRAII EvalObj( 9897 Info, 9898 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9899 CXXRD && CXXRD->getNumBases()); 9900 9901 if (RD->isUnion()) { 9902 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9903 Result = APValue(Field); 9904 if (!Field) 9905 return true; 9906 9907 // If the initializer list for a union does not contain any elements, the 9908 // first element of the union is value-initialized. 9909 // FIXME: The element should be initialized from an initializer list. 9910 // Is this difference ever observable for initializer lists which 9911 // we don't build? 9912 ImplicitValueInitExpr VIE(Field->getType()); 9913 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9914 9915 LValue Subobject = This; 9916 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9917 return false; 9918 9919 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9920 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9921 isa<CXXDefaultInitExpr>(InitExpr)); 9922 9923 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9924 if (Field->isBitField()) 9925 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9926 Field); 9927 return true; 9928 } 9929 9930 return false; 9931 } 9932 9933 if (!Result.hasValue()) 9934 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9935 std::distance(RD->field_begin(), RD->field_end())); 9936 unsigned ElementNo = 0; 9937 bool Success = true; 9938 9939 // Initialize base classes. 9940 if (CXXRD && CXXRD->getNumBases()) { 9941 for (const auto &Base : CXXRD->bases()) { 9942 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9943 const Expr *Init = E->getInit(ElementNo); 9944 9945 LValue Subobject = This; 9946 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9947 return false; 9948 9949 APValue &FieldVal = Result.getStructBase(ElementNo); 9950 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9951 if (!Info.noteFailure()) 9952 return false; 9953 Success = false; 9954 } 9955 ++ElementNo; 9956 } 9957 9958 EvalObj.finishedConstructingBases(); 9959 } 9960 9961 // Initialize members. 9962 for (const auto *Field : RD->fields()) { 9963 // Anonymous bit-fields are not considered members of the class for 9964 // purposes of aggregate initialization. 9965 if (Field->isUnnamedBitfield()) 9966 continue; 9967 9968 LValue Subobject = This; 9969 9970 bool HaveInit = ElementNo < E->getNumInits(); 9971 9972 // FIXME: Diagnostics here should point to the end of the initializer 9973 // list, not the start. 9974 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9975 Subobject, Field, &Layout)) 9976 return false; 9977 9978 // Perform an implicit value-initialization for members beyond the end of 9979 // the initializer list. 9980 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9981 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9982 9983 if (Field->getType()->isIncompleteArrayType()) { 9984 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) { 9985 if (!CAT->getSize().isZero()) { 9986 // Bail out for now. This might sort of "work", but the rest of the 9987 // code isn't really prepared to handle it. 9988 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array); 9989 return false; 9990 } 9991 } 9992 } 9993 9994 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9995 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9996 isa<CXXDefaultInitExpr>(Init)); 9997 9998 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9999 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 10000 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 10001 FieldVal, Field))) { 10002 if (!Info.noteFailure()) 10003 return false; 10004 Success = false; 10005 } 10006 } 10007 10008 EvalObj.finishedConstructingFields(); 10009 10010 return Success; 10011 } 10012 10013 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10014 QualType T) { 10015 // Note that E's type is not necessarily the type of our class here; we might 10016 // be initializing an array element instead. 10017 const CXXConstructorDecl *FD = E->getConstructor(); 10018 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 10019 10020 bool ZeroInit = E->requiresZeroInitialization(); 10021 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 10022 // If we've already performed zero-initialization, we're already done. 10023 if (Result.hasValue()) 10024 return true; 10025 10026 if (ZeroInit) 10027 return ZeroInitialization(E, T); 10028 10029 return getDefaultInitValue(T, Result); 10030 } 10031 10032 const FunctionDecl *Definition = nullptr; 10033 auto Body = FD->getBody(Definition); 10034 10035 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10036 return false; 10037 10038 // Avoid materializing a temporary for an elidable copy/move constructor. 10039 if (E->isElidable() && !ZeroInit) { 10040 // FIXME: This only handles the simplest case, where the source object 10041 // is passed directly as the first argument to the constructor. 10042 // This should also handle stepping though implicit casts and 10043 // and conversion sequences which involve two steps, with a 10044 // conversion operator followed by a converting constructor. 10045 const Expr *SrcObj = E->getArg(0); 10046 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent())); 10047 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 10048 if (const MaterializeTemporaryExpr *ME = 10049 dyn_cast<MaterializeTemporaryExpr>(SrcObj)) 10050 return Visit(ME->getSubExpr()); 10051 } 10052 10053 if (ZeroInit && !ZeroInitialization(E, T)) 10054 return false; 10055 10056 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 10057 return HandleConstructorCall(E, This, Args, 10058 cast<CXXConstructorDecl>(Definition), Info, 10059 Result); 10060 } 10061 10062 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 10063 const CXXInheritedCtorInitExpr *E) { 10064 if (!Info.CurrentCall) { 10065 assert(Info.checkingPotentialConstantExpression()); 10066 return false; 10067 } 10068 10069 const CXXConstructorDecl *FD = E->getConstructor(); 10070 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 10071 return false; 10072 10073 const FunctionDecl *Definition = nullptr; 10074 auto Body = FD->getBody(Definition); 10075 10076 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 10077 return false; 10078 10079 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 10080 cast<CXXConstructorDecl>(Definition), Info, 10081 Result); 10082 } 10083 10084 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 10085 const CXXStdInitializerListExpr *E) { 10086 const ConstantArrayType *ArrayType = 10087 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 10088 10089 LValue Array; 10090 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 10091 return false; 10092 10093 // Get a pointer to the first element of the array. 10094 Array.addArray(Info, E, ArrayType); 10095 10096 auto InvalidType = [&] { 10097 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 10098 << E->getType(); 10099 return false; 10100 }; 10101 10102 // FIXME: Perform the checks on the field types in SemaInit. 10103 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 10104 RecordDecl::field_iterator Field = Record->field_begin(); 10105 if (Field == Record->field_end()) 10106 return InvalidType(); 10107 10108 // Start pointer. 10109 if (!Field->getType()->isPointerType() || 10110 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10111 ArrayType->getElementType())) 10112 return InvalidType(); 10113 10114 // FIXME: What if the initializer_list type has base classes, etc? 10115 Result = APValue(APValue::UninitStruct(), 0, 2); 10116 Array.moveInto(Result.getStructField(0)); 10117 10118 if (++Field == Record->field_end()) 10119 return InvalidType(); 10120 10121 if (Field->getType()->isPointerType() && 10122 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10123 ArrayType->getElementType())) { 10124 // End pointer. 10125 if (!HandleLValueArrayAdjustment(Info, E, Array, 10126 ArrayType->getElementType(), 10127 ArrayType->getSize().getZExtValue())) 10128 return false; 10129 Array.moveInto(Result.getStructField(1)); 10130 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10131 // Length. 10132 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10133 else 10134 return InvalidType(); 10135 10136 if (++Field != Record->field_end()) 10137 return InvalidType(); 10138 10139 return true; 10140 } 10141 10142 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10143 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10144 if (ClosureClass->isInvalidDecl()) 10145 return false; 10146 10147 const size_t NumFields = 10148 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10149 10150 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10151 E->capture_init_end()) && 10152 "The number of lambda capture initializers should equal the number of " 10153 "fields within the closure type"); 10154 10155 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10156 // Iterate through all the lambda's closure object's fields and initialize 10157 // them. 10158 auto *CaptureInitIt = E->capture_init_begin(); 10159 bool Success = true; 10160 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10161 for (const auto *Field : ClosureClass->fields()) { 10162 assert(CaptureInitIt != E->capture_init_end()); 10163 // Get the initializer for this field 10164 Expr *const CurFieldInit = *CaptureInitIt++; 10165 10166 // If there is no initializer, either this is a VLA or an error has 10167 // occurred. 10168 if (!CurFieldInit) 10169 return Error(E); 10170 10171 LValue Subobject = This; 10172 10173 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10174 return false; 10175 10176 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10177 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10178 if (!Info.keepEvaluatingAfterFailure()) 10179 return false; 10180 Success = false; 10181 } 10182 } 10183 return Success; 10184 } 10185 10186 static bool EvaluateRecord(const Expr *E, const LValue &This, 10187 APValue &Result, EvalInfo &Info) { 10188 assert(!E->isValueDependent()); 10189 assert(E->isPRValue() && E->getType()->isRecordType() && 10190 "can't evaluate expression as a record rvalue"); 10191 return RecordExprEvaluator(Info, This, Result).Visit(E); 10192 } 10193 10194 //===----------------------------------------------------------------------===// 10195 // Temporary Evaluation 10196 // 10197 // Temporaries are represented in the AST as rvalues, but generally behave like 10198 // lvalues. The full-object of which the temporary is a subobject is implicitly 10199 // materialized so that a reference can bind to it. 10200 //===----------------------------------------------------------------------===// 10201 namespace { 10202 class TemporaryExprEvaluator 10203 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10204 public: 10205 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10206 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10207 10208 /// Visit an expression which constructs the value of this temporary. 10209 bool VisitConstructExpr(const Expr *E) { 10210 APValue &Value = Info.CurrentCall->createTemporary( 10211 E, E->getType(), ScopeKind::FullExpression, Result); 10212 return EvaluateInPlace(Value, Info, Result, E); 10213 } 10214 10215 bool VisitCastExpr(const CastExpr *E) { 10216 switch (E->getCastKind()) { 10217 default: 10218 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10219 10220 case CK_ConstructorConversion: 10221 return VisitConstructExpr(E->getSubExpr()); 10222 } 10223 } 10224 bool VisitInitListExpr(const InitListExpr *E) { 10225 return VisitConstructExpr(E); 10226 } 10227 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10228 return VisitConstructExpr(E); 10229 } 10230 bool VisitCallExpr(const CallExpr *E) { 10231 return VisitConstructExpr(E); 10232 } 10233 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10234 return VisitConstructExpr(E); 10235 } 10236 bool VisitLambdaExpr(const LambdaExpr *E) { 10237 return VisitConstructExpr(E); 10238 } 10239 }; 10240 } // end anonymous namespace 10241 10242 /// Evaluate an expression of record type as a temporary. 10243 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10244 assert(!E->isValueDependent()); 10245 assert(E->isPRValue() && E->getType()->isRecordType()); 10246 return TemporaryExprEvaluator(Info, Result).Visit(E); 10247 } 10248 10249 //===----------------------------------------------------------------------===// 10250 // Vector Evaluation 10251 //===----------------------------------------------------------------------===// 10252 10253 namespace { 10254 class VectorExprEvaluator 10255 : public ExprEvaluatorBase<VectorExprEvaluator> { 10256 APValue &Result; 10257 public: 10258 10259 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10260 : ExprEvaluatorBaseTy(info), Result(Result) {} 10261 10262 bool Success(ArrayRef<APValue> V, const Expr *E) { 10263 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10264 // FIXME: remove this APValue copy. 10265 Result = APValue(V.data(), V.size()); 10266 return true; 10267 } 10268 bool Success(const APValue &V, const Expr *E) { 10269 assert(V.isVector()); 10270 Result = V; 10271 return true; 10272 } 10273 bool ZeroInitialization(const Expr *E); 10274 10275 bool VisitUnaryReal(const UnaryOperator *E) 10276 { return Visit(E->getSubExpr()); } 10277 bool VisitCastExpr(const CastExpr* E); 10278 bool VisitInitListExpr(const InitListExpr *E); 10279 bool VisitUnaryImag(const UnaryOperator *E); 10280 bool VisitBinaryOperator(const BinaryOperator *E); 10281 bool VisitUnaryOperator(const UnaryOperator *E); 10282 // FIXME: Missing: conditional operator (for GNU 10283 // conditional select), shufflevector, ExtVectorElementExpr 10284 }; 10285 } // end anonymous namespace 10286 10287 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10288 assert(E->isPRValue() && E->getType()->isVectorType() && 10289 "not a vector prvalue"); 10290 return VectorExprEvaluator(Info, Result).Visit(E); 10291 } 10292 10293 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10294 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10295 unsigned NElts = VTy->getNumElements(); 10296 10297 const Expr *SE = E->getSubExpr(); 10298 QualType SETy = SE->getType(); 10299 10300 switch (E->getCastKind()) { 10301 case CK_VectorSplat: { 10302 APValue Val = APValue(); 10303 if (SETy->isIntegerType()) { 10304 APSInt IntResult; 10305 if (!EvaluateInteger(SE, IntResult, Info)) 10306 return false; 10307 Val = APValue(std::move(IntResult)); 10308 } else if (SETy->isRealFloatingType()) { 10309 APFloat FloatResult(0.0); 10310 if (!EvaluateFloat(SE, FloatResult, Info)) 10311 return false; 10312 Val = APValue(std::move(FloatResult)); 10313 } else { 10314 return Error(E); 10315 } 10316 10317 // Splat and create vector APValue. 10318 SmallVector<APValue, 4> Elts(NElts, Val); 10319 return Success(Elts, E); 10320 } 10321 case CK_BitCast: { 10322 // Evaluate the operand into an APInt we can extract from. 10323 llvm::APInt SValInt; 10324 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10325 return false; 10326 // Extract the elements 10327 QualType EltTy = VTy->getElementType(); 10328 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10329 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10330 SmallVector<APValue, 4> Elts; 10331 if (EltTy->isRealFloatingType()) { 10332 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10333 unsigned FloatEltSize = EltSize; 10334 if (&Sem == &APFloat::x87DoubleExtended()) 10335 FloatEltSize = 80; 10336 for (unsigned i = 0; i < NElts; i++) { 10337 llvm::APInt Elt; 10338 if (BigEndian) 10339 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10340 else 10341 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10342 Elts.push_back(APValue(APFloat(Sem, Elt))); 10343 } 10344 } else if (EltTy->isIntegerType()) { 10345 for (unsigned i = 0; i < NElts; i++) { 10346 llvm::APInt Elt; 10347 if (BigEndian) 10348 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10349 else 10350 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10351 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10352 } 10353 } else { 10354 return Error(E); 10355 } 10356 return Success(Elts, E); 10357 } 10358 default: 10359 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10360 } 10361 } 10362 10363 bool 10364 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10365 const VectorType *VT = E->getType()->castAs<VectorType>(); 10366 unsigned NumInits = E->getNumInits(); 10367 unsigned NumElements = VT->getNumElements(); 10368 10369 QualType EltTy = VT->getElementType(); 10370 SmallVector<APValue, 4> Elements; 10371 10372 // The number of initializers can be less than the number of 10373 // vector elements. For OpenCL, this can be due to nested vector 10374 // initialization. For GCC compatibility, missing trailing elements 10375 // should be initialized with zeroes. 10376 unsigned CountInits = 0, CountElts = 0; 10377 while (CountElts < NumElements) { 10378 // Handle nested vector initialization. 10379 if (CountInits < NumInits 10380 && E->getInit(CountInits)->getType()->isVectorType()) { 10381 APValue v; 10382 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10383 return Error(E); 10384 unsigned vlen = v.getVectorLength(); 10385 for (unsigned j = 0; j < vlen; j++) 10386 Elements.push_back(v.getVectorElt(j)); 10387 CountElts += vlen; 10388 } else if (EltTy->isIntegerType()) { 10389 llvm::APSInt sInt(32); 10390 if (CountInits < NumInits) { 10391 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10392 return false; 10393 } else // trailing integer zero. 10394 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10395 Elements.push_back(APValue(sInt)); 10396 CountElts++; 10397 } else { 10398 llvm::APFloat f(0.0); 10399 if (CountInits < NumInits) { 10400 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10401 return false; 10402 } else // trailing float zero. 10403 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10404 Elements.push_back(APValue(f)); 10405 CountElts++; 10406 } 10407 CountInits++; 10408 } 10409 return Success(Elements, E); 10410 } 10411 10412 bool 10413 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10414 const auto *VT = E->getType()->castAs<VectorType>(); 10415 QualType EltTy = VT->getElementType(); 10416 APValue ZeroElement; 10417 if (EltTy->isIntegerType()) 10418 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10419 else 10420 ZeroElement = 10421 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10422 10423 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10424 return Success(Elements, E); 10425 } 10426 10427 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10428 VisitIgnoredValue(E->getSubExpr()); 10429 return ZeroInitialization(E); 10430 } 10431 10432 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10433 BinaryOperatorKind Op = E->getOpcode(); 10434 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10435 "Operation not supported on vector types"); 10436 10437 if (Op == BO_Comma) 10438 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10439 10440 Expr *LHS = E->getLHS(); 10441 Expr *RHS = E->getRHS(); 10442 10443 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10444 "Must both be vector types"); 10445 // Checking JUST the types are the same would be fine, except shifts don't 10446 // need to have their types be the same (since you always shift by an int). 10447 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10448 E->getType()->castAs<VectorType>()->getNumElements() && 10449 RHS->getType()->castAs<VectorType>()->getNumElements() == 10450 E->getType()->castAs<VectorType>()->getNumElements() && 10451 "All operands must be the same size."); 10452 10453 APValue LHSValue; 10454 APValue RHSValue; 10455 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10456 if (!LHSOK && !Info.noteFailure()) 10457 return false; 10458 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10459 return false; 10460 10461 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10462 return false; 10463 10464 return Success(LHSValue, E); 10465 } 10466 10467 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx, 10468 QualType ResultTy, 10469 UnaryOperatorKind Op, 10470 APValue Elt) { 10471 switch (Op) { 10472 case UO_Plus: 10473 // Nothing to do here. 10474 return Elt; 10475 case UO_Minus: 10476 if (Elt.getKind() == APValue::Int) { 10477 Elt.getInt().negate(); 10478 } else { 10479 assert(Elt.getKind() == APValue::Float && 10480 "Vector can only be int or float type"); 10481 Elt.getFloat().changeSign(); 10482 } 10483 return Elt; 10484 case UO_Not: 10485 // This is only valid for integral types anyway, so we don't have to handle 10486 // float here. 10487 assert(Elt.getKind() == APValue::Int && 10488 "Vector operator ~ can only be int"); 10489 Elt.getInt().flipAllBits(); 10490 return Elt; 10491 case UO_LNot: { 10492 if (Elt.getKind() == APValue::Int) { 10493 Elt.getInt() = !Elt.getInt(); 10494 // operator ! on vectors returns -1 for 'truth', so negate it. 10495 Elt.getInt().negate(); 10496 return Elt; 10497 } 10498 assert(Elt.getKind() == APValue::Float && 10499 "Vector can only be int or float type"); 10500 // Float types result in an int of the same size, but -1 for true, or 0 for 10501 // false. 10502 APSInt EltResult{Ctx.getIntWidth(ResultTy), 10503 ResultTy->isUnsignedIntegerType()}; 10504 if (Elt.getFloat().isZero()) 10505 EltResult.setAllBits(); 10506 else 10507 EltResult.clearAllBits(); 10508 10509 return APValue{EltResult}; 10510 } 10511 default: 10512 // FIXME: Implement the rest of the unary operators. 10513 return llvm::None; 10514 } 10515 } 10516 10517 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10518 Expr *SubExpr = E->getSubExpr(); 10519 const auto *VD = SubExpr->getType()->castAs<VectorType>(); 10520 // This result element type differs in the case of negating a floating point 10521 // vector, since the result type is the a vector of the equivilant sized 10522 // integer. 10523 const QualType ResultEltTy = VD->getElementType(); 10524 UnaryOperatorKind Op = E->getOpcode(); 10525 10526 APValue SubExprValue; 10527 if (!Evaluate(SubExprValue, Info, SubExpr)) 10528 return false; 10529 10530 // FIXME: This vector evaluator someday needs to be changed to be LValue 10531 // aware/keep LValue information around, rather than dealing with just vector 10532 // types directly. Until then, we cannot handle cases where the operand to 10533 // these unary operators is an LValue. The only case I've been able to see 10534 // cause this is operator++ assigning to a member expression (only valid in 10535 // altivec compilations) in C mode, so this shouldn't limit us too much. 10536 if (SubExprValue.isLValue()) 10537 return false; 10538 10539 assert(SubExprValue.getVectorLength() == VD->getNumElements() && 10540 "Vector length doesn't match type?"); 10541 10542 SmallVector<APValue, 4> ResultElements; 10543 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) { 10544 llvm::Optional<APValue> Elt = handleVectorUnaryOperator( 10545 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum)); 10546 if (!Elt) 10547 return false; 10548 ResultElements.push_back(*Elt); 10549 } 10550 return Success(APValue(ResultElements.data(), ResultElements.size()), E); 10551 } 10552 10553 //===----------------------------------------------------------------------===// 10554 // Array Evaluation 10555 //===----------------------------------------------------------------------===// 10556 10557 namespace { 10558 class ArrayExprEvaluator 10559 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10560 const LValue &This; 10561 APValue &Result; 10562 public: 10563 10564 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10565 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10566 10567 bool Success(const APValue &V, const Expr *E) { 10568 assert(V.isArray() && "expected array"); 10569 Result = V; 10570 return true; 10571 } 10572 10573 bool ZeroInitialization(const Expr *E) { 10574 const ConstantArrayType *CAT = 10575 Info.Ctx.getAsConstantArrayType(E->getType()); 10576 if (!CAT) { 10577 if (E->getType()->isIncompleteArrayType()) { 10578 // We can be asked to zero-initialize a flexible array member; this 10579 // is represented as an ImplicitValueInitExpr of incomplete array 10580 // type. In this case, the array has zero elements. 10581 Result = APValue(APValue::UninitArray(), 0, 0); 10582 return true; 10583 } 10584 // FIXME: We could handle VLAs here. 10585 return Error(E); 10586 } 10587 10588 Result = APValue(APValue::UninitArray(), 0, 10589 CAT->getSize().getZExtValue()); 10590 if (!Result.hasArrayFiller()) 10591 return true; 10592 10593 // Zero-initialize all elements. 10594 LValue Subobject = This; 10595 Subobject.addArray(Info, E, CAT); 10596 ImplicitValueInitExpr VIE(CAT->getElementType()); 10597 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10598 } 10599 10600 bool VisitCallExpr(const CallExpr *E) { 10601 return handleCallExpr(E, Result, &This); 10602 } 10603 bool VisitInitListExpr(const InitListExpr *E, 10604 QualType AllocType = QualType()); 10605 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10606 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10607 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10608 const LValue &Subobject, 10609 APValue *Value, QualType Type); 10610 bool VisitStringLiteral(const StringLiteral *E, 10611 QualType AllocType = QualType()) { 10612 expandStringLiteral(Info, E, Result, AllocType); 10613 return true; 10614 } 10615 }; 10616 } // end anonymous namespace 10617 10618 static bool EvaluateArray(const Expr *E, const LValue &This, 10619 APValue &Result, EvalInfo &Info) { 10620 assert(!E->isValueDependent()); 10621 assert(E->isPRValue() && E->getType()->isArrayType() && 10622 "not an array prvalue"); 10623 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10624 } 10625 10626 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10627 APValue &Result, const InitListExpr *ILE, 10628 QualType AllocType) { 10629 assert(!ILE->isValueDependent()); 10630 assert(ILE->isPRValue() && ILE->getType()->isArrayType() && 10631 "not an array prvalue"); 10632 return ArrayExprEvaluator(Info, This, Result) 10633 .VisitInitListExpr(ILE, AllocType); 10634 } 10635 10636 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10637 APValue &Result, 10638 const CXXConstructExpr *CCE, 10639 QualType AllocType) { 10640 assert(!CCE->isValueDependent()); 10641 assert(CCE->isPRValue() && CCE->getType()->isArrayType() && 10642 "not an array prvalue"); 10643 return ArrayExprEvaluator(Info, This, Result) 10644 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10645 } 10646 10647 // Return true iff the given array filler may depend on the element index. 10648 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10649 // For now, just allow non-class value-initialization and initialization 10650 // lists comprised of them. 10651 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10652 return false; 10653 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10654 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10655 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10656 return true; 10657 } 10658 return false; 10659 } 10660 return true; 10661 } 10662 10663 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10664 QualType AllocType) { 10665 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10666 AllocType.isNull() ? E->getType() : AllocType); 10667 if (!CAT) 10668 return Error(E); 10669 10670 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10671 // an appropriately-typed string literal enclosed in braces. 10672 if (E->isStringLiteralInit()) { 10673 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); 10674 // FIXME: Support ObjCEncodeExpr here once we support it in 10675 // ArrayExprEvaluator generally. 10676 if (!SL) 10677 return Error(E); 10678 return VisitStringLiteral(SL, AllocType); 10679 } 10680 // Any other transparent list init will need proper handling of the 10681 // AllocType; we can't just recurse to the inner initializer. 10682 assert(!E->isTransparent() && 10683 "transparent array list initialization is not string literal init?"); 10684 10685 bool Success = true; 10686 10687 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10688 "zero-initialized array shouldn't have any initialized elts"); 10689 APValue Filler; 10690 if (Result.isArray() && Result.hasArrayFiller()) 10691 Filler = Result.getArrayFiller(); 10692 10693 unsigned NumEltsToInit = E->getNumInits(); 10694 unsigned NumElts = CAT->getSize().getZExtValue(); 10695 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10696 10697 // If the initializer might depend on the array index, run it for each 10698 // array element. 10699 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10700 NumEltsToInit = NumElts; 10701 10702 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10703 << NumEltsToInit << ".\n"); 10704 10705 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10706 10707 // If the array was previously zero-initialized, preserve the 10708 // zero-initialized values. 10709 if (Filler.hasValue()) { 10710 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10711 Result.getArrayInitializedElt(I) = Filler; 10712 if (Result.hasArrayFiller()) 10713 Result.getArrayFiller() = Filler; 10714 } 10715 10716 LValue Subobject = This; 10717 Subobject.addArray(Info, E, CAT); 10718 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10719 const Expr *Init = 10720 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10721 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10722 Info, Subobject, Init) || 10723 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10724 CAT->getElementType(), 1)) { 10725 if (!Info.noteFailure()) 10726 return false; 10727 Success = false; 10728 } 10729 } 10730 10731 if (!Result.hasArrayFiller()) 10732 return Success; 10733 10734 // If we get here, we have a trivial filler, which we can just evaluate 10735 // once and splat over the rest of the array elements. 10736 assert(FillerExpr && "no array filler for incomplete init list"); 10737 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10738 FillerExpr) && Success; 10739 } 10740 10741 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10742 LValue CommonLV; 10743 if (E->getCommonExpr() && 10744 !Evaluate(Info.CurrentCall->createTemporary( 10745 E->getCommonExpr(), 10746 getStorageType(Info.Ctx, E->getCommonExpr()), 10747 ScopeKind::FullExpression, CommonLV), 10748 Info, E->getCommonExpr()->getSourceExpr())) 10749 return false; 10750 10751 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10752 10753 uint64_t Elements = CAT->getSize().getZExtValue(); 10754 Result = APValue(APValue::UninitArray(), Elements, Elements); 10755 10756 LValue Subobject = This; 10757 Subobject.addArray(Info, E, CAT); 10758 10759 bool Success = true; 10760 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10761 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10762 Info, Subobject, E->getSubExpr()) || 10763 !HandleLValueArrayAdjustment(Info, E, Subobject, 10764 CAT->getElementType(), 1)) { 10765 if (!Info.noteFailure()) 10766 return false; 10767 Success = false; 10768 } 10769 } 10770 10771 return Success; 10772 } 10773 10774 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10775 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10776 } 10777 10778 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10779 const LValue &Subobject, 10780 APValue *Value, 10781 QualType Type) { 10782 bool HadZeroInit = Value->hasValue(); 10783 10784 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10785 unsigned FinalSize = CAT->getSize().getZExtValue(); 10786 10787 // Preserve the array filler if we had prior zero-initialization. 10788 APValue Filler = 10789 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10790 : APValue(); 10791 10792 *Value = APValue(APValue::UninitArray(), 0, FinalSize); 10793 if (FinalSize == 0) 10794 return true; 10795 10796 LValue ArrayElt = Subobject; 10797 ArrayElt.addArray(Info, E, CAT); 10798 // We do the whole initialization in two passes, first for just one element, 10799 // then for the whole array. It's possible we may find out we can't do const 10800 // init in the first pass, in which case we avoid allocating a potentially 10801 // large array. We don't do more passes because expanding array requires 10802 // copying the data, which is wasteful. 10803 for (const unsigned N : {1u, FinalSize}) { 10804 unsigned OldElts = Value->getArrayInitializedElts(); 10805 if (OldElts == N) 10806 break; 10807 10808 // Expand the array to appropriate size. 10809 APValue NewValue(APValue::UninitArray(), N, FinalSize); 10810 for (unsigned I = 0; I < OldElts; ++I) 10811 NewValue.getArrayInitializedElt(I).swap( 10812 Value->getArrayInitializedElt(I)); 10813 Value->swap(NewValue); 10814 10815 if (HadZeroInit) 10816 for (unsigned I = OldElts; I < N; ++I) 10817 Value->getArrayInitializedElt(I) = Filler; 10818 10819 // Initialize the elements. 10820 for (unsigned I = OldElts; I < N; ++I) { 10821 if (!VisitCXXConstructExpr(E, ArrayElt, 10822 &Value->getArrayInitializedElt(I), 10823 CAT->getElementType()) || 10824 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10825 CAT->getElementType(), 1)) 10826 return false; 10827 // When checking for const initilization any diagnostic is considered 10828 // an error. 10829 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() && 10830 !Info.keepEvaluatingAfterFailure()) 10831 return false; 10832 } 10833 } 10834 10835 return true; 10836 } 10837 10838 if (!Type->isRecordType()) 10839 return Error(E); 10840 10841 return RecordExprEvaluator(Info, Subobject, *Value) 10842 .VisitCXXConstructExpr(E, Type); 10843 } 10844 10845 //===----------------------------------------------------------------------===// 10846 // Integer Evaluation 10847 // 10848 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10849 // types and back in constant folding. Integer values are thus represented 10850 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10851 //===----------------------------------------------------------------------===// 10852 10853 namespace { 10854 class IntExprEvaluator 10855 : public ExprEvaluatorBase<IntExprEvaluator> { 10856 APValue &Result; 10857 public: 10858 IntExprEvaluator(EvalInfo &info, APValue &result) 10859 : ExprEvaluatorBaseTy(info), Result(result) {} 10860 10861 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10862 assert(E->getType()->isIntegralOrEnumerationType() && 10863 "Invalid evaluation result."); 10864 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10865 "Invalid evaluation result."); 10866 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10867 "Invalid evaluation result."); 10868 Result = APValue(SI); 10869 return true; 10870 } 10871 bool Success(const llvm::APSInt &SI, const Expr *E) { 10872 return Success(SI, E, Result); 10873 } 10874 10875 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10876 assert(E->getType()->isIntegralOrEnumerationType() && 10877 "Invalid evaluation result."); 10878 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10879 "Invalid evaluation result."); 10880 Result = APValue(APSInt(I)); 10881 Result.getInt().setIsUnsigned( 10882 E->getType()->isUnsignedIntegerOrEnumerationType()); 10883 return true; 10884 } 10885 bool Success(const llvm::APInt &I, const Expr *E) { 10886 return Success(I, E, Result); 10887 } 10888 10889 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10890 assert(E->getType()->isIntegralOrEnumerationType() && 10891 "Invalid evaluation result."); 10892 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10893 return true; 10894 } 10895 bool Success(uint64_t Value, const Expr *E) { 10896 return Success(Value, E, Result); 10897 } 10898 10899 bool Success(CharUnits Size, const Expr *E) { 10900 return Success(Size.getQuantity(), E); 10901 } 10902 10903 bool Success(const APValue &V, const Expr *E) { 10904 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10905 Result = V; 10906 return true; 10907 } 10908 return Success(V.getInt(), E); 10909 } 10910 10911 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10912 10913 //===--------------------------------------------------------------------===// 10914 // Visitor Methods 10915 //===--------------------------------------------------------------------===// 10916 10917 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10918 return Success(E->getValue(), E); 10919 } 10920 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10921 return Success(E->getValue(), E); 10922 } 10923 10924 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10925 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10926 if (CheckReferencedDecl(E, E->getDecl())) 10927 return true; 10928 10929 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10930 } 10931 bool VisitMemberExpr(const MemberExpr *E) { 10932 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10933 VisitIgnoredBaseExpression(E->getBase()); 10934 return true; 10935 } 10936 10937 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10938 } 10939 10940 bool VisitCallExpr(const CallExpr *E); 10941 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10942 bool VisitBinaryOperator(const BinaryOperator *E); 10943 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10944 bool VisitUnaryOperator(const UnaryOperator *E); 10945 10946 bool VisitCastExpr(const CastExpr* E); 10947 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10948 10949 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10950 return Success(E->getValue(), E); 10951 } 10952 10953 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10954 return Success(E->getValue(), E); 10955 } 10956 10957 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10958 if (Info.ArrayInitIndex == uint64_t(-1)) { 10959 // We were asked to evaluate this subexpression independent of the 10960 // enclosing ArrayInitLoopExpr. We can't do that. 10961 Info.FFDiag(E); 10962 return false; 10963 } 10964 return Success(Info.ArrayInitIndex, E); 10965 } 10966 10967 // Note, GNU defines __null as an integer, not a pointer. 10968 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10969 return ZeroInitialization(E); 10970 } 10971 10972 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10973 return Success(E->getValue(), E); 10974 } 10975 10976 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10977 return Success(E->getValue(), E); 10978 } 10979 10980 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10981 return Success(E->getValue(), E); 10982 } 10983 10984 bool VisitUnaryReal(const UnaryOperator *E); 10985 bool VisitUnaryImag(const UnaryOperator *E); 10986 10987 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10988 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10989 bool VisitSourceLocExpr(const SourceLocExpr *E); 10990 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10991 bool VisitRequiresExpr(const RequiresExpr *E); 10992 // FIXME: Missing: array subscript of vector, member of vector 10993 }; 10994 10995 class FixedPointExprEvaluator 10996 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10997 APValue &Result; 10998 10999 public: 11000 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 11001 : ExprEvaluatorBaseTy(info), Result(result) {} 11002 11003 bool Success(const llvm::APInt &I, const Expr *E) { 11004 return Success( 11005 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11006 } 11007 11008 bool Success(uint64_t Value, const Expr *E) { 11009 return Success( 11010 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 11011 } 11012 11013 bool Success(const APValue &V, const Expr *E) { 11014 return Success(V.getFixedPoint(), E); 11015 } 11016 11017 bool Success(const APFixedPoint &V, const Expr *E) { 11018 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 11019 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 11020 "Invalid evaluation result."); 11021 Result = APValue(V); 11022 return true; 11023 } 11024 11025 //===--------------------------------------------------------------------===// 11026 // Visitor Methods 11027 //===--------------------------------------------------------------------===// 11028 11029 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 11030 return Success(E->getValue(), E); 11031 } 11032 11033 bool VisitCastExpr(const CastExpr *E); 11034 bool VisitUnaryOperator(const UnaryOperator *E); 11035 bool VisitBinaryOperator(const BinaryOperator *E); 11036 }; 11037 } // end anonymous namespace 11038 11039 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 11040 /// produce either the integer value or a pointer. 11041 /// 11042 /// GCC has a heinous extension which folds casts between pointer types and 11043 /// pointer-sized integral types. We support this by allowing the evaluation of 11044 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 11045 /// Some simple arithmetic on such values is supported (they are treated much 11046 /// like char*). 11047 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 11048 EvalInfo &Info) { 11049 assert(!E->isValueDependent()); 11050 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); 11051 return IntExprEvaluator(Info, Result).Visit(E); 11052 } 11053 11054 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 11055 assert(!E->isValueDependent()); 11056 APValue Val; 11057 if (!EvaluateIntegerOrLValue(E, Val, Info)) 11058 return false; 11059 if (!Val.isInt()) { 11060 // FIXME: It would be better to produce the diagnostic for casting 11061 // a pointer to an integer. 11062 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11063 return false; 11064 } 11065 Result = Val.getInt(); 11066 return true; 11067 } 11068 11069 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 11070 APValue Evaluated = E->EvaluateInContext( 11071 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 11072 return Success(Evaluated, E); 11073 } 11074 11075 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 11076 EvalInfo &Info) { 11077 assert(!E->isValueDependent()); 11078 if (E->getType()->isFixedPointType()) { 11079 APValue Val; 11080 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 11081 return false; 11082 if (!Val.isFixedPoint()) 11083 return false; 11084 11085 Result = Val.getFixedPoint(); 11086 return true; 11087 } 11088 return false; 11089 } 11090 11091 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 11092 EvalInfo &Info) { 11093 assert(!E->isValueDependent()); 11094 if (E->getType()->isIntegerType()) { 11095 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 11096 APSInt Val; 11097 if (!EvaluateInteger(E, Val, Info)) 11098 return false; 11099 Result = APFixedPoint(Val, FXSema); 11100 return true; 11101 } else if (E->getType()->isFixedPointType()) { 11102 return EvaluateFixedPoint(E, Result, Info); 11103 } 11104 return false; 11105 } 11106 11107 /// Check whether the given declaration can be directly converted to an integral 11108 /// rvalue. If not, no diagnostic is produced; there are other things we can 11109 /// try. 11110 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 11111 // Enums are integer constant exprs. 11112 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 11113 // Check for signedness/width mismatches between E type and ECD value. 11114 bool SameSign = (ECD->getInitVal().isSigned() 11115 == E->getType()->isSignedIntegerOrEnumerationType()); 11116 bool SameWidth = (ECD->getInitVal().getBitWidth() 11117 == Info.Ctx.getIntWidth(E->getType())); 11118 if (SameSign && SameWidth) 11119 return Success(ECD->getInitVal(), E); 11120 else { 11121 // Get rid of mismatch (otherwise Success assertions will fail) 11122 // by computing a new value matching the type of E. 11123 llvm::APSInt Val = ECD->getInitVal(); 11124 if (!SameSign) 11125 Val.setIsSigned(!ECD->getInitVal().isSigned()); 11126 if (!SameWidth) 11127 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 11128 return Success(Val, E); 11129 } 11130 } 11131 return false; 11132 } 11133 11134 /// Values returned by __builtin_classify_type, chosen to match the values 11135 /// produced by GCC's builtin. 11136 enum class GCCTypeClass { 11137 None = -1, 11138 Void = 0, 11139 Integer = 1, 11140 // GCC reserves 2 for character types, but instead classifies them as 11141 // integers. 11142 Enum = 3, 11143 Bool = 4, 11144 Pointer = 5, 11145 // GCC reserves 6 for references, but appears to never use it (because 11146 // expressions never have reference type, presumably). 11147 PointerToDataMember = 7, 11148 RealFloat = 8, 11149 Complex = 9, 11150 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 11151 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 11152 // GCC claims to reserve 11 for pointers to member functions, but *actually* 11153 // uses 12 for that purpose, same as for a class or struct. Maybe it 11154 // internally implements a pointer to member as a struct? Who knows. 11155 PointerToMemberFunction = 12, // Not a bug, see above. 11156 ClassOrStruct = 12, 11157 Union = 13, 11158 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 11159 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 11160 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 11161 // literals. 11162 }; 11163 11164 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11165 /// as GCC. 11166 static GCCTypeClass 11167 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 11168 assert(!T->isDependentType() && "unexpected dependent type"); 11169 11170 QualType CanTy = T.getCanonicalType(); 11171 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 11172 11173 switch (CanTy->getTypeClass()) { 11174 #define TYPE(ID, BASE) 11175 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 11176 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 11177 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 11178 #include "clang/AST/TypeNodes.inc" 11179 case Type::Auto: 11180 case Type::DeducedTemplateSpecialization: 11181 llvm_unreachable("unexpected non-canonical or dependent type"); 11182 11183 case Type::Builtin: 11184 switch (BT->getKind()) { 11185 #define BUILTIN_TYPE(ID, SINGLETON_ID) 11186 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 11187 case BuiltinType::ID: return GCCTypeClass::Integer; 11188 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 11189 case BuiltinType::ID: return GCCTypeClass::RealFloat; 11190 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 11191 case BuiltinType::ID: break; 11192 #include "clang/AST/BuiltinTypes.def" 11193 case BuiltinType::Void: 11194 return GCCTypeClass::Void; 11195 11196 case BuiltinType::Bool: 11197 return GCCTypeClass::Bool; 11198 11199 case BuiltinType::Char_U: 11200 case BuiltinType::UChar: 11201 case BuiltinType::WChar_U: 11202 case BuiltinType::Char8: 11203 case BuiltinType::Char16: 11204 case BuiltinType::Char32: 11205 case BuiltinType::UShort: 11206 case BuiltinType::UInt: 11207 case BuiltinType::ULong: 11208 case BuiltinType::ULongLong: 11209 case BuiltinType::UInt128: 11210 return GCCTypeClass::Integer; 11211 11212 case BuiltinType::UShortAccum: 11213 case BuiltinType::UAccum: 11214 case BuiltinType::ULongAccum: 11215 case BuiltinType::UShortFract: 11216 case BuiltinType::UFract: 11217 case BuiltinType::ULongFract: 11218 case BuiltinType::SatUShortAccum: 11219 case BuiltinType::SatUAccum: 11220 case BuiltinType::SatULongAccum: 11221 case BuiltinType::SatUShortFract: 11222 case BuiltinType::SatUFract: 11223 case BuiltinType::SatULongFract: 11224 return GCCTypeClass::None; 11225 11226 case BuiltinType::NullPtr: 11227 11228 case BuiltinType::ObjCId: 11229 case BuiltinType::ObjCClass: 11230 case BuiltinType::ObjCSel: 11231 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11232 case BuiltinType::Id: 11233 #include "clang/Basic/OpenCLImageTypes.def" 11234 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11235 case BuiltinType::Id: 11236 #include "clang/Basic/OpenCLExtensionTypes.def" 11237 case BuiltinType::OCLSampler: 11238 case BuiltinType::OCLEvent: 11239 case BuiltinType::OCLClkEvent: 11240 case BuiltinType::OCLQueue: 11241 case BuiltinType::OCLReserveID: 11242 #define SVE_TYPE(Name, Id, SingletonId) \ 11243 case BuiltinType::Id: 11244 #include "clang/Basic/AArch64SVEACLETypes.def" 11245 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11246 case BuiltinType::Id: 11247 #include "clang/Basic/PPCTypes.def" 11248 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11249 #include "clang/Basic/RISCVVTypes.def" 11250 return GCCTypeClass::None; 11251 11252 case BuiltinType::Dependent: 11253 llvm_unreachable("unexpected dependent type"); 11254 }; 11255 llvm_unreachable("unexpected placeholder type"); 11256 11257 case Type::Enum: 11258 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11259 11260 case Type::Pointer: 11261 case Type::ConstantArray: 11262 case Type::VariableArray: 11263 case Type::IncompleteArray: 11264 case Type::FunctionNoProto: 11265 case Type::FunctionProto: 11266 return GCCTypeClass::Pointer; 11267 11268 case Type::MemberPointer: 11269 return CanTy->isMemberDataPointerType() 11270 ? GCCTypeClass::PointerToDataMember 11271 : GCCTypeClass::PointerToMemberFunction; 11272 11273 case Type::Complex: 11274 return GCCTypeClass::Complex; 11275 11276 case Type::Record: 11277 return CanTy->isUnionType() ? GCCTypeClass::Union 11278 : GCCTypeClass::ClassOrStruct; 11279 11280 case Type::Atomic: 11281 // GCC classifies _Atomic T the same as T. 11282 return EvaluateBuiltinClassifyType( 11283 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11284 11285 case Type::BlockPointer: 11286 case Type::Vector: 11287 case Type::ExtVector: 11288 case Type::ConstantMatrix: 11289 case Type::ObjCObject: 11290 case Type::ObjCInterface: 11291 case Type::ObjCObjectPointer: 11292 case Type::Pipe: 11293 case Type::BitInt: 11294 // GCC classifies vectors as None. We follow its lead and classify all 11295 // other types that don't fit into the regular classification the same way. 11296 return GCCTypeClass::None; 11297 11298 case Type::LValueReference: 11299 case Type::RValueReference: 11300 llvm_unreachable("invalid type for expression"); 11301 } 11302 11303 llvm_unreachable("unexpected type class"); 11304 } 11305 11306 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11307 /// as GCC. 11308 static GCCTypeClass 11309 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11310 // If no argument was supplied, default to None. This isn't 11311 // ideal, however it is what gcc does. 11312 if (E->getNumArgs() == 0) 11313 return GCCTypeClass::None; 11314 11315 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11316 // being an ICE, but still folds it to a constant using the type of the first 11317 // argument. 11318 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11319 } 11320 11321 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11322 /// __builtin_constant_p when applied to the given pointer. 11323 /// 11324 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11325 /// or it points to the first character of a string literal. 11326 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11327 APValue::LValueBase Base = LV.getLValueBase(); 11328 if (Base.isNull()) { 11329 // A null base is acceptable. 11330 return true; 11331 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11332 if (!isa<StringLiteral>(E)) 11333 return false; 11334 return LV.getLValueOffset().isZero(); 11335 } else if (Base.is<TypeInfoLValue>()) { 11336 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11337 // evaluate to true. 11338 return true; 11339 } else { 11340 // Any other base is not constant enough for GCC. 11341 return false; 11342 } 11343 } 11344 11345 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11346 /// GCC as we can manage. 11347 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11348 // This evaluation is not permitted to have side-effects, so evaluate it in 11349 // a speculative evaluation context. 11350 SpeculativeEvaluationRAII SpeculativeEval(Info); 11351 11352 // Constant-folding is always enabled for the operand of __builtin_constant_p 11353 // (even when the enclosing evaluation context otherwise requires a strict 11354 // language-specific constant expression). 11355 FoldConstant Fold(Info, true); 11356 11357 QualType ArgType = Arg->getType(); 11358 11359 // __builtin_constant_p always has one operand. The rules which gcc follows 11360 // are not precisely documented, but are as follows: 11361 // 11362 // - If the operand is of integral, floating, complex or enumeration type, 11363 // and can be folded to a known value of that type, it returns 1. 11364 // - If the operand can be folded to a pointer to the first character 11365 // of a string literal (or such a pointer cast to an integral type) 11366 // or to a null pointer or an integer cast to a pointer, it returns 1. 11367 // 11368 // Otherwise, it returns 0. 11369 // 11370 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11371 // its support for this did not work prior to GCC 9 and is not yet well 11372 // understood. 11373 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11374 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11375 ArgType->isNullPtrType()) { 11376 APValue V; 11377 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11378 Fold.keepDiagnostics(); 11379 return false; 11380 } 11381 11382 // For a pointer (possibly cast to integer), there are special rules. 11383 if (V.getKind() == APValue::LValue) 11384 return EvaluateBuiltinConstantPForLValue(V); 11385 11386 // Otherwise, any constant value is good enough. 11387 return V.hasValue(); 11388 } 11389 11390 // Anything else isn't considered to be sufficiently constant. 11391 return false; 11392 } 11393 11394 /// Retrieves the "underlying object type" of the given expression, 11395 /// as used by __builtin_object_size. 11396 static QualType getObjectType(APValue::LValueBase B) { 11397 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11398 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11399 return VD->getType(); 11400 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11401 if (isa<CompoundLiteralExpr>(E)) 11402 return E->getType(); 11403 } else if (B.is<TypeInfoLValue>()) { 11404 return B.getTypeInfoType(); 11405 } else if (B.is<DynamicAllocLValue>()) { 11406 return B.getDynamicAllocType(); 11407 } 11408 11409 return QualType(); 11410 } 11411 11412 /// A more selective version of E->IgnoreParenCasts for 11413 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11414 /// to change the type of E. 11415 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11416 /// 11417 /// Always returns an RValue with a pointer representation. 11418 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11419 assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); 11420 11421 auto *NoParens = E->IgnoreParens(); 11422 auto *Cast = dyn_cast<CastExpr>(NoParens); 11423 if (Cast == nullptr) 11424 return NoParens; 11425 11426 // We only conservatively allow a few kinds of casts, because this code is 11427 // inherently a simple solution that seeks to support the common case. 11428 auto CastKind = Cast->getCastKind(); 11429 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11430 CastKind != CK_AddressSpaceConversion) 11431 return NoParens; 11432 11433 auto *SubExpr = Cast->getSubExpr(); 11434 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) 11435 return NoParens; 11436 return ignorePointerCastsAndParens(SubExpr); 11437 } 11438 11439 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11440 /// record layout. e.g. 11441 /// struct { struct { int a, b; } fst, snd; } obj; 11442 /// obj.fst // no 11443 /// obj.snd // yes 11444 /// obj.fst.a // no 11445 /// obj.fst.b // no 11446 /// obj.snd.a // no 11447 /// obj.snd.b // yes 11448 /// 11449 /// Please note: this function is specialized for how __builtin_object_size 11450 /// views "objects". 11451 /// 11452 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11453 /// correct result, it will always return true. 11454 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11455 assert(!LVal.Designator.Invalid); 11456 11457 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11458 const RecordDecl *Parent = FD->getParent(); 11459 Invalid = Parent->isInvalidDecl(); 11460 if (Invalid || Parent->isUnion()) 11461 return true; 11462 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11463 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11464 }; 11465 11466 auto &Base = LVal.getLValueBase(); 11467 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11468 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11469 bool Invalid; 11470 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11471 return Invalid; 11472 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11473 for (auto *FD : IFD->chain()) { 11474 bool Invalid; 11475 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11476 return Invalid; 11477 } 11478 } 11479 } 11480 11481 unsigned I = 0; 11482 QualType BaseType = getType(Base); 11483 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11484 // If we don't know the array bound, conservatively assume we're looking at 11485 // the final array element. 11486 ++I; 11487 if (BaseType->isIncompleteArrayType()) 11488 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11489 else 11490 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11491 } 11492 11493 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11494 const auto &Entry = LVal.Designator.Entries[I]; 11495 if (BaseType->isArrayType()) { 11496 // Because __builtin_object_size treats arrays as objects, we can ignore 11497 // the index iff this is the last array in the Designator. 11498 if (I + 1 == E) 11499 return true; 11500 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11501 uint64_t Index = Entry.getAsArrayIndex(); 11502 if (Index + 1 != CAT->getSize()) 11503 return false; 11504 BaseType = CAT->getElementType(); 11505 } else if (BaseType->isAnyComplexType()) { 11506 const auto *CT = BaseType->castAs<ComplexType>(); 11507 uint64_t Index = Entry.getAsArrayIndex(); 11508 if (Index != 1) 11509 return false; 11510 BaseType = CT->getElementType(); 11511 } else if (auto *FD = getAsField(Entry)) { 11512 bool Invalid; 11513 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11514 return Invalid; 11515 BaseType = FD->getType(); 11516 } else { 11517 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11518 return false; 11519 } 11520 } 11521 return true; 11522 } 11523 11524 /// Tests to see if the LValue has a user-specified designator (that isn't 11525 /// necessarily valid). Note that this always returns 'true' if the LValue has 11526 /// an unsized array as its first designator entry, because there's currently no 11527 /// way to tell if the user typed *foo or foo[0]. 11528 static bool refersToCompleteObject(const LValue &LVal) { 11529 if (LVal.Designator.Invalid) 11530 return false; 11531 11532 if (!LVal.Designator.Entries.empty()) 11533 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11534 11535 if (!LVal.InvalidBase) 11536 return true; 11537 11538 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11539 // the LValueBase. 11540 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11541 return !E || !isa<MemberExpr>(E); 11542 } 11543 11544 /// Attempts to detect a user writing into a piece of memory that's impossible 11545 /// to figure out the size of by just using types. 11546 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11547 const SubobjectDesignator &Designator = LVal.Designator; 11548 // Notes: 11549 // - Users can only write off of the end when we have an invalid base. Invalid 11550 // bases imply we don't know where the memory came from. 11551 // - We used to be a bit more aggressive here; we'd only be conservative if 11552 // the array at the end was flexible, or if it had 0 or 1 elements. This 11553 // broke some common standard library extensions (PR30346), but was 11554 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11555 // with some sort of list. OTOH, it seems that GCC is always 11556 // conservative with the last element in structs (if it's an array), so our 11557 // current behavior is more compatible than an explicit list approach would 11558 // be. 11559 return LVal.InvalidBase && 11560 Designator.Entries.size() == Designator.MostDerivedPathLength && 11561 Designator.MostDerivedIsArrayElement && 11562 isDesignatorAtObjectEnd(Ctx, LVal); 11563 } 11564 11565 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11566 /// Fails if the conversion would cause loss of precision. 11567 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11568 CharUnits &Result) { 11569 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11570 if (Int.ugt(CharUnitsMax)) 11571 return false; 11572 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11573 return true; 11574 } 11575 11576 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11577 /// determine how many bytes exist from the beginning of the object to either 11578 /// the end of the current subobject, or the end of the object itself, depending 11579 /// on what the LValue looks like + the value of Type. 11580 /// 11581 /// If this returns false, the value of Result is undefined. 11582 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11583 unsigned Type, const LValue &LVal, 11584 CharUnits &EndOffset) { 11585 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11586 11587 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11588 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11589 return false; 11590 return HandleSizeof(Info, ExprLoc, Ty, Result); 11591 }; 11592 11593 // We want to evaluate the size of the entire object. This is a valid fallback 11594 // for when Type=1 and the designator is invalid, because we're asked for an 11595 // upper-bound. 11596 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11597 // Type=3 wants a lower bound, so we can't fall back to this. 11598 if (Type == 3 && !DetermineForCompleteObject) 11599 return false; 11600 11601 llvm::APInt APEndOffset; 11602 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11603 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11604 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11605 11606 if (LVal.InvalidBase) 11607 return false; 11608 11609 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11610 return CheckedHandleSizeof(BaseTy, EndOffset); 11611 } 11612 11613 // We want to evaluate the size of a subobject. 11614 const SubobjectDesignator &Designator = LVal.Designator; 11615 11616 // The following is a moderately common idiom in C: 11617 // 11618 // struct Foo { int a; char c[1]; }; 11619 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11620 // strcpy(&F->c[0], Bar); 11621 // 11622 // In order to not break too much legacy code, we need to support it. 11623 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11624 // If we can resolve this to an alloc_size call, we can hand that back, 11625 // because we know for certain how many bytes there are to write to. 11626 llvm::APInt APEndOffset; 11627 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11628 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11629 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11630 11631 // If we cannot determine the size of the initial allocation, then we can't 11632 // given an accurate upper-bound. However, we are still able to give 11633 // conservative lower-bounds for Type=3. 11634 if (Type == 1) 11635 return false; 11636 } 11637 11638 CharUnits BytesPerElem; 11639 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11640 return false; 11641 11642 // According to the GCC documentation, we want the size of the subobject 11643 // denoted by the pointer. But that's not quite right -- what we actually 11644 // want is the size of the immediately-enclosing array, if there is one. 11645 int64_t ElemsRemaining; 11646 if (Designator.MostDerivedIsArrayElement && 11647 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11648 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11649 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11650 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11651 } else { 11652 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11653 } 11654 11655 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11656 return true; 11657 } 11658 11659 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11660 /// returns true and stores the result in @p Size. 11661 /// 11662 /// If @p WasError is non-null, this will report whether the failure to evaluate 11663 /// is to be treated as an Error in IntExprEvaluator. 11664 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11665 EvalInfo &Info, uint64_t &Size) { 11666 // Determine the denoted object. 11667 LValue LVal; 11668 { 11669 // The operand of __builtin_object_size is never evaluated for side-effects. 11670 // If there are any, but we can determine the pointed-to object anyway, then 11671 // ignore the side-effects. 11672 SpeculativeEvaluationRAII SpeculativeEval(Info); 11673 IgnoreSideEffectsRAII Fold(Info); 11674 11675 if (E->isGLValue()) { 11676 // It's possible for us to be given GLValues if we're called via 11677 // Expr::tryEvaluateObjectSize. 11678 APValue RVal; 11679 if (!EvaluateAsRValue(Info, E, RVal)) 11680 return false; 11681 LVal.setFrom(Info.Ctx, RVal); 11682 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11683 /*InvalidBaseOK=*/true)) 11684 return false; 11685 } 11686 11687 // If we point to before the start of the object, there are no accessible 11688 // bytes. 11689 if (LVal.getLValueOffset().isNegative()) { 11690 Size = 0; 11691 return true; 11692 } 11693 11694 CharUnits EndOffset; 11695 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11696 return false; 11697 11698 // If we've fallen outside of the end offset, just pretend there's nothing to 11699 // write to/read from. 11700 if (EndOffset <= LVal.getLValueOffset()) 11701 Size = 0; 11702 else 11703 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11704 return true; 11705 } 11706 11707 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11708 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11709 return VisitBuiltinCallExpr(E, BuiltinOp); 11710 11711 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11712 } 11713 11714 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11715 APValue &Val, APSInt &Alignment) { 11716 QualType SrcTy = E->getArg(0)->getType(); 11717 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11718 return false; 11719 // Even though we are evaluating integer expressions we could get a pointer 11720 // argument for the __builtin_is_aligned() case. 11721 if (SrcTy->isPointerType()) { 11722 LValue Ptr; 11723 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11724 return false; 11725 Ptr.moveInto(Val); 11726 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11727 Info.FFDiag(E->getArg(0)); 11728 return false; 11729 } else { 11730 APSInt SrcInt; 11731 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11732 return false; 11733 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11734 "Bit widths must be the same"); 11735 Val = APValue(SrcInt); 11736 } 11737 assert(Val.hasValue()); 11738 return true; 11739 } 11740 11741 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11742 unsigned BuiltinOp) { 11743 switch (BuiltinOp) { 11744 default: 11745 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11746 11747 case Builtin::BI__builtin_dynamic_object_size: 11748 case Builtin::BI__builtin_object_size: { 11749 // The type was checked when we built the expression. 11750 unsigned Type = 11751 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11752 assert(Type <= 3 && "unexpected type"); 11753 11754 uint64_t Size; 11755 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11756 return Success(Size, E); 11757 11758 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11759 return Success((Type & 2) ? 0 : -1, E); 11760 11761 // Expression had no side effects, but we couldn't statically determine the 11762 // size of the referenced object. 11763 switch (Info.EvalMode) { 11764 case EvalInfo::EM_ConstantExpression: 11765 case EvalInfo::EM_ConstantFold: 11766 case EvalInfo::EM_IgnoreSideEffects: 11767 // Leave it to IR generation. 11768 return Error(E); 11769 case EvalInfo::EM_ConstantExpressionUnevaluated: 11770 // Reduce it to a constant now. 11771 return Success((Type & 2) ? 0 : -1, E); 11772 } 11773 11774 llvm_unreachable("unexpected EvalMode"); 11775 } 11776 11777 case Builtin::BI__builtin_os_log_format_buffer_size: { 11778 analyze_os_log::OSLogBufferLayout Layout; 11779 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11780 return Success(Layout.size().getQuantity(), E); 11781 } 11782 11783 case Builtin::BI__builtin_is_aligned: { 11784 APValue Src; 11785 APSInt Alignment; 11786 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11787 return false; 11788 if (Src.isLValue()) { 11789 // If we evaluated a pointer, check the minimum known alignment. 11790 LValue Ptr; 11791 Ptr.setFrom(Info.Ctx, Src); 11792 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11793 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11794 // We can return true if the known alignment at the computed offset is 11795 // greater than the requested alignment. 11796 assert(PtrAlign.isPowerOfTwo()); 11797 assert(Alignment.isPowerOf2()); 11798 if (PtrAlign.getQuantity() >= Alignment) 11799 return Success(1, E); 11800 // If the alignment is not known to be sufficient, some cases could still 11801 // be aligned at run time. However, if the requested alignment is less or 11802 // equal to the base alignment and the offset is not aligned, we know that 11803 // the run-time value can never be aligned. 11804 if (BaseAlignment.getQuantity() >= Alignment && 11805 PtrAlign.getQuantity() < Alignment) 11806 return Success(0, E); 11807 // Otherwise we can't infer whether the value is sufficiently aligned. 11808 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11809 // in cases where we can't fully evaluate the pointer. 11810 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11811 << Alignment; 11812 return false; 11813 } 11814 assert(Src.isInt()); 11815 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11816 } 11817 case Builtin::BI__builtin_align_up: { 11818 APValue Src; 11819 APSInt Alignment; 11820 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11821 return false; 11822 if (!Src.isInt()) 11823 return Error(E); 11824 APSInt AlignedVal = 11825 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11826 Src.getInt().isUnsigned()); 11827 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11828 return Success(AlignedVal, E); 11829 } 11830 case Builtin::BI__builtin_align_down: { 11831 APValue Src; 11832 APSInt Alignment; 11833 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11834 return false; 11835 if (!Src.isInt()) 11836 return Error(E); 11837 APSInt AlignedVal = 11838 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11839 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11840 return Success(AlignedVal, E); 11841 } 11842 11843 case Builtin::BI__builtin_bitreverse8: 11844 case Builtin::BI__builtin_bitreverse16: 11845 case Builtin::BI__builtin_bitreverse32: 11846 case Builtin::BI__builtin_bitreverse64: { 11847 APSInt Val; 11848 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11849 return false; 11850 11851 return Success(Val.reverseBits(), E); 11852 } 11853 11854 case Builtin::BI__builtin_bswap16: 11855 case Builtin::BI__builtin_bswap32: 11856 case Builtin::BI__builtin_bswap64: { 11857 APSInt Val; 11858 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11859 return false; 11860 11861 return Success(Val.byteSwap(), E); 11862 } 11863 11864 case Builtin::BI__builtin_classify_type: 11865 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11866 11867 case Builtin::BI__builtin_clrsb: 11868 case Builtin::BI__builtin_clrsbl: 11869 case Builtin::BI__builtin_clrsbll: { 11870 APSInt Val; 11871 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11872 return false; 11873 11874 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11875 } 11876 11877 case Builtin::BI__builtin_clz: 11878 case Builtin::BI__builtin_clzl: 11879 case Builtin::BI__builtin_clzll: 11880 case Builtin::BI__builtin_clzs: { 11881 APSInt Val; 11882 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11883 return false; 11884 if (!Val) 11885 return Error(E); 11886 11887 return Success(Val.countLeadingZeros(), E); 11888 } 11889 11890 case Builtin::BI__builtin_constant_p: { 11891 const Expr *Arg = E->getArg(0); 11892 if (EvaluateBuiltinConstantP(Info, Arg)) 11893 return Success(true, E); 11894 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11895 // Outside a constant context, eagerly evaluate to false in the presence 11896 // of side-effects in order to avoid -Wunsequenced false-positives in 11897 // a branch on __builtin_constant_p(expr). 11898 return Success(false, E); 11899 } 11900 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11901 return false; 11902 } 11903 11904 case Builtin::BI__builtin_is_constant_evaluated: { 11905 const auto *Callee = Info.CurrentCall->getCallee(); 11906 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11907 (Info.CallStackDepth == 1 || 11908 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11909 Callee->getIdentifier() && 11910 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11911 // FIXME: Find a better way to avoid duplicated diagnostics. 11912 if (Info.EvalStatus.Diag) 11913 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11914 : Info.CurrentCall->CallLoc, 11915 diag::warn_is_constant_evaluated_always_true_constexpr) 11916 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11917 : "std::is_constant_evaluated"); 11918 } 11919 11920 return Success(Info.InConstantContext, E); 11921 } 11922 11923 case Builtin::BI__builtin_ctz: 11924 case Builtin::BI__builtin_ctzl: 11925 case Builtin::BI__builtin_ctzll: 11926 case Builtin::BI__builtin_ctzs: { 11927 APSInt Val; 11928 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11929 return false; 11930 if (!Val) 11931 return Error(E); 11932 11933 return Success(Val.countTrailingZeros(), E); 11934 } 11935 11936 case Builtin::BI__builtin_eh_return_data_regno: { 11937 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11938 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11939 return Success(Operand, E); 11940 } 11941 11942 case Builtin::BI__builtin_expect: 11943 case Builtin::BI__builtin_expect_with_probability: 11944 return Visit(E->getArg(0)); 11945 11946 case Builtin::BI__builtin_ffs: 11947 case Builtin::BI__builtin_ffsl: 11948 case Builtin::BI__builtin_ffsll: { 11949 APSInt Val; 11950 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11951 return false; 11952 11953 unsigned N = Val.countTrailingZeros(); 11954 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11955 } 11956 11957 case Builtin::BI__builtin_fpclassify: { 11958 APFloat Val(0.0); 11959 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11960 return false; 11961 unsigned Arg; 11962 switch (Val.getCategory()) { 11963 case APFloat::fcNaN: Arg = 0; break; 11964 case APFloat::fcInfinity: Arg = 1; break; 11965 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11966 case APFloat::fcZero: Arg = 4; break; 11967 } 11968 return Visit(E->getArg(Arg)); 11969 } 11970 11971 case Builtin::BI__builtin_isinf_sign: { 11972 APFloat Val(0.0); 11973 return EvaluateFloat(E->getArg(0), Val, Info) && 11974 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11975 } 11976 11977 case Builtin::BI__builtin_isinf: { 11978 APFloat Val(0.0); 11979 return EvaluateFloat(E->getArg(0), Val, Info) && 11980 Success(Val.isInfinity() ? 1 : 0, E); 11981 } 11982 11983 case Builtin::BI__builtin_isfinite: { 11984 APFloat Val(0.0); 11985 return EvaluateFloat(E->getArg(0), Val, Info) && 11986 Success(Val.isFinite() ? 1 : 0, E); 11987 } 11988 11989 case Builtin::BI__builtin_isnan: { 11990 APFloat Val(0.0); 11991 return EvaluateFloat(E->getArg(0), Val, Info) && 11992 Success(Val.isNaN() ? 1 : 0, E); 11993 } 11994 11995 case Builtin::BI__builtin_isnormal: { 11996 APFloat Val(0.0); 11997 return EvaluateFloat(E->getArg(0), Val, Info) && 11998 Success(Val.isNormal() ? 1 : 0, E); 11999 } 12000 12001 case Builtin::BI__builtin_parity: 12002 case Builtin::BI__builtin_parityl: 12003 case Builtin::BI__builtin_parityll: { 12004 APSInt Val; 12005 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12006 return false; 12007 12008 return Success(Val.countPopulation() % 2, E); 12009 } 12010 12011 case Builtin::BI__builtin_popcount: 12012 case Builtin::BI__builtin_popcountl: 12013 case Builtin::BI__builtin_popcountll: { 12014 APSInt Val; 12015 if (!EvaluateInteger(E->getArg(0), Val, Info)) 12016 return false; 12017 12018 return Success(Val.countPopulation(), E); 12019 } 12020 12021 case Builtin::BI__builtin_rotateleft8: 12022 case Builtin::BI__builtin_rotateleft16: 12023 case Builtin::BI__builtin_rotateleft32: 12024 case Builtin::BI__builtin_rotateleft64: 12025 case Builtin::BI_rotl8: // Microsoft variants of rotate right 12026 case Builtin::BI_rotl16: 12027 case Builtin::BI_rotl: 12028 case Builtin::BI_lrotl: 12029 case Builtin::BI_rotl64: { 12030 APSInt Val, Amt; 12031 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12032 !EvaluateInteger(E->getArg(1), Amt, Info)) 12033 return false; 12034 12035 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 12036 } 12037 12038 case Builtin::BI__builtin_rotateright8: 12039 case Builtin::BI__builtin_rotateright16: 12040 case Builtin::BI__builtin_rotateright32: 12041 case Builtin::BI__builtin_rotateright64: 12042 case Builtin::BI_rotr8: // Microsoft variants of rotate right 12043 case Builtin::BI_rotr16: 12044 case Builtin::BI_rotr: 12045 case Builtin::BI_lrotr: 12046 case Builtin::BI_rotr64: { 12047 APSInt Val, Amt; 12048 if (!EvaluateInteger(E->getArg(0), Val, Info) || 12049 !EvaluateInteger(E->getArg(1), Amt, Info)) 12050 return false; 12051 12052 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 12053 } 12054 12055 case Builtin::BIstrlen: 12056 case Builtin::BIwcslen: 12057 // A call to strlen is not a constant expression. 12058 if (Info.getLangOpts().CPlusPlus11) 12059 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12060 << /*isConstexpr*/0 << /*isConstructor*/0 12061 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12062 else 12063 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12064 LLVM_FALLTHROUGH; 12065 case Builtin::BI__builtin_strlen: 12066 case Builtin::BI__builtin_wcslen: { 12067 // As an extension, we support __builtin_strlen() as a constant expression, 12068 // and support folding strlen() to a constant. 12069 uint64_t StrLen; 12070 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) 12071 return Success(StrLen, E); 12072 return false; 12073 } 12074 12075 case Builtin::BIstrcmp: 12076 case Builtin::BIwcscmp: 12077 case Builtin::BIstrncmp: 12078 case Builtin::BIwcsncmp: 12079 case Builtin::BImemcmp: 12080 case Builtin::BIbcmp: 12081 case Builtin::BIwmemcmp: 12082 // A call to strlen is not a constant expression. 12083 if (Info.getLangOpts().CPlusPlus11) 12084 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 12085 << /*isConstexpr*/0 << /*isConstructor*/0 12086 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 12087 else 12088 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 12089 LLVM_FALLTHROUGH; 12090 case Builtin::BI__builtin_strcmp: 12091 case Builtin::BI__builtin_wcscmp: 12092 case Builtin::BI__builtin_strncmp: 12093 case Builtin::BI__builtin_wcsncmp: 12094 case Builtin::BI__builtin_memcmp: 12095 case Builtin::BI__builtin_bcmp: 12096 case Builtin::BI__builtin_wmemcmp: { 12097 LValue String1, String2; 12098 if (!EvaluatePointer(E->getArg(0), String1, Info) || 12099 !EvaluatePointer(E->getArg(1), String2, Info)) 12100 return false; 12101 12102 uint64_t MaxLength = uint64_t(-1); 12103 if (BuiltinOp != Builtin::BIstrcmp && 12104 BuiltinOp != Builtin::BIwcscmp && 12105 BuiltinOp != Builtin::BI__builtin_strcmp && 12106 BuiltinOp != Builtin::BI__builtin_wcscmp) { 12107 APSInt N; 12108 if (!EvaluateInteger(E->getArg(2), N, Info)) 12109 return false; 12110 MaxLength = N.getExtValue(); 12111 } 12112 12113 // Empty substrings compare equal by definition. 12114 if (MaxLength == 0u) 12115 return Success(0, E); 12116 12117 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12118 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 12119 String1.Designator.Invalid || String2.Designator.Invalid) 12120 return false; 12121 12122 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 12123 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 12124 12125 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 12126 BuiltinOp == Builtin::BIbcmp || 12127 BuiltinOp == Builtin::BI__builtin_memcmp || 12128 BuiltinOp == Builtin::BI__builtin_bcmp; 12129 12130 assert(IsRawByte || 12131 (Info.Ctx.hasSameUnqualifiedType( 12132 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 12133 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 12134 12135 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 12136 // 'char8_t', but no other types. 12137 if (IsRawByte && 12138 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 12139 // FIXME: Consider using our bit_cast implementation to support this. 12140 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 12141 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 12142 << CharTy1 << CharTy2; 12143 return false; 12144 } 12145 12146 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 12147 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 12148 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 12149 Char1.isInt() && Char2.isInt(); 12150 }; 12151 const auto &AdvanceElems = [&] { 12152 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 12153 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 12154 }; 12155 12156 bool StopAtNull = 12157 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 12158 BuiltinOp != Builtin::BIwmemcmp && 12159 BuiltinOp != Builtin::BI__builtin_memcmp && 12160 BuiltinOp != Builtin::BI__builtin_bcmp && 12161 BuiltinOp != Builtin::BI__builtin_wmemcmp); 12162 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 12163 BuiltinOp == Builtin::BIwcsncmp || 12164 BuiltinOp == Builtin::BIwmemcmp || 12165 BuiltinOp == Builtin::BI__builtin_wcscmp || 12166 BuiltinOp == Builtin::BI__builtin_wcsncmp || 12167 BuiltinOp == Builtin::BI__builtin_wmemcmp; 12168 12169 for (; MaxLength; --MaxLength) { 12170 APValue Char1, Char2; 12171 if (!ReadCurElems(Char1, Char2)) 12172 return false; 12173 if (Char1.getInt().ne(Char2.getInt())) { 12174 if (IsWide) // wmemcmp compares with wchar_t signedness. 12175 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 12176 // memcmp always compares unsigned chars. 12177 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 12178 } 12179 if (StopAtNull && !Char1.getInt()) 12180 return Success(0, E); 12181 assert(!(StopAtNull && !Char2.getInt())); 12182 if (!AdvanceElems()) 12183 return false; 12184 } 12185 // We hit the strncmp / memcmp limit. 12186 return Success(0, E); 12187 } 12188 12189 case Builtin::BI__atomic_always_lock_free: 12190 case Builtin::BI__atomic_is_lock_free: 12191 case Builtin::BI__c11_atomic_is_lock_free: { 12192 APSInt SizeVal; 12193 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 12194 return false; 12195 12196 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12197 // of two less than or equal to the maximum inline atomic width, we know it 12198 // is lock-free. If the size isn't a power of two, or greater than the 12199 // maximum alignment where we promote atomics, we know it is not lock-free 12200 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12201 // the answer can only be determined at runtime; for example, 16-byte 12202 // atomics have lock-free implementations on some, but not all, 12203 // x86-64 processors. 12204 12205 // Check power-of-two. 12206 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12207 if (Size.isPowerOfTwo()) { 12208 // Check against inlining width. 12209 unsigned InlineWidthBits = 12210 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12211 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12212 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12213 Size == CharUnits::One() || 12214 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12215 Expr::NPC_NeverValueDependent)) 12216 // OK, we will inline appropriately-aligned operations of this size, 12217 // and _Atomic(T) is appropriately-aligned. 12218 return Success(1, E); 12219 12220 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12221 castAs<PointerType>()->getPointeeType(); 12222 if (!PointeeType->isIncompleteType() && 12223 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12224 // OK, we will inline operations on this object. 12225 return Success(1, E); 12226 } 12227 } 12228 } 12229 12230 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12231 Success(0, E) : Error(E); 12232 } 12233 case Builtin::BI__builtin_add_overflow: 12234 case Builtin::BI__builtin_sub_overflow: 12235 case Builtin::BI__builtin_mul_overflow: 12236 case Builtin::BI__builtin_sadd_overflow: 12237 case Builtin::BI__builtin_uadd_overflow: 12238 case Builtin::BI__builtin_uaddl_overflow: 12239 case Builtin::BI__builtin_uaddll_overflow: 12240 case Builtin::BI__builtin_usub_overflow: 12241 case Builtin::BI__builtin_usubl_overflow: 12242 case Builtin::BI__builtin_usubll_overflow: 12243 case Builtin::BI__builtin_umul_overflow: 12244 case Builtin::BI__builtin_umull_overflow: 12245 case Builtin::BI__builtin_umulll_overflow: 12246 case Builtin::BI__builtin_saddl_overflow: 12247 case Builtin::BI__builtin_saddll_overflow: 12248 case Builtin::BI__builtin_ssub_overflow: 12249 case Builtin::BI__builtin_ssubl_overflow: 12250 case Builtin::BI__builtin_ssubll_overflow: 12251 case Builtin::BI__builtin_smul_overflow: 12252 case Builtin::BI__builtin_smull_overflow: 12253 case Builtin::BI__builtin_smulll_overflow: { 12254 LValue ResultLValue; 12255 APSInt LHS, RHS; 12256 12257 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12258 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12259 !EvaluateInteger(E->getArg(1), RHS, Info) || 12260 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12261 return false; 12262 12263 APSInt Result; 12264 bool DidOverflow = false; 12265 12266 // If the types don't have to match, enlarge all 3 to the largest of them. 12267 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12268 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12269 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12270 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12271 ResultType->isSignedIntegerOrEnumerationType(); 12272 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12273 ResultType->isSignedIntegerOrEnumerationType(); 12274 uint64_t LHSSize = LHS.getBitWidth(); 12275 uint64_t RHSSize = RHS.getBitWidth(); 12276 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12277 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12278 12279 // Add an additional bit if the signedness isn't uniformly agreed to. We 12280 // could do this ONLY if there is a signed and an unsigned that both have 12281 // MaxBits, but the code to check that is pretty nasty. The issue will be 12282 // caught in the shrink-to-result later anyway. 12283 if (IsSigned && !AllSigned) 12284 ++MaxBits; 12285 12286 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12287 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12288 Result = APSInt(MaxBits, !IsSigned); 12289 } 12290 12291 // Find largest int. 12292 switch (BuiltinOp) { 12293 default: 12294 llvm_unreachable("Invalid value for BuiltinOp"); 12295 case Builtin::BI__builtin_add_overflow: 12296 case Builtin::BI__builtin_sadd_overflow: 12297 case Builtin::BI__builtin_saddl_overflow: 12298 case Builtin::BI__builtin_saddll_overflow: 12299 case Builtin::BI__builtin_uadd_overflow: 12300 case Builtin::BI__builtin_uaddl_overflow: 12301 case Builtin::BI__builtin_uaddll_overflow: 12302 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12303 : LHS.uadd_ov(RHS, DidOverflow); 12304 break; 12305 case Builtin::BI__builtin_sub_overflow: 12306 case Builtin::BI__builtin_ssub_overflow: 12307 case Builtin::BI__builtin_ssubl_overflow: 12308 case Builtin::BI__builtin_ssubll_overflow: 12309 case Builtin::BI__builtin_usub_overflow: 12310 case Builtin::BI__builtin_usubl_overflow: 12311 case Builtin::BI__builtin_usubll_overflow: 12312 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12313 : LHS.usub_ov(RHS, DidOverflow); 12314 break; 12315 case Builtin::BI__builtin_mul_overflow: 12316 case Builtin::BI__builtin_smul_overflow: 12317 case Builtin::BI__builtin_smull_overflow: 12318 case Builtin::BI__builtin_smulll_overflow: 12319 case Builtin::BI__builtin_umul_overflow: 12320 case Builtin::BI__builtin_umull_overflow: 12321 case Builtin::BI__builtin_umulll_overflow: 12322 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12323 : LHS.umul_ov(RHS, DidOverflow); 12324 break; 12325 } 12326 12327 // In the case where multiple sizes are allowed, truncate and see if 12328 // the values are the same. 12329 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12330 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12331 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12332 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12333 // since it will give us the behavior of a TruncOrSelf in the case where 12334 // its parameter <= its size. We previously set Result to be at least the 12335 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12336 // will work exactly like TruncOrSelf. 12337 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12338 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12339 12340 if (!APSInt::isSameValue(Temp, Result)) 12341 DidOverflow = true; 12342 Result = Temp; 12343 } 12344 12345 APValue APV{Result}; 12346 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12347 return false; 12348 return Success(DidOverflow, E); 12349 } 12350 } 12351 } 12352 12353 /// Determine whether this is a pointer past the end of the complete 12354 /// object referred to by the lvalue. 12355 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12356 const LValue &LV) { 12357 // A null pointer can be viewed as being "past the end" but we don't 12358 // choose to look at it that way here. 12359 if (!LV.getLValueBase()) 12360 return false; 12361 12362 // If the designator is valid and refers to a subobject, we're not pointing 12363 // past the end. 12364 if (!LV.getLValueDesignator().Invalid && 12365 !LV.getLValueDesignator().isOnePastTheEnd()) 12366 return false; 12367 12368 // A pointer to an incomplete type might be past-the-end if the type's size is 12369 // zero. We cannot tell because the type is incomplete. 12370 QualType Ty = getType(LV.getLValueBase()); 12371 if (Ty->isIncompleteType()) 12372 return true; 12373 12374 // We're a past-the-end pointer if we point to the byte after the object, 12375 // no matter what our type or path is. 12376 auto Size = Ctx.getTypeSizeInChars(Ty); 12377 return LV.getLValueOffset() == Size; 12378 } 12379 12380 namespace { 12381 12382 /// Data recursive integer evaluator of certain binary operators. 12383 /// 12384 /// We use a data recursive algorithm for binary operators so that we are able 12385 /// to handle extreme cases of chained binary operators without causing stack 12386 /// overflow. 12387 class DataRecursiveIntBinOpEvaluator { 12388 struct EvalResult { 12389 APValue Val; 12390 bool Failed; 12391 12392 EvalResult() : Failed(false) { } 12393 12394 void swap(EvalResult &RHS) { 12395 Val.swap(RHS.Val); 12396 Failed = RHS.Failed; 12397 RHS.Failed = false; 12398 } 12399 }; 12400 12401 struct Job { 12402 const Expr *E; 12403 EvalResult LHSResult; // meaningful only for binary operator expression. 12404 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12405 12406 Job() = default; 12407 Job(Job &&) = default; 12408 12409 void startSpeculativeEval(EvalInfo &Info) { 12410 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12411 } 12412 12413 private: 12414 SpeculativeEvaluationRAII SpecEvalRAII; 12415 }; 12416 12417 SmallVector<Job, 16> Queue; 12418 12419 IntExprEvaluator &IntEval; 12420 EvalInfo &Info; 12421 APValue &FinalResult; 12422 12423 public: 12424 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12425 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12426 12427 /// True if \param E is a binary operator that we are going to handle 12428 /// data recursively. 12429 /// We handle binary operators that are comma, logical, or that have operands 12430 /// with integral or enumeration type. 12431 static bool shouldEnqueue(const BinaryOperator *E) { 12432 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12433 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && 12434 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12435 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12436 } 12437 12438 bool Traverse(const BinaryOperator *E) { 12439 enqueue(E); 12440 EvalResult PrevResult; 12441 while (!Queue.empty()) 12442 process(PrevResult); 12443 12444 if (PrevResult.Failed) return false; 12445 12446 FinalResult.swap(PrevResult.Val); 12447 return true; 12448 } 12449 12450 private: 12451 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12452 return IntEval.Success(Value, E, Result); 12453 } 12454 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12455 return IntEval.Success(Value, E, Result); 12456 } 12457 bool Error(const Expr *E) { 12458 return IntEval.Error(E); 12459 } 12460 bool Error(const Expr *E, diag::kind D) { 12461 return IntEval.Error(E, D); 12462 } 12463 12464 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12465 return Info.CCEDiag(E, D); 12466 } 12467 12468 // Returns true if visiting the RHS is necessary, false otherwise. 12469 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12470 bool &SuppressRHSDiags); 12471 12472 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12473 const BinaryOperator *E, APValue &Result); 12474 12475 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12476 Result.Failed = !Evaluate(Result.Val, Info, E); 12477 if (Result.Failed) 12478 Result.Val = APValue(); 12479 } 12480 12481 void process(EvalResult &Result); 12482 12483 void enqueue(const Expr *E) { 12484 E = E->IgnoreParens(); 12485 Queue.resize(Queue.size()+1); 12486 Queue.back().E = E; 12487 Queue.back().Kind = Job::AnyExprKind; 12488 } 12489 }; 12490 12491 } 12492 12493 bool DataRecursiveIntBinOpEvaluator:: 12494 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12495 bool &SuppressRHSDiags) { 12496 if (E->getOpcode() == BO_Comma) { 12497 // Ignore LHS but note if we could not evaluate it. 12498 if (LHSResult.Failed) 12499 return Info.noteSideEffect(); 12500 return true; 12501 } 12502 12503 if (E->isLogicalOp()) { 12504 bool LHSAsBool; 12505 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12506 // We were able to evaluate the LHS, see if we can get away with not 12507 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12508 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12509 Success(LHSAsBool, E, LHSResult.Val); 12510 return false; // Ignore RHS 12511 } 12512 } else { 12513 LHSResult.Failed = true; 12514 12515 // Since we weren't able to evaluate the left hand side, it 12516 // might have had side effects. 12517 if (!Info.noteSideEffect()) 12518 return false; 12519 12520 // We can't evaluate the LHS; however, sometimes the result 12521 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12522 // Don't ignore RHS and suppress diagnostics from this arm. 12523 SuppressRHSDiags = true; 12524 } 12525 12526 return true; 12527 } 12528 12529 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12530 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12531 12532 if (LHSResult.Failed && !Info.noteFailure()) 12533 return false; // Ignore RHS; 12534 12535 return true; 12536 } 12537 12538 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12539 bool IsSub) { 12540 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12541 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12542 // offsets. 12543 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12544 CharUnits &Offset = LVal.getLValueOffset(); 12545 uint64_t Offset64 = Offset.getQuantity(); 12546 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12547 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12548 : Offset64 + Index64); 12549 } 12550 12551 bool DataRecursiveIntBinOpEvaluator:: 12552 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12553 const BinaryOperator *E, APValue &Result) { 12554 if (E->getOpcode() == BO_Comma) { 12555 if (RHSResult.Failed) 12556 return false; 12557 Result = RHSResult.Val; 12558 return true; 12559 } 12560 12561 if (E->isLogicalOp()) { 12562 bool lhsResult, rhsResult; 12563 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12564 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12565 12566 if (LHSIsOK) { 12567 if (RHSIsOK) { 12568 if (E->getOpcode() == BO_LOr) 12569 return Success(lhsResult || rhsResult, E, Result); 12570 else 12571 return Success(lhsResult && rhsResult, E, Result); 12572 } 12573 } else { 12574 if (RHSIsOK) { 12575 // We can't evaluate the LHS; however, sometimes the result 12576 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12577 if (rhsResult == (E->getOpcode() == BO_LOr)) 12578 return Success(rhsResult, E, Result); 12579 } 12580 } 12581 12582 return false; 12583 } 12584 12585 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12586 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12587 12588 if (LHSResult.Failed || RHSResult.Failed) 12589 return false; 12590 12591 const APValue &LHSVal = LHSResult.Val; 12592 const APValue &RHSVal = RHSResult.Val; 12593 12594 // Handle cases like (unsigned long)&a + 4. 12595 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12596 Result = LHSVal; 12597 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12598 return true; 12599 } 12600 12601 // Handle cases like 4 + (unsigned long)&a 12602 if (E->getOpcode() == BO_Add && 12603 RHSVal.isLValue() && LHSVal.isInt()) { 12604 Result = RHSVal; 12605 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12606 return true; 12607 } 12608 12609 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12610 // Handle (intptr_t)&&A - (intptr_t)&&B. 12611 if (!LHSVal.getLValueOffset().isZero() || 12612 !RHSVal.getLValueOffset().isZero()) 12613 return false; 12614 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12615 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12616 if (!LHSExpr || !RHSExpr) 12617 return false; 12618 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12619 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12620 if (!LHSAddrExpr || !RHSAddrExpr) 12621 return false; 12622 // Make sure both labels come from the same function. 12623 if (LHSAddrExpr->getLabel()->getDeclContext() != 12624 RHSAddrExpr->getLabel()->getDeclContext()) 12625 return false; 12626 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12627 return true; 12628 } 12629 12630 // All the remaining cases expect both operands to be an integer 12631 if (!LHSVal.isInt() || !RHSVal.isInt()) 12632 return Error(E); 12633 12634 // Set up the width and signedness manually, in case it can't be deduced 12635 // from the operation we're performing. 12636 // FIXME: Don't do this in the cases where we can deduce it. 12637 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12638 E->getType()->isUnsignedIntegerOrEnumerationType()); 12639 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12640 RHSVal.getInt(), Value)) 12641 return false; 12642 return Success(Value, E, Result); 12643 } 12644 12645 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12646 Job &job = Queue.back(); 12647 12648 switch (job.Kind) { 12649 case Job::AnyExprKind: { 12650 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12651 if (shouldEnqueue(Bop)) { 12652 job.Kind = Job::BinOpKind; 12653 enqueue(Bop->getLHS()); 12654 return; 12655 } 12656 } 12657 12658 EvaluateExpr(job.E, Result); 12659 Queue.pop_back(); 12660 return; 12661 } 12662 12663 case Job::BinOpKind: { 12664 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12665 bool SuppressRHSDiags = false; 12666 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12667 Queue.pop_back(); 12668 return; 12669 } 12670 if (SuppressRHSDiags) 12671 job.startSpeculativeEval(Info); 12672 job.LHSResult.swap(Result); 12673 job.Kind = Job::BinOpVisitedLHSKind; 12674 enqueue(Bop->getRHS()); 12675 return; 12676 } 12677 12678 case Job::BinOpVisitedLHSKind: { 12679 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12680 EvalResult RHS; 12681 RHS.swap(Result); 12682 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12683 Queue.pop_back(); 12684 return; 12685 } 12686 } 12687 12688 llvm_unreachable("Invalid Job::Kind!"); 12689 } 12690 12691 namespace { 12692 enum class CmpResult { 12693 Unequal, 12694 Less, 12695 Equal, 12696 Greater, 12697 Unordered, 12698 }; 12699 } 12700 12701 template <class SuccessCB, class AfterCB> 12702 static bool 12703 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12704 SuccessCB &&Success, AfterCB &&DoAfter) { 12705 assert(!E->isValueDependent()); 12706 assert(E->isComparisonOp() && "expected comparison operator"); 12707 assert((E->getOpcode() == BO_Cmp || 12708 E->getType()->isIntegralOrEnumerationType()) && 12709 "unsupported binary expression evaluation"); 12710 auto Error = [&](const Expr *E) { 12711 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12712 return false; 12713 }; 12714 12715 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12716 bool IsEquality = E->isEqualityOp(); 12717 12718 QualType LHSTy = E->getLHS()->getType(); 12719 QualType RHSTy = E->getRHS()->getType(); 12720 12721 if (LHSTy->isIntegralOrEnumerationType() && 12722 RHSTy->isIntegralOrEnumerationType()) { 12723 APSInt LHS, RHS; 12724 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12725 if (!LHSOK && !Info.noteFailure()) 12726 return false; 12727 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12728 return false; 12729 if (LHS < RHS) 12730 return Success(CmpResult::Less, E); 12731 if (LHS > RHS) 12732 return Success(CmpResult::Greater, E); 12733 return Success(CmpResult::Equal, E); 12734 } 12735 12736 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12737 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12738 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12739 12740 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12741 if (!LHSOK && !Info.noteFailure()) 12742 return false; 12743 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12744 return false; 12745 if (LHSFX < RHSFX) 12746 return Success(CmpResult::Less, E); 12747 if (LHSFX > RHSFX) 12748 return Success(CmpResult::Greater, E); 12749 return Success(CmpResult::Equal, E); 12750 } 12751 12752 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12753 ComplexValue LHS, RHS; 12754 bool LHSOK; 12755 if (E->isAssignmentOp()) { 12756 LValue LV; 12757 EvaluateLValue(E->getLHS(), LV, Info); 12758 LHSOK = false; 12759 } else if (LHSTy->isRealFloatingType()) { 12760 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12761 if (LHSOK) { 12762 LHS.makeComplexFloat(); 12763 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12764 } 12765 } else { 12766 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12767 } 12768 if (!LHSOK && !Info.noteFailure()) 12769 return false; 12770 12771 if (E->getRHS()->getType()->isRealFloatingType()) { 12772 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12773 return false; 12774 RHS.makeComplexFloat(); 12775 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12776 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12777 return false; 12778 12779 if (LHS.isComplexFloat()) { 12780 APFloat::cmpResult CR_r = 12781 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12782 APFloat::cmpResult CR_i = 12783 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12784 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12785 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12786 } else { 12787 assert(IsEquality && "invalid complex comparison"); 12788 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12789 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12790 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12791 } 12792 } 12793 12794 if (LHSTy->isRealFloatingType() && 12795 RHSTy->isRealFloatingType()) { 12796 APFloat RHS(0.0), LHS(0.0); 12797 12798 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12799 if (!LHSOK && !Info.noteFailure()) 12800 return false; 12801 12802 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12803 return false; 12804 12805 assert(E->isComparisonOp() && "Invalid binary operator!"); 12806 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12807 if (!Info.InConstantContext && 12808 APFloatCmpResult == APFloat::cmpUnordered && 12809 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12810 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12811 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12812 return false; 12813 } 12814 auto GetCmpRes = [&]() { 12815 switch (APFloatCmpResult) { 12816 case APFloat::cmpEqual: 12817 return CmpResult::Equal; 12818 case APFloat::cmpLessThan: 12819 return CmpResult::Less; 12820 case APFloat::cmpGreaterThan: 12821 return CmpResult::Greater; 12822 case APFloat::cmpUnordered: 12823 return CmpResult::Unordered; 12824 } 12825 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12826 }; 12827 return Success(GetCmpRes(), E); 12828 } 12829 12830 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12831 LValue LHSValue, RHSValue; 12832 12833 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12834 if (!LHSOK && !Info.noteFailure()) 12835 return false; 12836 12837 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12838 return false; 12839 12840 // Reject differing bases from the normal codepath; we special-case 12841 // comparisons to null. 12842 if (!HasSameBase(LHSValue, RHSValue)) { 12843 // Inequalities and subtractions between unrelated pointers have 12844 // unspecified or undefined behavior. 12845 if (!IsEquality) { 12846 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12847 return false; 12848 } 12849 // A constant address may compare equal to the address of a symbol. 12850 // The one exception is that address of an object cannot compare equal 12851 // to a null pointer constant. 12852 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12853 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12854 return Error(E); 12855 // It's implementation-defined whether distinct literals will have 12856 // distinct addresses. In clang, the result of such a comparison is 12857 // unspecified, so it is not a constant expression. However, we do know 12858 // that the address of a literal will be non-null. 12859 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12860 LHSValue.Base && RHSValue.Base) 12861 return Error(E); 12862 // We can't tell whether weak symbols will end up pointing to the same 12863 // object. 12864 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12865 return Error(E); 12866 // We can't compare the address of the start of one object with the 12867 // past-the-end address of another object, per C++ DR1652. 12868 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12869 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12870 (RHSValue.Base && RHSValue.Offset.isZero() && 12871 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12872 return Error(E); 12873 // We can't tell whether an object is at the same address as another 12874 // zero sized object. 12875 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12876 (LHSValue.Base && isZeroSized(RHSValue))) 12877 return Error(E); 12878 return Success(CmpResult::Unequal, E); 12879 } 12880 12881 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12882 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12883 12884 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12885 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12886 12887 // C++11 [expr.rel]p3: 12888 // Pointers to void (after pointer conversions) can be compared, with a 12889 // result defined as follows: If both pointers represent the same 12890 // address or are both the null pointer value, the result is true if the 12891 // operator is <= or >= and false otherwise; otherwise the result is 12892 // unspecified. 12893 // We interpret this as applying to pointers to *cv* void. 12894 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12895 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12896 12897 // C++11 [expr.rel]p2: 12898 // - If two pointers point to non-static data members of the same object, 12899 // or to subobjects or array elements fo such members, recursively, the 12900 // pointer to the later declared member compares greater provided the 12901 // two members have the same access control and provided their class is 12902 // not a union. 12903 // [...] 12904 // - Otherwise pointer comparisons are unspecified. 12905 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12906 bool WasArrayIndex; 12907 unsigned Mismatch = FindDesignatorMismatch( 12908 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12909 // At the point where the designators diverge, the comparison has a 12910 // specified value if: 12911 // - we are comparing array indices 12912 // - we are comparing fields of a union, or fields with the same access 12913 // Otherwise, the result is unspecified and thus the comparison is not a 12914 // constant expression. 12915 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12916 Mismatch < RHSDesignator.Entries.size()) { 12917 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12918 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12919 if (!LF && !RF) 12920 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12921 else if (!LF) 12922 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12923 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12924 << RF->getParent() << RF; 12925 else if (!RF) 12926 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12927 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12928 << LF->getParent() << LF; 12929 else if (!LF->getParent()->isUnion() && 12930 LF->getAccess() != RF->getAccess()) 12931 Info.CCEDiag(E, 12932 diag::note_constexpr_pointer_comparison_differing_access) 12933 << LF << LF->getAccess() << RF << RF->getAccess() 12934 << LF->getParent(); 12935 } 12936 } 12937 12938 // The comparison here must be unsigned, and performed with the same 12939 // width as the pointer. 12940 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12941 uint64_t CompareLHS = LHSOffset.getQuantity(); 12942 uint64_t CompareRHS = RHSOffset.getQuantity(); 12943 assert(PtrSize <= 64 && "Unexpected pointer width"); 12944 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12945 CompareLHS &= Mask; 12946 CompareRHS &= Mask; 12947 12948 // If there is a base and this is a relational operator, we can only 12949 // compare pointers within the object in question; otherwise, the result 12950 // depends on where the object is located in memory. 12951 if (!LHSValue.Base.isNull() && IsRelational) { 12952 QualType BaseTy = getType(LHSValue.Base); 12953 if (BaseTy->isIncompleteType()) 12954 return Error(E); 12955 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12956 uint64_t OffsetLimit = Size.getQuantity(); 12957 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12958 return Error(E); 12959 } 12960 12961 if (CompareLHS < CompareRHS) 12962 return Success(CmpResult::Less, E); 12963 if (CompareLHS > CompareRHS) 12964 return Success(CmpResult::Greater, E); 12965 return Success(CmpResult::Equal, E); 12966 } 12967 12968 if (LHSTy->isMemberPointerType()) { 12969 assert(IsEquality && "unexpected member pointer operation"); 12970 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12971 12972 MemberPtr LHSValue, RHSValue; 12973 12974 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12975 if (!LHSOK && !Info.noteFailure()) 12976 return false; 12977 12978 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12979 return false; 12980 12981 // C++11 [expr.eq]p2: 12982 // If both operands are null, they compare equal. Otherwise if only one is 12983 // null, they compare unequal. 12984 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12985 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12986 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12987 } 12988 12989 // Otherwise if either is a pointer to a virtual member function, the 12990 // result is unspecified. 12991 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12992 if (MD->isVirtual()) 12993 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12994 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12995 if (MD->isVirtual()) 12996 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12997 12998 // Otherwise they compare equal if and only if they would refer to the 12999 // same member of the same most derived object or the same subobject if 13000 // they were dereferenced with a hypothetical object of the associated 13001 // class type. 13002 bool Equal = LHSValue == RHSValue; 13003 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 13004 } 13005 13006 if (LHSTy->isNullPtrType()) { 13007 assert(E->isComparisonOp() && "unexpected nullptr operation"); 13008 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 13009 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 13010 // are compared, the result is true of the operator is <=, >= or ==, and 13011 // false otherwise. 13012 return Success(CmpResult::Equal, E); 13013 } 13014 13015 return DoAfter(); 13016 } 13017 13018 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 13019 if (!CheckLiteralType(Info, E)) 13020 return false; 13021 13022 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13023 ComparisonCategoryResult CCR; 13024 switch (CR) { 13025 case CmpResult::Unequal: 13026 llvm_unreachable("should never produce Unequal for three-way comparison"); 13027 case CmpResult::Less: 13028 CCR = ComparisonCategoryResult::Less; 13029 break; 13030 case CmpResult::Equal: 13031 CCR = ComparisonCategoryResult::Equal; 13032 break; 13033 case CmpResult::Greater: 13034 CCR = ComparisonCategoryResult::Greater; 13035 break; 13036 case CmpResult::Unordered: 13037 CCR = ComparisonCategoryResult::Unordered; 13038 break; 13039 } 13040 // Evaluation succeeded. Lookup the information for the comparison category 13041 // type and fetch the VarDecl for the result. 13042 const ComparisonCategoryInfo &CmpInfo = 13043 Info.Ctx.CompCategories.getInfoForType(E->getType()); 13044 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 13045 // Check and evaluate the result as a constant expression. 13046 LValue LV; 13047 LV.set(VD); 13048 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13049 return false; 13050 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 13051 ConstantExprKind::Normal); 13052 }; 13053 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13054 return ExprEvaluatorBaseTy::VisitBinCmp(E); 13055 }); 13056 } 13057 13058 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13059 // We don't support assignment in C. C++ assignments don't get here because 13060 // assignment is an lvalue in C++. 13061 if (E->isAssignmentOp()) { 13062 Error(E); 13063 if (!Info.noteFailure()) 13064 return false; 13065 } 13066 13067 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 13068 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 13069 13070 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 13071 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 13072 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 13073 13074 if (E->isComparisonOp()) { 13075 // Evaluate builtin binary comparisons by evaluating them as three-way 13076 // comparisons and then translating the result. 13077 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 13078 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 13079 "should only produce Unequal for equality comparisons"); 13080 bool IsEqual = CR == CmpResult::Equal, 13081 IsLess = CR == CmpResult::Less, 13082 IsGreater = CR == CmpResult::Greater; 13083 auto Op = E->getOpcode(); 13084 switch (Op) { 13085 default: 13086 llvm_unreachable("unsupported binary operator"); 13087 case BO_EQ: 13088 case BO_NE: 13089 return Success(IsEqual == (Op == BO_EQ), E); 13090 case BO_LT: 13091 return Success(IsLess, E); 13092 case BO_GT: 13093 return Success(IsGreater, E); 13094 case BO_LE: 13095 return Success(IsEqual || IsLess, E); 13096 case BO_GE: 13097 return Success(IsEqual || IsGreater, E); 13098 } 13099 }; 13100 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 13101 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13102 }); 13103 } 13104 13105 QualType LHSTy = E->getLHS()->getType(); 13106 QualType RHSTy = E->getRHS()->getType(); 13107 13108 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 13109 E->getOpcode() == BO_Sub) { 13110 LValue LHSValue, RHSValue; 13111 13112 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 13113 if (!LHSOK && !Info.noteFailure()) 13114 return false; 13115 13116 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 13117 return false; 13118 13119 // Reject differing bases from the normal codepath; we special-case 13120 // comparisons to null. 13121 if (!HasSameBase(LHSValue, RHSValue)) { 13122 // Handle &&A - &&B. 13123 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 13124 return Error(E); 13125 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 13126 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 13127 if (!LHSExpr || !RHSExpr) 13128 return Error(E); 13129 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 13130 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 13131 if (!LHSAddrExpr || !RHSAddrExpr) 13132 return Error(E); 13133 // Make sure both labels come from the same function. 13134 if (LHSAddrExpr->getLabel()->getDeclContext() != 13135 RHSAddrExpr->getLabel()->getDeclContext()) 13136 return Error(E); 13137 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 13138 } 13139 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 13140 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 13141 13142 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 13143 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 13144 13145 // C++11 [expr.add]p6: 13146 // Unless both pointers point to elements of the same array object, or 13147 // one past the last element of the array object, the behavior is 13148 // undefined. 13149 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 13150 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 13151 RHSDesignator)) 13152 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 13153 13154 QualType Type = E->getLHS()->getType(); 13155 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 13156 13157 CharUnits ElementSize; 13158 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 13159 return false; 13160 13161 // As an extension, a type may have zero size (empty struct or union in 13162 // C, array of zero length). Pointer subtraction in such cases has 13163 // undefined behavior, so is not constant. 13164 if (ElementSize.isZero()) { 13165 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 13166 << ElementType; 13167 return false; 13168 } 13169 13170 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 13171 // and produce incorrect results when it overflows. Such behavior 13172 // appears to be non-conforming, but is common, so perhaps we should 13173 // assume the standard intended for such cases to be undefined behavior 13174 // and check for them. 13175 13176 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 13177 // overflow in the final conversion to ptrdiff_t. 13178 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 13179 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 13180 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 13181 false); 13182 APSInt TrueResult = (LHS - RHS) / ElemSize; 13183 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 13184 13185 if (Result.extend(65) != TrueResult && 13186 !HandleOverflow(Info, E, TrueResult, E->getType())) 13187 return false; 13188 return Success(Result, E); 13189 } 13190 13191 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13192 } 13193 13194 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 13195 /// a result as the expression's type. 13196 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13197 const UnaryExprOrTypeTraitExpr *E) { 13198 switch(E->getKind()) { 13199 case UETT_PreferredAlignOf: 13200 case UETT_AlignOf: { 13201 if (E->isArgumentType()) 13202 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13203 E); 13204 else 13205 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13206 E); 13207 } 13208 13209 case UETT_VecStep: { 13210 QualType Ty = E->getTypeOfArgument(); 13211 13212 if (Ty->isVectorType()) { 13213 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13214 13215 // The vec_step built-in functions that take a 3-component 13216 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13217 if (n == 3) 13218 n = 4; 13219 13220 return Success(n, E); 13221 } else 13222 return Success(1, E); 13223 } 13224 13225 case UETT_SizeOf: { 13226 QualType SrcTy = E->getTypeOfArgument(); 13227 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13228 // the result is the size of the referenced type." 13229 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13230 SrcTy = Ref->getPointeeType(); 13231 13232 CharUnits Sizeof; 13233 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13234 return false; 13235 return Success(Sizeof, E); 13236 } 13237 case UETT_OpenMPRequiredSimdAlign: 13238 assert(E->isArgumentType()); 13239 return Success( 13240 Info.Ctx.toCharUnitsFromBits( 13241 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13242 .getQuantity(), 13243 E); 13244 } 13245 13246 llvm_unreachable("unknown expr/type trait"); 13247 } 13248 13249 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13250 CharUnits Result; 13251 unsigned n = OOE->getNumComponents(); 13252 if (n == 0) 13253 return Error(OOE); 13254 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13255 for (unsigned i = 0; i != n; ++i) { 13256 OffsetOfNode ON = OOE->getComponent(i); 13257 switch (ON.getKind()) { 13258 case OffsetOfNode::Array: { 13259 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13260 APSInt IdxResult; 13261 if (!EvaluateInteger(Idx, IdxResult, Info)) 13262 return false; 13263 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13264 if (!AT) 13265 return Error(OOE); 13266 CurrentType = AT->getElementType(); 13267 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13268 Result += IdxResult.getSExtValue() * ElementSize; 13269 break; 13270 } 13271 13272 case OffsetOfNode::Field: { 13273 FieldDecl *MemberDecl = ON.getField(); 13274 const RecordType *RT = CurrentType->getAs<RecordType>(); 13275 if (!RT) 13276 return Error(OOE); 13277 RecordDecl *RD = RT->getDecl(); 13278 if (RD->isInvalidDecl()) return false; 13279 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13280 unsigned i = MemberDecl->getFieldIndex(); 13281 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13282 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13283 CurrentType = MemberDecl->getType().getNonReferenceType(); 13284 break; 13285 } 13286 13287 case OffsetOfNode::Identifier: 13288 llvm_unreachable("dependent __builtin_offsetof"); 13289 13290 case OffsetOfNode::Base: { 13291 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13292 if (BaseSpec->isVirtual()) 13293 return Error(OOE); 13294 13295 // Find the layout of the class whose base we are looking into. 13296 const RecordType *RT = CurrentType->getAs<RecordType>(); 13297 if (!RT) 13298 return Error(OOE); 13299 RecordDecl *RD = RT->getDecl(); 13300 if (RD->isInvalidDecl()) return false; 13301 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13302 13303 // Find the base class itself. 13304 CurrentType = BaseSpec->getType(); 13305 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13306 if (!BaseRT) 13307 return Error(OOE); 13308 13309 // Add the offset to the base. 13310 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13311 break; 13312 } 13313 } 13314 } 13315 return Success(Result, OOE); 13316 } 13317 13318 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13319 switch (E->getOpcode()) { 13320 default: 13321 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13322 // See C99 6.6p3. 13323 return Error(E); 13324 case UO_Extension: 13325 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13326 // If so, we could clear the diagnostic ID. 13327 return Visit(E->getSubExpr()); 13328 case UO_Plus: 13329 // The result is just the value. 13330 return Visit(E->getSubExpr()); 13331 case UO_Minus: { 13332 if (!Visit(E->getSubExpr())) 13333 return false; 13334 if (!Result.isInt()) return Error(E); 13335 const APSInt &Value = Result.getInt(); 13336 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13337 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13338 E->getType())) 13339 return false; 13340 return Success(-Value, E); 13341 } 13342 case UO_Not: { 13343 if (!Visit(E->getSubExpr())) 13344 return false; 13345 if (!Result.isInt()) return Error(E); 13346 return Success(~Result.getInt(), E); 13347 } 13348 case UO_LNot: { 13349 bool bres; 13350 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13351 return false; 13352 return Success(!bres, E); 13353 } 13354 } 13355 } 13356 13357 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13358 /// result type is integer. 13359 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13360 const Expr *SubExpr = E->getSubExpr(); 13361 QualType DestType = E->getType(); 13362 QualType SrcType = SubExpr->getType(); 13363 13364 switch (E->getCastKind()) { 13365 case CK_BaseToDerived: 13366 case CK_DerivedToBase: 13367 case CK_UncheckedDerivedToBase: 13368 case CK_Dynamic: 13369 case CK_ToUnion: 13370 case CK_ArrayToPointerDecay: 13371 case CK_FunctionToPointerDecay: 13372 case CK_NullToPointer: 13373 case CK_NullToMemberPointer: 13374 case CK_BaseToDerivedMemberPointer: 13375 case CK_DerivedToBaseMemberPointer: 13376 case CK_ReinterpretMemberPointer: 13377 case CK_ConstructorConversion: 13378 case CK_IntegralToPointer: 13379 case CK_ToVoid: 13380 case CK_VectorSplat: 13381 case CK_IntegralToFloating: 13382 case CK_FloatingCast: 13383 case CK_CPointerToObjCPointerCast: 13384 case CK_BlockPointerToObjCPointerCast: 13385 case CK_AnyPointerToBlockPointerCast: 13386 case CK_ObjCObjectLValueCast: 13387 case CK_FloatingRealToComplex: 13388 case CK_FloatingComplexToReal: 13389 case CK_FloatingComplexCast: 13390 case CK_FloatingComplexToIntegralComplex: 13391 case CK_IntegralRealToComplex: 13392 case CK_IntegralComplexCast: 13393 case CK_IntegralComplexToFloatingComplex: 13394 case CK_BuiltinFnToFnPtr: 13395 case CK_ZeroToOCLOpaqueType: 13396 case CK_NonAtomicToAtomic: 13397 case CK_AddressSpaceConversion: 13398 case CK_IntToOCLSampler: 13399 case CK_FloatingToFixedPoint: 13400 case CK_FixedPointToFloating: 13401 case CK_FixedPointCast: 13402 case CK_IntegralToFixedPoint: 13403 case CK_MatrixCast: 13404 llvm_unreachable("invalid cast kind for integral value"); 13405 13406 case CK_BitCast: 13407 case CK_Dependent: 13408 case CK_LValueBitCast: 13409 case CK_ARCProduceObject: 13410 case CK_ARCConsumeObject: 13411 case CK_ARCReclaimReturnedObject: 13412 case CK_ARCExtendBlockObject: 13413 case CK_CopyAndAutoreleaseBlockObject: 13414 return Error(E); 13415 13416 case CK_UserDefinedConversion: 13417 case CK_LValueToRValue: 13418 case CK_AtomicToNonAtomic: 13419 case CK_NoOp: 13420 case CK_LValueToRValueBitCast: 13421 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13422 13423 case CK_MemberPointerToBoolean: 13424 case CK_PointerToBoolean: 13425 case CK_IntegralToBoolean: 13426 case CK_FloatingToBoolean: 13427 case CK_BooleanToSignedIntegral: 13428 case CK_FloatingComplexToBoolean: 13429 case CK_IntegralComplexToBoolean: { 13430 bool BoolResult; 13431 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13432 return false; 13433 uint64_t IntResult = BoolResult; 13434 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13435 IntResult = (uint64_t)-1; 13436 return Success(IntResult, E); 13437 } 13438 13439 case CK_FixedPointToIntegral: { 13440 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13441 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13442 return false; 13443 bool Overflowed; 13444 llvm::APSInt Result = Src.convertToInt( 13445 Info.Ctx.getIntWidth(DestType), 13446 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13447 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13448 return false; 13449 return Success(Result, E); 13450 } 13451 13452 case CK_FixedPointToBoolean: { 13453 // Unsigned padding does not affect this. 13454 APValue Val; 13455 if (!Evaluate(Val, Info, SubExpr)) 13456 return false; 13457 return Success(Val.getFixedPoint().getBoolValue(), E); 13458 } 13459 13460 case CK_IntegralCast: { 13461 if (!Visit(SubExpr)) 13462 return false; 13463 13464 if (!Result.isInt()) { 13465 // Allow casts of address-of-label differences if they are no-ops 13466 // or narrowing. (The narrowing case isn't actually guaranteed to 13467 // be constant-evaluatable except in some narrow cases which are hard 13468 // to detect here. We let it through on the assumption the user knows 13469 // what they are doing.) 13470 if (Result.isAddrLabelDiff()) 13471 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13472 // Only allow casts of lvalues if they are lossless. 13473 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13474 } 13475 13476 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13477 Result.getInt()), E); 13478 } 13479 13480 case CK_PointerToIntegral: { 13481 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13482 13483 LValue LV; 13484 if (!EvaluatePointer(SubExpr, LV, Info)) 13485 return false; 13486 13487 if (LV.getLValueBase()) { 13488 // Only allow based lvalue casts if they are lossless. 13489 // FIXME: Allow a larger integer size than the pointer size, and allow 13490 // narrowing back down to pointer width in subsequent integral casts. 13491 // FIXME: Check integer type's active bits, not its type size. 13492 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13493 return Error(E); 13494 13495 LV.Designator.setInvalid(); 13496 LV.moveInto(Result); 13497 return true; 13498 } 13499 13500 APSInt AsInt; 13501 APValue V; 13502 LV.moveInto(V); 13503 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13504 llvm_unreachable("Can't cast this!"); 13505 13506 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13507 } 13508 13509 case CK_IntegralComplexToReal: { 13510 ComplexValue C; 13511 if (!EvaluateComplex(SubExpr, C, Info)) 13512 return false; 13513 return Success(C.getComplexIntReal(), E); 13514 } 13515 13516 case CK_FloatingToIntegral: { 13517 APFloat F(0.0); 13518 if (!EvaluateFloat(SubExpr, F, Info)) 13519 return false; 13520 13521 APSInt Value; 13522 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13523 return false; 13524 return Success(Value, E); 13525 } 13526 } 13527 13528 llvm_unreachable("unknown cast resulting in integral value"); 13529 } 13530 13531 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13532 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13533 ComplexValue LV; 13534 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13535 return false; 13536 if (!LV.isComplexInt()) 13537 return Error(E); 13538 return Success(LV.getComplexIntReal(), E); 13539 } 13540 13541 return Visit(E->getSubExpr()); 13542 } 13543 13544 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13545 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13546 ComplexValue LV; 13547 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13548 return false; 13549 if (!LV.isComplexInt()) 13550 return Error(E); 13551 return Success(LV.getComplexIntImag(), E); 13552 } 13553 13554 VisitIgnoredValue(E->getSubExpr()); 13555 return Success(0, E); 13556 } 13557 13558 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13559 return Success(E->getPackLength(), E); 13560 } 13561 13562 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13563 return Success(E->getValue(), E); 13564 } 13565 13566 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13567 const ConceptSpecializationExpr *E) { 13568 return Success(E->isSatisfied(), E); 13569 } 13570 13571 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13572 return Success(E->isSatisfied(), E); 13573 } 13574 13575 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13576 switch (E->getOpcode()) { 13577 default: 13578 // Invalid unary operators 13579 return Error(E); 13580 case UO_Plus: 13581 // The result is just the value. 13582 return Visit(E->getSubExpr()); 13583 case UO_Minus: { 13584 if (!Visit(E->getSubExpr())) return false; 13585 if (!Result.isFixedPoint()) 13586 return Error(E); 13587 bool Overflowed; 13588 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13589 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13590 return false; 13591 return Success(Negated, E); 13592 } 13593 case UO_LNot: { 13594 bool bres; 13595 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13596 return false; 13597 return Success(!bres, E); 13598 } 13599 } 13600 } 13601 13602 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13603 const Expr *SubExpr = E->getSubExpr(); 13604 QualType DestType = E->getType(); 13605 assert(DestType->isFixedPointType() && 13606 "Expected destination type to be a fixed point type"); 13607 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13608 13609 switch (E->getCastKind()) { 13610 case CK_FixedPointCast: { 13611 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13612 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13613 return false; 13614 bool Overflowed; 13615 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13616 if (Overflowed) { 13617 if (Info.checkingForUndefinedBehavior()) 13618 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13619 diag::warn_fixedpoint_constant_overflow) 13620 << Result.toString() << E->getType(); 13621 if (!HandleOverflow(Info, E, Result, E->getType())) 13622 return false; 13623 } 13624 return Success(Result, E); 13625 } 13626 case CK_IntegralToFixedPoint: { 13627 APSInt Src; 13628 if (!EvaluateInteger(SubExpr, Src, Info)) 13629 return false; 13630 13631 bool Overflowed; 13632 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13633 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13634 13635 if (Overflowed) { 13636 if (Info.checkingForUndefinedBehavior()) 13637 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13638 diag::warn_fixedpoint_constant_overflow) 13639 << IntResult.toString() << E->getType(); 13640 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13641 return false; 13642 } 13643 13644 return Success(IntResult, E); 13645 } 13646 case CK_FloatingToFixedPoint: { 13647 APFloat Src(0.0); 13648 if (!EvaluateFloat(SubExpr, Src, Info)) 13649 return false; 13650 13651 bool Overflowed; 13652 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13653 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13654 13655 if (Overflowed) { 13656 if (Info.checkingForUndefinedBehavior()) 13657 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13658 diag::warn_fixedpoint_constant_overflow) 13659 << Result.toString() << E->getType(); 13660 if (!HandleOverflow(Info, E, Result, E->getType())) 13661 return false; 13662 } 13663 13664 return Success(Result, E); 13665 } 13666 case CK_NoOp: 13667 case CK_LValueToRValue: 13668 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13669 default: 13670 return Error(E); 13671 } 13672 } 13673 13674 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13675 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13676 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13677 13678 const Expr *LHS = E->getLHS(); 13679 const Expr *RHS = E->getRHS(); 13680 FixedPointSemantics ResultFXSema = 13681 Info.Ctx.getFixedPointSemantics(E->getType()); 13682 13683 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13684 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13685 return false; 13686 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13687 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13688 return false; 13689 13690 bool OpOverflow = false, ConversionOverflow = false; 13691 APFixedPoint Result(LHSFX.getSemantics()); 13692 switch (E->getOpcode()) { 13693 case BO_Add: { 13694 Result = LHSFX.add(RHSFX, &OpOverflow) 13695 .convert(ResultFXSema, &ConversionOverflow); 13696 break; 13697 } 13698 case BO_Sub: { 13699 Result = LHSFX.sub(RHSFX, &OpOverflow) 13700 .convert(ResultFXSema, &ConversionOverflow); 13701 break; 13702 } 13703 case BO_Mul: { 13704 Result = LHSFX.mul(RHSFX, &OpOverflow) 13705 .convert(ResultFXSema, &ConversionOverflow); 13706 break; 13707 } 13708 case BO_Div: { 13709 if (RHSFX.getValue() == 0) { 13710 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13711 return false; 13712 } 13713 Result = LHSFX.div(RHSFX, &OpOverflow) 13714 .convert(ResultFXSema, &ConversionOverflow); 13715 break; 13716 } 13717 case BO_Shl: 13718 case BO_Shr: { 13719 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13720 llvm::APSInt RHSVal = RHSFX.getValue(); 13721 13722 unsigned ShiftBW = 13723 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13724 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13725 // Embedded-C 4.1.6.2.2: 13726 // The right operand must be nonnegative and less than the total number 13727 // of (nonpadding) bits of the fixed-point operand ... 13728 if (RHSVal.isNegative()) 13729 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13730 else if (Amt != RHSVal) 13731 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13732 << RHSVal << E->getType() << ShiftBW; 13733 13734 if (E->getOpcode() == BO_Shl) 13735 Result = LHSFX.shl(Amt, &OpOverflow); 13736 else 13737 Result = LHSFX.shr(Amt, &OpOverflow); 13738 break; 13739 } 13740 default: 13741 return false; 13742 } 13743 if (OpOverflow || ConversionOverflow) { 13744 if (Info.checkingForUndefinedBehavior()) 13745 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13746 diag::warn_fixedpoint_constant_overflow) 13747 << Result.toString() << E->getType(); 13748 if (!HandleOverflow(Info, E, Result, E->getType())) 13749 return false; 13750 } 13751 return Success(Result, E); 13752 } 13753 13754 //===----------------------------------------------------------------------===// 13755 // Float Evaluation 13756 //===----------------------------------------------------------------------===// 13757 13758 namespace { 13759 class FloatExprEvaluator 13760 : public ExprEvaluatorBase<FloatExprEvaluator> { 13761 APFloat &Result; 13762 public: 13763 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13764 : ExprEvaluatorBaseTy(info), Result(result) {} 13765 13766 bool Success(const APValue &V, const Expr *e) { 13767 Result = V.getFloat(); 13768 return true; 13769 } 13770 13771 bool ZeroInitialization(const Expr *E) { 13772 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13773 return true; 13774 } 13775 13776 bool VisitCallExpr(const CallExpr *E); 13777 13778 bool VisitUnaryOperator(const UnaryOperator *E); 13779 bool VisitBinaryOperator(const BinaryOperator *E); 13780 bool VisitFloatingLiteral(const FloatingLiteral *E); 13781 bool VisitCastExpr(const CastExpr *E); 13782 13783 bool VisitUnaryReal(const UnaryOperator *E); 13784 bool VisitUnaryImag(const UnaryOperator *E); 13785 13786 // FIXME: Missing: array subscript of vector, member of vector 13787 }; 13788 } // end anonymous namespace 13789 13790 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13791 assert(!E->isValueDependent()); 13792 assert(E->isPRValue() && E->getType()->isRealFloatingType()); 13793 return FloatExprEvaluator(Info, Result).Visit(E); 13794 } 13795 13796 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13797 QualType ResultTy, 13798 const Expr *Arg, 13799 bool SNaN, 13800 llvm::APFloat &Result) { 13801 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13802 if (!S) return false; 13803 13804 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13805 13806 llvm::APInt fill; 13807 13808 // Treat empty strings as if they were zero. 13809 if (S->getString().empty()) 13810 fill = llvm::APInt(32, 0); 13811 else if (S->getString().getAsInteger(0, fill)) 13812 return false; 13813 13814 if (Context.getTargetInfo().isNan2008()) { 13815 if (SNaN) 13816 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13817 else 13818 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13819 } else { 13820 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13821 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13822 // a different encoding to what became a standard in 2008, and for pre- 13823 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13824 // sNaN. This is now known as "legacy NaN" encoding. 13825 if (SNaN) 13826 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13827 else 13828 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13829 } 13830 13831 return true; 13832 } 13833 13834 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13835 switch (E->getBuiltinCallee()) { 13836 default: 13837 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13838 13839 case Builtin::BI__builtin_huge_val: 13840 case Builtin::BI__builtin_huge_valf: 13841 case Builtin::BI__builtin_huge_vall: 13842 case Builtin::BI__builtin_huge_valf128: 13843 case Builtin::BI__builtin_inf: 13844 case Builtin::BI__builtin_inff: 13845 case Builtin::BI__builtin_infl: 13846 case Builtin::BI__builtin_inff128: { 13847 const llvm::fltSemantics &Sem = 13848 Info.Ctx.getFloatTypeSemantics(E->getType()); 13849 Result = llvm::APFloat::getInf(Sem); 13850 return true; 13851 } 13852 13853 case Builtin::BI__builtin_nans: 13854 case Builtin::BI__builtin_nansf: 13855 case Builtin::BI__builtin_nansl: 13856 case Builtin::BI__builtin_nansf128: 13857 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13858 true, Result)) 13859 return Error(E); 13860 return true; 13861 13862 case Builtin::BI__builtin_nan: 13863 case Builtin::BI__builtin_nanf: 13864 case Builtin::BI__builtin_nanl: 13865 case Builtin::BI__builtin_nanf128: 13866 // If this is __builtin_nan() turn this into a nan, otherwise we 13867 // can't constant fold it. 13868 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13869 false, Result)) 13870 return Error(E); 13871 return true; 13872 13873 case Builtin::BI__builtin_fabs: 13874 case Builtin::BI__builtin_fabsf: 13875 case Builtin::BI__builtin_fabsl: 13876 case Builtin::BI__builtin_fabsf128: 13877 // The C standard says "fabs raises no floating-point exceptions, 13878 // even if x is a signaling NaN. The returned value is independent of 13879 // the current rounding direction mode." Therefore constant folding can 13880 // proceed without regard to the floating point settings. 13881 // Reference, WG14 N2478 F.10.4.3 13882 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13883 return false; 13884 13885 if (Result.isNegative()) 13886 Result.changeSign(); 13887 return true; 13888 13889 case Builtin::BI__arithmetic_fence: 13890 return EvaluateFloat(E->getArg(0), Result, Info); 13891 13892 // FIXME: Builtin::BI__builtin_powi 13893 // FIXME: Builtin::BI__builtin_powif 13894 // FIXME: Builtin::BI__builtin_powil 13895 13896 case Builtin::BI__builtin_copysign: 13897 case Builtin::BI__builtin_copysignf: 13898 case Builtin::BI__builtin_copysignl: 13899 case Builtin::BI__builtin_copysignf128: { 13900 APFloat RHS(0.); 13901 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13902 !EvaluateFloat(E->getArg(1), RHS, Info)) 13903 return false; 13904 Result.copySign(RHS); 13905 return true; 13906 } 13907 } 13908 } 13909 13910 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13911 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13912 ComplexValue CV; 13913 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13914 return false; 13915 Result = CV.FloatReal; 13916 return true; 13917 } 13918 13919 return Visit(E->getSubExpr()); 13920 } 13921 13922 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13923 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13924 ComplexValue CV; 13925 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13926 return false; 13927 Result = CV.FloatImag; 13928 return true; 13929 } 13930 13931 VisitIgnoredValue(E->getSubExpr()); 13932 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13933 Result = llvm::APFloat::getZero(Sem); 13934 return true; 13935 } 13936 13937 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13938 switch (E->getOpcode()) { 13939 default: return Error(E); 13940 case UO_Plus: 13941 return EvaluateFloat(E->getSubExpr(), Result, Info); 13942 case UO_Minus: 13943 // In C standard, WG14 N2478 F.3 p4 13944 // "the unary - raises no floating point exceptions, 13945 // even if the operand is signalling." 13946 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13947 return false; 13948 Result.changeSign(); 13949 return true; 13950 } 13951 } 13952 13953 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13954 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13955 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13956 13957 APFloat RHS(0.0); 13958 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13959 if (!LHSOK && !Info.noteFailure()) 13960 return false; 13961 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13962 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13963 } 13964 13965 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13966 Result = E->getValue(); 13967 return true; 13968 } 13969 13970 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13971 const Expr* SubExpr = E->getSubExpr(); 13972 13973 switch (E->getCastKind()) { 13974 default: 13975 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13976 13977 case CK_IntegralToFloating: { 13978 APSInt IntResult; 13979 const FPOptions FPO = E->getFPFeaturesInEffect( 13980 Info.Ctx.getLangOpts()); 13981 return EvaluateInteger(SubExpr, IntResult, Info) && 13982 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13983 IntResult, E->getType(), Result); 13984 } 13985 13986 case CK_FixedPointToFloating: { 13987 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13988 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13989 return false; 13990 Result = 13991 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13992 return true; 13993 } 13994 13995 case CK_FloatingCast: { 13996 if (!Visit(SubExpr)) 13997 return false; 13998 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13999 Result); 14000 } 14001 14002 case CK_FloatingComplexToReal: { 14003 ComplexValue V; 14004 if (!EvaluateComplex(SubExpr, V, Info)) 14005 return false; 14006 Result = V.getComplexFloatReal(); 14007 return true; 14008 } 14009 } 14010 } 14011 14012 //===----------------------------------------------------------------------===// 14013 // Complex Evaluation (for float and integer) 14014 //===----------------------------------------------------------------------===// 14015 14016 namespace { 14017 class ComplexExprEvaluator 14018 : public ExprEvaluatorBase<ComplexExprEvaluator> { 14019 ComplexValue &Result; 14020 14021 public: 14022 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 14023 : ExprEvaluatorBaseTy(info), Result(Result) {} 14024 14025 bool Success(const APValue &V, const Expr *e) { 14026 Result.setFrom(V); 14027 return true; 14028 } 14029 14030 bool ZeroInitialization(const Expr *E); 14031 14032 //===--------------------------------------------------------------------===// 14033 // Visitor Methods 14034 //===--------------------------------------------------------------------===// 14035 14036 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 14037 bool VisitCastExpr(const CastExpr *E); 14038 bool VisitBinaryOperator(const BinaryOperator *E); 14039 bool VisitUnaryOperator(const UnaryOperator *E); 14040 bool VisitInitListExpr(const InitListExpr *E); 14041 bool VisitCallExpr(const CallExpr *E); 14042 }; 14043 } // end anonymous namespace 14044 14045 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 14046 EvalInfo &Info) { 14047 assert(!E->isValueDependent()); 14048 assert(E->isPRValue() && E->getType()->isAnyComplexType()); 14049 return ComplexExprEvaluator(Info, Result).Visit(E); 14050 } 14051 14052 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 14053 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 14054 if (ElemTy->isRealFloatingType()) { 14055 Result.makeComplexFloat(); 14056 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 14057 Result.FloatReal = Zero; 14058 Result.FloatImag = Zero; 14059 } else { 14060 Result.makeComplexInt(); 14061 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 14062 Result.IntReal = Zero; 14063 Result.IntImag = Zero; 14064 } 14065 return true; 14066 } 14067 14068 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 14069 const Expr* SubExpr = E->getSubExpr(); 14070 14071 if (SubExpr->getType()->isRealFloatingType()) { 14072 Result.makeComplexFloat(); 14073 APFloat &Imag = Result.FloatImag; 14074 if (!EvaluateFloat(SubExpr, Imag, Info)) 14075 return false; 14076 14077 Result.FloatReal = APFloat(Imag.getSemantics()); 14078 return true; 14079 } else { 14080 assert(SubExpr->getType()->isIntegerType() && 14081 "Unexpected imaginary literal."); 14082 14083 Result.makeComplexInt(); 14084 APSInt &Imag = Result.IntImag; 14085 if (!EvaluateInteger(SubExpr, Imag, Info)) 14086 return false; 14087 14088 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 14089 return true; 14090 } 14091 } 14092 14093 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 14094 14095 switch (E->getCastKind()) { 14096 case CK_BitCast: 14097 case CK_BaseToDerived: 14098 case CK_DerivedToBase: 14099 case CK_UncheckedDerivedToBase: 14100 case CK_Dynamic: 14101 case CK_ToUnion: 14102 case CK_ArrayToPointerDecay: 14103 case CK_FunctionToPointerDecay: 14104 case CK_NullToPointer: 14105 case CK_NullToMemberPointer: 14106 case CK_BaseToDerivedMemberPointer: 14107 case CK_DerivedToBaseMemberPointer: 14108 case CK_MemberPointerToBoolean: 14109 case CK_ReinterpretMemberPointer: 14110 case CK_ConstructorConversion: 14111 case CK_IntegralToPointer: 14112 case CK_PointerToIntegral: 14113 case CK_PointerToBoolean: 14114 case CK_ToVoid: 14115 case CK_VectorSplat: 14116 case CK_IntegralCast: 14117 case CK_BooleanToSignedIntegral: 14118 case CK_IntegralToBoolean: 14119 case CK_IntegralToFloating: 14120 case CK_FloatingToIntegral: 14121 case CK_FloatingToBoolean: 14122 case CK_FloatingCast: 14123 case CK_CPointerToObjCPointerCast: 14124 case CK_BlockPointerToObjCPointerCast: 14125 case CK_AnyPointerToBlockPointerCast: 14126 case CK_ObjCObjectLValueCast: 14127 case CK_FloatingComplexToReal: 14128 case CK_FloatingComplexToBoolean: 14129 case CK_IntegralComplexToReal: 14130 case CK_IntegralComplexToBoolean: 14131 case CK_ARCProduceObject: 14132 case CK_ARCConsumeObject: 14133 case CK_ARCReclaimReturnedObject: 14134 case CK_ARCExtendBlockObject: 14135 case CK_CopyAndAutoreleaseBlockObject: 14136 case CK_BuiltinFnToFnPtr: 14137 case CK_ZeroToOCLOpaqueType: 14138 case CK_NonAtomicToAtomic: 14139 case CK_AddressSpaceConversion: 14140 case CK_IntToOCLSampler: 14141 case CK_FloatingToFixedPoint: 14142 case CK_FixedPointToFloating: 14143 case CK_FixedPointCast: 14144 case CK_FixedPointToBoolean: 14145 case CK_FixedPointToIntegral: 14146 case CK_IntegralToFixedPoint: 14147 case CK_MatrixCast: 14148 llvm_unreachable("invalid cast kind for complex value"); 14149 14150 case CK_LValueToRValue: 14151 case CK_AtomicToNonAtomic: 14152 case CK_NoOp: 14153 case CK_LValueToRValueBitCast: 14154 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14155 14156 case CK_Dependent: 14157 case CK_LValueBitCast: 14158 case CK_UserDefinedConversion: 14159 return Error(E); 14160 14161 case CK_FloatingRealToComplex: { 14162 APFloat &Real = Result.FloatReal; 14163 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 14164 return false; 14165 14166 Result.makeComplexFloat(); 14167 Result.FloatImag = APFloat(Real.getSemantics()); 14168 return true; 14169 } 14170 14171 case CK_FloatingComplexCast: { 14172 if (!Visit(E->getSubExpr())) 14173 return false; 14174 14175 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14176 QualType From 14177 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14178 14179 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 14180 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 14181 } 14182 14183 case CK_FloatingComplexToIntegralComplex: { 14184 if (!Visit(E->getSubExpr())) 14185 return false; 14186 14187 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14188 QualType From 14189 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14190 Result.makeComplexInt(); 14191 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 14192 To, Result.IntReal) && 14193 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 14194 To, Result.IntImag); 14195 } 14196 14197 case CK_IntegralRealToComplex: { 14198 APSInt &Real = Result.IntReal; 14199 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14200 return false; 14201 14202 Result.makeComplexInt(); 14203 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14204 return true; 14205 } 14206 14207 case CK_IntegralComplexCast: { 14208 if (!Visit(E->getSubExpr())) 14209 return false; 14210 14211 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14212 QualType From 14213 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14214 14215 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14216 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14217 return true; 14218 } 14219 14220 case CK_IntegralComplexToFloatingComplex: { 14221 if (!Visit(E->getSubExpr())) 14222 return false; 14223 14224 const FPOptions FPO = E->getFPFeaturesInEffect( 14225 Info.Ctx.getLangOpts()); 14226 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14227 QualType From 14228 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14229 Result.makeComplexFloat(); 14230 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14231 To, Result.FloatReal) && 14232 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14233 To, Result.FloatImag); 14234 } 14235 } 14236 14237 llvm_unreachable("unknown cast resulting in complex value"); 14238 } 14239 14240 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14241 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14242 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14243 14244 // Track whether the LHS or RHS is real at the type system level. When this is 14245 // the case we can simplify our evaluation strategy. 14246 bool LHSReal = false, RHSReal = false; 14247 14248 bool LHSOK; 14249 if (E->getLHS()->getType()->isRealFloatingType()) { 14250 LHSReal = true; 14251 APFloat &Real = Result.FloatReal; 14252 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14253 if (LHSOK) { 14254 Result.makeComplexFloat(); 14255 Result.FloatImag = APFloat(Real.getSemantics()); 14256 } 14257 } else { 14258 LHSOK = Visit(E->getLHS()); 14259 } 14260 if (!LHSOK && !Info.noteFailure()) 14261 return false; 14262 14263 ComplexValue RHS; 14264 if (E->getRHS()->getType()->isRealFloatingType()) { 14265 RHSReal = true; 14266 APFloat &Real = RHS.FloatReal; 14267 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14268 return false; 14269 RHS.makeComplexFloat(); 14270 RHS.FloatImag = APFloat(Real.getSemantics()); 14271 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14272 return false; 14273 14274 assert(!(LHSReal && RHSReal) && 14275 "Cannot have both operands of a complex operation be real."); 14276 switch (E->getOpcode()) { 14277 default: return Error(E); 14278 case BO_Add: 14279 if (Result.isComplexFloat()) { 14280 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14281 APFloat::rmNearestTiesToEven); 14282 if (LHSReal) 14283 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14284 else if (!RHSReal) 14285 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14286 APFloat::rmNearestTiesToEven); 14287 } else { 14288 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14289 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14290 } 14291 break; 14292 case BO_Sub: 14293 if (Result.isComplexFloat()) { 14294 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14295 APFloat::rmNearestTiesToEven); 14296 if (LHSReal) { 14297 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14298 Result.getComplexFloatImag().changeSign(); 14299 } else if (!RHSReal) { 14300 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14301 APFloat::rmNearestTiesToEven); 14302 } 14303 } else { 14304 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14305 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14306 } 14307 break; 14308 case BO_Mul: 14309 if (Result.isComplexFloat()) { 14310 // This is an implementation of complex multiplication according to the 14311 // constraints laid out in C11 Annex G. The implementation uses the 14312 // following naming scheme: 14313 // (a + ib) * (c + id) 14314 ComplexValue LHS = Result; 14315 APFloat &A = LHS.getComplexFloatReal(); 14316 APFloat &B = LHS.getComplexFloatImag(); 14317 APFloat &C = RHS.getComplexFloatReal(); 14318 APFloat &D = RHS.getComplexFloatImag(); 14319 APFloat &ResR = Result.getComplexFloatReal(); 14320 APFloat &ResI = Result.getComplexFloatImag(); 14321 if (LHSReal) { 14322 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14323 ResR = A * C; 14324 ResI = A * D; 14325 } else if (RHSReal) { 14326 ResR = C * A; 14327 ResI = C * B; 14328 } else { 14329 // In the fully general case, we need to handle NaNs and infinities 14330 // robustly. 14331 APFloat AC = A * C; 14332 APFloat BD = B * D; 14333 APFloat AD = A * D; 14334 APFloat BC = B * C; 14335 ResR = AC - BD; 14336 ResI = AD + BC; 14337 if (ResR.isNaN() && ResI.isNaN()) { 14338 bool Recalc = false; 14339 if (A.isInfinity() || B.isInfinity()) { 14340 A = APFloat::copySign( 14341 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14342 B = APFloat::copySign( 14343 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14344 if (C.isNaN()) 14345 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14346 if (D.isNaN()) 14347 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14348 Recalc = true; 14349 } 14350 if (C.isInfinity() || D.isInfinity()) { 14351 C = APFloat::copySign( 14352 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14353 D = APFloat::copySign( 14354 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14355 if (A.isNaN()) 14356 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14357 if (B.isNaN()) 14358 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14359 Recalc = true; 14360 } 14361 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14362 AD.isInfinity() || BC.isInfinity())) { 14363 if (A.isNaN()) 14364 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14365 if (B.isNaN()) 14366 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14367 if (C.isNaN()) 14368 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14369 if (D.isNaN()) 14370 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14371 Recalc = true; 14372 } 14373 if (Recalc) { 14374 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14375 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14376 } 14377 } 14378 } 14379 } else { 14380 ComplexValue LHS = Result; 14381 Result.getComplexIntReal() = 14382 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14383 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14384 Result.getComplexIntImag() = 14385 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14386 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14387 } 14388 break; 14389 case BO_Div: 14390 if (Result.isComplexFloat()) { 14391 // This is an implementation of complex division according to the 14392 // constraints laid out in C11 Annex G. The implementation uses the 14393 // following naming scheme: 14394 // (a + ib) / (c + id) 14395 ComplexValue LHS = Result; 14396 APFloat &A = LHS.getComplexFloatReal(); 14397 APFloat &B = LHS.getComplexFloatImag(); 14398 APFloat &C = RHS.getComplexFloatReal(); 14399 APFloat &D = RHS.getComplexFloatImag(); 14400 APFloat &ResR = Result.getComplexFloatReal(); 14401 APFloat &ResI = Result.getComplexFloatImag(); 14402 if (RHSReal) { 14403 ResR = A / C; 14404 ResI = B / C; 14405 } else { 14406 if (LHSReal) { 14407 // No real optimizations we can do here, stub out with zero. 14408 B = APFloat::getZero(A.getSemantics()); 14409 } 14410 int DenomLogB = 0; 14411 APFloat MaxCD = maxnum(abs(C), abs(D)); 14412 if (MaxCD.isFinite()) { 14413 DenomLogB = ilogb(MaxCD); 14414 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14415 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14416 } 14417 APFloat Denom = C * C + D * D; 14418 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14419 APFloat::rmNearestTiesToEven); 14420 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14421 APFloat::rmNearestTiesToEven); 14422 if (ResR.isNaN() && ResI.isNaN()) { 14423 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14424 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14425 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14426 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14427 D.isFinite()) { 14428 A = APFloat::copySign( 14429 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14430 B = APFloat::copySign( 14431 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14432 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14433 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14434 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14435 C = APFloat::copySign( 14436 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14437 D = APFloat::copySign( 14438 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14439 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14440 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14441 } 14442 } 14443 } 14444 } else { 14445 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14446 return Error(E, diag::note_expr_divide_by_zero); 14447 14448 ComplexValue LHS = Result; 14449 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14450 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14451 Result.getComplexIntReal() = 14452 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14453 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14454 Result.getComplexIntImag() = 14455 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14456 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14457 } 14458 break; 14459 } 14460 14461 return true; 14462 } 14463 14464 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14465 // Get the operand value into 'Result'. 14466 if (!Visit(E->getSubExpr())) 14467 return false; 14468 14469 switch (E->getOpcode()) { 14470 default: 14471 return Error(E); 14472 case UO_Extension: 14473 return true; 14474 case UO_Plus: 14475 // The result is always just the subexpr. 14476 return true; 14477 case UO_Minus: 14478 if (Result.isComplexFloat()) { 14479 Result.getComplexFloatReal().changeSign(); 14480 Result.getComplexFloatImag().changeSign(); 14481 } 14482 else { 14483 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14484 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14485 } 14486 return true; 14487 case UO_Not: 14488 if (Result.isComplexFloat()) 14489 Result.getComplexFloatImag().changeSign(); 14490 else 14491 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14492 return true; 14493 } 14494 } 14495 14496 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14497 if (E->getNumInits() == 2) { 14498 if (E->getType()->isComplexType()) { 14499 Result.makeComplexFloat(); 14500 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14501 return false; 14502 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14503 return false; 14504 } else { 14505 Result.makeComplexInt(); 14506 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14507 return false; 14508 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14509 return false; 14510 } 14511 return true; 14512 } 14513 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14514 } 14515 14516 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14517 switch (E->getBuiltinCallee()) { 14518 case Builtin::BI__builtin_complex: 14519 Result.makeComplexFloat(); 14520 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14521 return false; 14522 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14523 return false; 14524 return true; 14525 14526 default: 14527 break; 14528 } 14529 14530 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14531 } 14532 14533 //===----------------------------------------------------------------------===// 14534 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14535 // implicit conversion. 14536 //===----------------------------------------------------------------------===// 14537 14538 namespace { 14539 class AtomicExprEvaluator : 14540 public ExprEvaluatorBase<AtomicExprEvaluator> { 14541 const LValue *This; 14542 APValue &Result; 14543 public: 14544 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14545 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14546 14547 bool Success(const APValue &V, const Expr *E) { 14548 Result = V; 14549 return true; 14550 } 14551 14552 bool ZeroInitialization(const Expr *E) { 14553 ImplicitValueInitExpr VIE( 14554 E->getType()->castAs<AtomicType>()->getValueType()); 14555 // For atomic-qualified class (and array) types in C++, initialize the 14556 // _Atomic-wrapped subobject directly, in-place. 14557 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14558 : Evaluate(Result, Info, &VIE); 14559 } 14560 14561 bool VisitCastExpr(const CastExpr *E) { 14562 switch (E->getCastKind()) { 14563 default: 14564 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14565 case CK_NonAtomicToAtomic: 14566 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14567 : Evaluate(Result, Info, E->getSubExpr()); 14568 } 14569 } 14570 }; 14571 } // end anonymous namespace 14572 14573 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14574 EvalInfo &Info) { 14575 assert(!E->isValueDependent()); 14576 assert(E->isPRValue() && E->getType()->isAtomicType()); 14577 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14578 } 14579 14580 //===----------------------------------------------------------------------===// 14581 // Void expression evaluation, primarily for a cast to void on the LHS of a 14582 // comma operator 14583 //===----------------------------------------------------------------------===// 14584 14585 namespace { 14586 class VoidExprEvaluator 14587 : public ExprEvaluatorBase<VoidExprEvaluator> { 14588 public: 14589 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14590 14591 bool Success(const APValue &V, const Expr *e) { return true; } 14592 14593 bool ZeroInitialization(const Expr *E) { return true; } 14594 14595 bool VisitCastExpr(const CastExpr *E) { 14596 switch (E->getCastKind()) { 14597 default: 14598 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14599 case CK_ToVoid: 14600 VisitIgnoredValue(E->getSubExpr()); 14601 return true; 14602 } 14603 } 14604 14605 bool VisitCallExpr(const CallExpr *E) { 14606 switch (E->getBuiltinCallee()) { 14607 case Builtin::BI__assume: 14608 case Builtin::BI__builtin_assume: 14609 // The argument is not evaluated! 14610 return true; 14611 14612 case Builtin::BI__builtin_operator_delete: 14613 return HandleOperatorDeleteCall(Info, E); 14614 14615 default: 14616 break; 14617 } 14618 14619 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14620 } 14621 14622 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14623 }; 14624 } // end anonymous namespace 14625 14626 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14627 // We cannot speculatively evaluate a delete expression. 14628 if (Info.SpeculativeEvaluationDepth) 14629 return false; 14630 14631 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14632 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14633 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14634 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14635 return false; 14636 } 14637 14638 const Expr *Arg = E->getArgument(); 14639 14640 LValue Pointer; 14641 if (!EvaluatePointer(Arg, Pointer, Info)) 14642 return false; 14643 if (Pointer.Designator.Invalid) 14644 return false; 14645 14646 // Deleting a null pointer has no effect. 14647 if (Pointer.isNullPointer()) { 14648 // This is the only case where we need to produce an extension warning: 14649 // the only other way we can succeed is if we find a dynamic allocation, 14650 // and we will have warned when we allocated it in that case. 14651 if (!Info.getLangOpts().CPlusPlus20) 14652 Info.CCEDiag(E, diag::note_constexpr_new); 14653 return true; 14654 } 14655 14656 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14657 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14658 if (!Alloc) 14659 return false; 14660 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14661 14662 // For the non-array case, the designator must be empty if the static type 14663 // does not have a virtual destructor. 14664 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14665 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14666 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14667 << Arg->getType()->getPointeeType() << AllocType; 14668 return false; 14669 } 14670 14671 // For a class type with a virtual destructor, the selected operator delete 14672 // is the one looked up when building the destructor. 14673 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14674 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14675 if (VirtualDelete && 14676 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14677 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14678 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14679 return false; 14680 } 14681 } 14682 14683 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14684 (*Alloc)->Value, AllocType)) 14685 return false; 14686 14687 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14688 // The element was already erased. This means the destructor call also 14689 // deleted the object. 14690 // FIXME: This probably results in undefined behavior before we get this 14691 // far, and should be diagnosed elsewhere first. 14692 Info.FFDiag(E, diag::note_constexpr_double_delete); 14693 return false; 14694 } 14695 14696 return true; 14697 } 14698 14699 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14700 assert(!E->isValueDependent()); 14701 assert(E->isPRValue() && E->getType()->isVoidType()); 14702 return VoidExprEvaluator(Info).Visit(E); 14703 } 14704 14705 //===----------------------------------------------------------------------===// 14706 // Top level Expr::EvaluateAsRValue method. 14707 //===----------------------------------------------------------------------===// 14708 14709 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14710 assert(!E->isValueDependent()); 14711 // In C, function designators are not lvalues, but we evaluate them as if they 14712 // are. 14713 QualType T = E->getType(); 14714 if (E->isGLValue() || T->isFunctionType()) { 14715 LValue LV; 14716 if (!EvaluateLValue(E, LV, Info)) 14717 return false; 14718 LV.moveInto(Result); 14719 } else if (T->isVectorType()) { 14720 if (!EvaluateVector(E, Result, Info)) 14721 return false; 14722 } else if (T->isIntegralOrEnumerationType()) { 14723 if (!IntExprEvaluator(Info, Result).Visit(E)) 14724 return false; 14725 } else if (T->hasPointerRepresentation()) { 14726 LValue LV; 14727 if (!EvaluatePointer(E, LV, Info)) 14728 return false; 14729 LV.moveInto(Result); 14730 } else if (T->isRealFloatingType()) { 14731 llvm::APFloat F(0.0); 14732 if (!EvaluateFloat(E, F, Info)) 14733 return false; 14734 Result = APValue(F); 14735 } else if (T->isAnyComplexType()) { 14736 ComplexValue C; 14737 if (!EvaluateComplex(E, C, Info)) 14738 return false; 14739 C.moveInto(Result); 14740 } else if (T->isFixedPointType()) { 14741 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14742 } else if (T->isMemberPointerType()) { 14743 MemberPtr P; 14744 if (!EvaluateMemberPointer(E, P, Info)) 14745 return false; 14746 P.moveInto(Result); 14747 return true; 14748 } else if (T->isArrayType()) { 14749 LValue LV; 14750 APValue &Value = 14751 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14752 if (!EvaluateArray(E, LV, Value, Info)) 14753 return false; 14754 Result = Value; 14755 } else if (T->isRecordType()) { 14756 LValue LV; 14757 APValue &Value = 14758 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14759 if (!EvaluateRecord(E, LV, Value, Info)) 14760 return false; 14761 Result = Value; 14762 } else if (T->isVoidType()) { 14763 if (!Info.getLangOpts().CPlusPlus11) 14764 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14765 << E->getType(); 14766 if (!EvaluateVoid(E, Info)) 14767 return false; 14768 } else if (T->isAtomicType()) { 14769 QualType Unqual = T.getAtomicUnqualifiedType(); 14770 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14771 LValue LV; 14772 APValue &Value = Info.CurrentCall->createTemporary( 14773 E, Unqual, ScopeKind::FullExpression, LV); 14774 if (!EvaluateAtomic(E, &LV, Value, Info)) 14775 return false; 14776 } else { 14777 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14778 return false; 14779 } 14780 } else if (Info.getLangOpts().CPlusPlus11) { 14781 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14782 return false; 14783 } else { 14784 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14785 return false; 14786 } 14787 14788 return true; 14789 } 14790 14791 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14792 /// cases, the in-place evaluation is essential, since later initializers for 14793 /// an object can indirectly refer to subobjects which were initialized earlier. 14794 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14795 const Expr *E, bool AllowNonLiteralTypes) { 14796 assert(!E->isValueDependent()); 14797 14798 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14799 return false; 14800 14801 if (E->isPRValue()) { 14802 // Evaluate arrays and record types in-place, so that later initializers can 14803 // refer to earlier-initialized members of the object. 14804 QualType T = E->getType(); 14805 if (T->isArrayType()) 14806 return EvaluateArray(E, This, Result, Info); 14807 else if (T->isRecordType()) 14808 return EvaluateRecord(E, This, Result, Info); 14809 else if (T->isAtomicType()) { 14810 QualType Unqual = T.getAtomicUnqualifiedType(); 14811 if (Unqual->isArrayType() || Unqual->isRecordType()) 14812 return EvaluateAtomic(E, &This, Result, Info); 14813 } 14814 } 14815 14816 // For any other type, in-place evaluation is unimportant. 14817 return Evaluate(Result, Info, E); 14818 } 14819 14820 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14821 /// lvalue-to-rvalue cast if it is an lvalue. 14822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14823 assert(!E->isValueDependent()); 14824 if (Info.EnableNewConstInterp) { 14825 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14826 return false; 14827 } else { 14828 if (E->getType().isNull()) 14829 return false; 14830 14831 if (!CheckLiteralType(Info, E)) 14832 return false; 14833 14834 if (!::Evaluate(Result, Info, E)) 14835 return false; 14836 14837 if (E->isGLValue()) { 14838 LValue LV; 14839 LV.setFrom(Info.Ctx, Result); 14840 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14841 return false; 14842 } 14843 } 14844 14845 // Check this core constant expression is a constant expression. 14846 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14847 ConstantExprKind::Normal) && 14848 CheckMemoryLeaks(Info); 14849 } 14850 14851 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14852 const ASTContext &Ctx, bool &IsConst) { 14853 // Fast-path evaluations of integer literals, since we sometimes see files 14854 // containing vast quantities of these. 14855 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14856 Result.Val = APValue(APSInt(L->getValue(), 14857 L->getType()->isUnsignedIntegerType())); 14858 IsConst = true; 14859 return true; 14860 } 14861 14862 // This case should be rare, but we need to check it before we check on 14863 // the type below. 14864 if (Exp->getType().isNull()) { 14865 IsConst = false; 14866 return true; 14867 } 14868 14869 // FIXME: Evaluating values of large array and record types can cause 14870 // performance problems. Only do so in C++11 for now. 14871 if (Exp->isPRValue() && 14872 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && 14873 !Ctx.getLangOpts().CPlusPlus11) { 14874 IsConst = false; 14875 return true; 14876 } 14877 return false; 14878 } 14879 14880 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14881 Expr::SideEffectsKind SEK) { 14882 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14883 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14884 } 14885 14886 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14887 const ASTContext &Ctx, EvalInfo &Info) { 14888 assert(!E->isValueDependent()); 14889 bool IsConst; 14890 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14891 return IsConst; 14892 14893 return EvaluateAsRValue(Info, E, Result.Val); 14894 } 14895 14896 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14897 const ASTContext &Ctx, 14898 Expr::SideEffectsKind AllowSideEffects, 14899 EvalInfo &Info) { 14900 assert(!E->isValueDependent()); 14901 if (!E->getType()->isIntegralOrEnumerationType()) 14902 return false; 14903 14904 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14905 !ExprResult.Val.isInt() || 14906 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14907 return false; 14908 14909 return true; 14910 } 14911 14912 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14913 const ASTContext &Ctx, 14914 Expr::SideEffectsKind AllowSideEffects, 14915 EvalInfo &Info) { 14916 assert(!E->isValueDependent()); 14917 if (!E->getType()->isFixedPointType()) 14918 return false; 14919 14920 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14921 return false; 14922 14923 if (!ExprResult.Val.isFixedPoint() || 14924 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14925 return false; 14926 14927 return true; 14928 } 14929 14930 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14931 /// any crazy technique (that has nothing to do with language standards) that 14932 /// we want to. If this function returns true, it returns the folded constant 14933 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14934 /// will be applied to the result. 14935 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14936 bool InConstantContext) const { 14937 assert(!isValueDependent() && 14938 "Expression evaluator can't be called on a dependent expression."); 14939 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14940 Info.InConstantContext = InConstantContext; 14941 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14942 } 14943 14944 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14945 bool InConstantContext) const { 14946 assert(!isValueDependent() && 14947 "Expression evaluator can't be called on a dependent expression."); 14948 EvalResult Scratch; 14949 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14950 HandleConversionToBool(Scratch.Val, Result); 14951 } 14952 14953 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14954 SideEffectsKind AllowSideEffects, 14955 bool InConstantContext) const { 14956 assert(!isValueDependent() && 14957 "Expression evaluator can't be called on a dependent expression."); 14958 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14959 Info.InConstantContext = InConstantContext; 14960 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14961 } 14962 14963 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14964 SideEffectsKind AllowSideEffects, 14965 bool InConstantContext) const { 14966 assert(!isValueDependent() && 14967 "Expression evaluator can't be called on a dependent expression."); 14968 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14969 Info.InConstantContext = InConstantContext; 14970 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14971 } 14972 14973 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14974 SideEffectsKind AllowSideEffects, 14975 bool InConstantContext) const { 14976 assert(!isValueDependent() && 14977 "Expression evaluator can't be called on a dependent expression."); 14978 14979 if (!getType()->isRealFloatingType()) 14980 return false; 14981 14982 EvalResult ExprResult; 14983 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14984 !ExprResult.Val.isFloat() || 14985 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14986 return false; 14987 14988 Result = ExprResult.Val.getFloat(); 14989 return true; 14990 } 14991 14992 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14993 bool InConstantContext) const { 14994 assert(!isValueDependent() && 14995 "Expression evaluator can't be called on a dependent expression."); 14996 14997 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14998 Info.InConstantContext = InConstantContext; 14999 LValue LV; 15000 CheckedTemporaries CheckedTemps; 15001 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 15002 Result.HasSideEffects || 15003 !CheckLValueConstantExpression(Info, getExprLoc(), 15004 Ctx.getLValueReferenceType(getType()), LV, 15005 ConstantExprKind::Normal, CheckedTemps)) 15006 return false; 15007 15008 LV.moveInto(Result.Val); 15009 return true; 15010 } 15011 15012 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 15013 APValue DestroyedValue, QualType Type, 15014 SourceLocation Loc, Expr::EvalStatus &EStatus, 15015 bool IsConstantDestruction) { 15016 EvalInfo Info(Ctx, EStatus, 15017 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 15018 : EvalInfo::EM_ConstantFold); 15019 Info.setEvaluatingDecl(Base, DestroyedValue, 15020 EvalInfo::EvaluatingDeclKind::Dtor); 15021 Info.InConstantContext = IsConstantDestruction; 15022 15023 LValue LVal; 15024 LVal.set(Base); 15025 15026 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 15027 EStatus.HasSideEffects) 15028 return false; 15029 15030 if (!Info.discardCleanups()) 15031 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15032 15033 return true; 15034 } 15035 15036 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 15037 ConstantExprKind Kind) const { 15038 assert(!isValueDependent() && 15039 "Expression evaluator can't be called on a dependent expression."); 15040 15041 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 15042 EvalInfo Info(Ctx, Result, EM); 15043 Info.InConstantContext = true; 15044 15045 // The type of the object we're initializing is 'const T' for a class NTTP. 15046 QualType T = getType(); 15047 if (Kind == ConstantExprKind::ClassTemplateArgument) 15048 T.addConst(); 15049 15050 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 15051 // represent the result of the evaluation. CheckConstantExpression ensures 15052 // this doesn't escape. 15053 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 15054 APValue::LValueBase Base(&BaseMTE); 15055 15056 Info.setEvaluatingDecl(Base, Result.Val); 15057 LValue LVal; 15058 LVal.set(Base); 15059 15060 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 15061 return false; 15062 15063 if (!Info.discardCleanups()) 15064 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15065 15066 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 15067 Result.Val, Kind)) 15068 return false; 15069 if (!CheckMemoryLeaks(Info)) 15070 return false; 15071 15072 // If this is a class template argument, it's required to have constant 15073 // destruction too. 15074 if (Kind == ConstantExprKind::ClassTemplateArgument && 15075 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 15076 true) || 15077 Result.HasSideEffects)) { 15078 // FIXME: Prefix a note to indicate that the problem is lack of constant 15079 // destruction. 15080 return false; 15081 } 15082 15083 return true; 15084 } 15085 15086 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 15087 const VarDecl *VD, 15088 SmallVectorImpl<PartialDiagnosticAt> &Notes, 15089 bool IsConstantInitialization) const { 15090 assert(!isValueDependent() && 15091 "Expression evaluator can't be called on a dependent expression."); 15092 15093 // FIXME: Evaluating initializers for large array and record types can cause 15094 // performance problems. Only do so in C++11 for now. 15095 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 15096 !Ctx.getLangOpts().CPlusPlus11) 15097 return false; 15098 15099 Expr::EvalStatus EStatus; 15100 EStatus.Diag = &Notes; 15101 15102 EvalInfo Info(Ctx, EStatus, 15103 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 15104 ? EvalInfo::EM_ConstantExpression 15105 : EvalInfo::EM_ConstantFold); 15106 Info.setEvaluatingDecl(VD, Value); 15107 Info.InConstantContext = IsConstantInitialization; 15108 15109 SourceLocation DeclLoc = VD->getLocation(); 15110 QualType DeclTy = VD->getType(); 15111 15112 if (Info.EnableNewConstInterp) { 15113 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 15114 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 15115 return false; 15116 } else { 15117 LValue LVal; 15118 LVal.set(VD); 15119 15120 if (!EvaluateInPlace(Value, Info, LVal, this, 15121 /*AllowNonLiteralTypes=*/true) || 15122 EStatus.HasSideEffects) 15123 return false; 15124 15125 // At this point, any lifetime-extended temporaries are completely 15126 // initialized. 15127 Info.performLifetimeExtension(); 15128 15129 if (!Info.discardCleanups()) 15130 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 15131 } 15132 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 15133 ConstantExprKind::Normal) && 15134 CheckMemoryLeaks(Info); 15135 } 15136 15137 bool VarDecl::evaluateDestruction( 15138 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 15139 Expr::EvalStatus EStatus; 15140 EStatus.Diag = &Notes; 15141 15142 // Only treat the destruction as constant destruction if we formally have 15143 // constant initialization (or are usable in a constant expression). 15144 bool IsConstantDestruction = hasConstantInitialization(); 15145 15146 // Make a copy of the value for the destructor to mutate, if we know it. 15147 // Otherwise, treat the value as default-initialized; if the destructor works 15148 // anyway, then the destruction is constant (and must be essentially empty). 15149 APValue DestroyedValue; 15150 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 15151 DestroyedValue = *getEvaluatedValue(); 15152 else if (!getDefaultInitValue(getType(), DestroyedValue)) 15153 return false; 15154 15155 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 15156 getType(), getLocation(), EStatus, 15157 IsConstantDestruction) || 15158 EStatus.HasSideEffects) 15159 return false; 15160 15161 ensureEvaluatedStmt()->HasConstantDestruction = true; 15162 return true; 15163 } 15164 15165 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 15166 /// constant folded, but discard the result. 15167 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 15168 assert(!isValueDependent() && 15169 "Expression evaluator can't be called on a dependent expression."); 15170 15171 EvalResult Result; 15172 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 15173 !hasUnacceptableSideEffect(Result, SEK); 15174 } 15175 15176 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 15177 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15178 assert(!isValueDependent() && 15179 "Expression evaluator can't be called on a dependent expression."); 15180 15181 EvalResult EVResult; 15182 EVResult.Diag = Diag; 15183 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15184 Info.InConstantContext = true; 15185 15186 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 15187 (void)Result; 15188 assert(Result && "Could not evaluate expression"); 15189 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15190 15191 return EVResult.Val.getInt(); 15192 } 15193 15194 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 15195 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 15196 assert(!isValueDependent() && 15197 "Expression evaluator can't be called on a dependent expression."); 15198 15199 EvalResult EVResult; 15200 EVResult.Diag = Diag; 15201 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15202 Info.InConstantContext = true; 15203 Info.CheckingForUndefinedBehavior = true; 15204 15205 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15206 (void)Result; 15207 assert(Result && "Could not evaluate expression"); 15208 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15209 15210 return EVResult.Val.getInt(); 15211 } 15212 15213 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15214 assert(!isValueDependent() && 15215 "Expression evaluator can't be called on a dependent expression."); 15216 15217 bool IsConst; 15218 EvalResult EVResult; 15219 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15220 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15221 Info.CheckingForUndefinedBehavior = true; 15222 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15223 } 15224 } 15225 15226 bool Expr::EvalResult::isGlobalLValue() const { 15227 assert(Val.isLValue()); 15228 return IsGlobalLValue(Val.getLValueBase()); 15229 } 15230 15231 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15232 /// an integer constant expression. 15233 15234 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15235 /// comma, etc 15236 15237 // CheckICE - This function does the fundamental ICE checking: the returned 15238 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15239 // and a (possibly null) SourceLocation indicating the location of the problem. 15240 // 15241 // Note that to reduce code duplication, this helper does no evaluation 15242 // itself; the caller checks whether the expression is evaluatable, and 15243 // in the rare cases where CheckICE actually cares about the evaluated 15244 // value, it calls into Evaluate. 15245 15246 namespace { 15247 15248 enum ICEKind { 15249 /// This expression is an ICE. 15250 IK_ICE, 15251 /// This expression is not an ICE, but if it isn't evaluated, it's 15252 /// a legal subexpression for an ICE. This return value is used to handle 15253 /// the comma operator in C99 mode, and non-constant subexpressions. 15254 IK_ICEIfUnevaluated, 15255 /// This expression is not an ICE, and is not a legal subexpression for one. 15256 IK_NotICE 15257 }; 15258 15259 struct ICEDiag { 15260 ICEKind Kind; 15261 SourceLocation Loc; 15262 15263 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15264 }; 15265 15266 } 15267 15268 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15269 15270 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15271 15272 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15273 Expr::EvalResult EVResult; 15274 Expr::EvalStatus Status; 15275 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15276 15277 Info.InConstantContext = true; 15278 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15279 !EVResult.Val.isInt()) 15280 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15281 15282 return NoDiag(); 15283 } 15284 15285 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15286 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15287 if (!E->getType()->isIntegralOrEnumerationType()) 15288 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15289 15290 switch (E->getStmtClass()) { 15291 #define ABSTRACT_STMT(Node) 15292 #define STMT(Node, Base) case Expr::Node##Class: 15293 #define EXPR(Node, Base) 15294 #include "clang/AST/StmtNodes.inc" 15295 case Expr::PredefinedExprClass: 15296 case Expr::FloatingLiteralClass: 15297 case Expr::ImaginaryLiteralClass: 15298 case Expr::StringLiteralClass: 15299 case Expr::ArraySubscriptExprClass: 15300 case Expr::MatrixSubscriptExprClass: 15301 case Expr::OMPArraySectionExprClass: 15302 case Expr::OMPArrayShapingExprClass: 15303 case Expr::OMPIteratorExprClass: 15304 case Expr::MemberExprClass: 15305 case Expr::CompoundAssignOperatorClass: 15306 case Expr::CompoundLiteralExprClass: 15307 case Expr::ExtVectorElementExprClass: 15308 case Expr::DesignatedInitExprClass: 15309 case Expr::ArrayInitLoopExprClass: 15310 case Expr::ArrayInitIndexExprClass: 15311 case Expr::NoInitExprClass: 15312 case Expr::DesignatedInitUpdateExprClass: 15313 case Expr::ImplicitValueInitExprClass: 15314 case Expr::ParenListExprClass: 15315 case Expr::VAArgExprClass: 15316 case Expr::AddrLabelExprClass: 15317 case Expr::StmtExprClass: 15318 case Expr::CXXMemberCallExprClass: 15319 case Expr::CUDAKernelCallExprClass: 15320 case Expr::CXXAddrspaceCastExprClass: 15321 case Expr::CXXDynamicCastExprClass: 15322 case Expr::CXXTypeidExprClass: 15323 case Expr::CXXUuidofExprClass: 15324 case Expr::MSPropertyRefExprClass: 15325 case Expr::MSPropertySubscriptExprClass: 15326 case Expr::CXXNullPtrLiteralExprClass: 15327 case Expr::UserDefinedLiteralClass: 15328 case Expr::CXXThisExprClass: 15329 case Expr::CXXThrowExprClass: 15330 case Expr::CXXNewExprClass: 15331 case Expr::CXXDeleteExprClass: 15332 case Expr::CXXPseudoDestructorExprClass: 15333 case Expr::UnresolvedLookupExprClass: 15334 case Expr::TypoExprClass: 15335 case Expr::RecoveryExprClass: 15336 case Expr::DependentScopeDeclRefExprClass: 15337 case Expr::CXXConstructExprClass: 15338 case Expr::CXXInheritedCtorInitExprClass: 15339 case Expr::CXXStdInitializerListExprClass: 15340 case Expr::CXXBindTemporaryExprClass: 15341 case Expr::ExprWithCleanupsClass: 15342 case Expr::CXXTemporaryObjectExprClass: 15343 case Expr::CXXUnresolvedConstructExprClass: 15344 case Expr::CXXDependentScopeMemberExprClass: 15345 case Expr::UnresolvedMemberExprClass: 15346 case Expr::ObjCStringLiteralClass: 15347 case Expr::ObjCBoxedExprClass: 15348 case Expr::ObjCArrayLiteralClass: 15349 case Expr::ObjCDictionaryLiteralClass: 15350 case Expr::ObjCEncodeExprClass: 15351 case Expr::ObjCMessageExprClass: 15352 case Expr::ObjCSelectorExprClass: 15353 case Expr::ObjCProtocolExprClass: 15354 case Expr::ObjCIvarRefExprClass: 15355 case Expr::ObjCPropertyRefExprClass: 15356 case Expr::ObjCSubscriptRefExprClass: 15357 case Expr::ObjCIsaExprClass: 15358 case Expr::ObjCAvailabilityCheckExprClass: 15359 case Expr::ShuffleVectorExprClass: 15360 case Expr::ConvertVectorExprClass: 15361 case Expr::BlockExprClass: 15362 case Expr::NoStmtClass: 15363 case Expr::OpaqueValueExprClass: 15364 case Expr::PackExpansionExprClass: 15365 case Expr::SubstNonTypeTemplateParmPackExprClass: 15366 case Expr::FunctionParmPackExprClass: 15367 case Expr::AsTypeExprClass: 15368 case Expr::ObjCIndirectCopyRestoreExprClass: 15369 case Expr::MaterializeTemporaryExprClass: 15370 case Expr::PseudoObjectExprClass: 15371 case Expr::AtomicExprClass: 15372 case Expr::LambdaExprClass: 15373 case Expr::CXXFoldExprClass: 15374 case Expr::CoawaitExprClass: 15375 case Expr::DependentCoawaitExprClass: 15376 case Expr::CoyieldExprClass: 15377 case Expr::SYCLUniqueStableNameExprClass: 15378 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15379 15380 case Expr::InitListExprClass: { 15381 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15382 // form "T x = { a };" is equivalent to "T x = a;". 15383 // Unless we're initializing a reference, T is a scalar as it is known to be 15384 // of integral or enumeration type. 15385 if (E->isPRValue()) 15386 if (cast<InitListExpr>(E)->getNumInits() == 1) 15387 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15388 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15389 } 15390 15391 case Expr::SizeOfPackExprClass: 15392 case Expr::GNUNullExprClass: 15393 case Expr::SourceLocExprClass: 15394 return NoDiag(); 15395 15396 case Expr::SubstNonTypeTemplateParmExprClass: 15397 return 15398 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15399 15400 case Expr::ConstantExprClass: 15401 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15402 15403 case Expr::ParenExprClass: 15404 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15405 case Expr::GenericSelectionExprClass: 15406 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15407 case Expr::IntegerLiteralClass: 15408 case Expr::FixedPointLiteralClass: 15409 case Expr::CharacterLiteralClass: 15410 case Expr::ObjCBoolLiteralExprClass: 15411 case Expr::CXXBoolLiteralExprClass: 15412 case Expr::CXXScalarValueInitExprClass: 15413 case Expr::TypeTraitExprClass: 15414 case Expr::ConceptSpecializationExprClass: 15415 case Expr::RequiresExprClass: 15416 case Expr::ArrayTypeTraitExprClass: 15417 case Expr::ExpressionTraitExprClass: 15418 case Expr::CXXNoexceptExprClass: 15419 return NoDiag(); 15420 case Expr::CallExprClass: 15421 case Expr::CXXOperatorCallExprClass: { 15422 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15423 // constant expressions, but they can never be ICEs because an ICE cannot 15424 // contain an operand of (pointer to) function type. 15425 const CallExpr *CE = cast<CallExpr>(E); 15426 if (CE->getBuiltinCallee()) 15427 return CheckEvalInICE(E, Ctx); 15428 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15429 } 15430 case Expr::CXXRewrittenBinaryOperatorClass: 15431 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15432 Ctx); 15433 case Expr::DeclRefExprClass: { 15434 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15435 if (isa<EnumConstantDecl>(D)) 15436 return NoDiag(); 15437 15438 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15439 // integer variables in constant expressions: 15440 // 15441 // C++ 7.1.5.1p2 15442 // A variable of non-volatile const-qualified integral or enumeration 15443 // type initialized by an ICE can be used in ICEs. 15444 // 15445 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15446 // that mode, use of reference variables should not be allowed. 15447 const VarDecl *VD = dyn_cast<VarDecl>(D); 15448 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15449 !VD->getType()->isReferenceType()) 15450 return NoDiag(); 15451 15452 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15453 } 15454 case Expr::UnaryOperatorClass: { 15455 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15456 switch (Exp->getOpcode()) { 15457 case UO_PostInc: 15458 case UO_PostDec: 15459 case UO_PreInc: 15460 case UO_PreDec: 15461 case UO_AddrOf: 15462 case UO_Deref: 15463 case UO_Coawait: 15464 // C99 6.6/3 allows increment and decrement within unevaluated 15465 // subexpressions of constant expressions, but they can never be ICEs 15466 // because an ICE cannot contain an lvalue operand. 15467 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15468 case UO_Extension: 15469 case UO_LNot: 15470 case UO_Plus: 15471 case UO_Minus: 15472 case UO_Not: 15473 case UO_Real: 15474 case UO_Imag: 15475 return CheckICE(Exp->getSubExpr(), Ctx); 15476 } 15477 llvm_unreachable("invalid unary operator class"); 15478 } 15479 case Expr::OffsetOfExprClass: { 15480 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15481 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15482 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15483 // compliance: we should warn earlier for offsetof expressions with 15484 // array subscripts that aren't ICEs, and if the array subscripts 15485 // are ICEs, the value of the offsetof must be an integer constant. 15486 return CheckEvalInICE(E, Ctx); 15487 } 15488 case Expr::UnaryExprOrTypeTraitExprClass: { 15489 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15490 if ((Exp->getKind() == UETT_SizeOf) && 15491 Exp->getTypeOfArgument()->isVariableArrayType()) 15492 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15493 return NoDiag(); 15494 } 15495 case Expr::BinaryOperatorClass: { 15496 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15497 switch (Exp->getOpcode()) { 15498 case BO_PtrMemD: 15499 case BO_PtrMemI: 15500 case BO_Assign: 15501 case BO_MulAssign: 15502 case BO_DivAssign: 15503 case BO_RemAssign: 15504 case BO_AddAssign: 15505 case BO_SubAssign: 15506 case BO_ShlAssign: 15507 case BO_ShrAssign: 15508 case BO_AndAssign: 15509 case BO_XorAssign: 15510 case BO_OrAssign: 15511 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15512 // constant expressions, but they can never be ICEs because an ICE cannot 15513 // contain an lvalue operand. 15514 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15515 15516 case BO_Mul: 15517 case BO_Div: 15518 case BO_Rem: 15519 case BO_Add: 15520 case BO_Sub: 15521 case BO_Shl: 15522 case BO_Shr: 15523 case BO_LT: 15524 case BO_GT: 15525 case BO_LE: 15526 case BO_GE: 15527 case BO_EQ: 15528 case BO_NE: 15529 case BO_And: 15530 case BO_Xor: 15531 case BO_Or: 15532 case BO_Comma: 15533 case BO_Cmp: { 15534 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15535 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15536 if (Exp->getOpcode() == BO_Div || 15537 Exp->getOpcode() == BO_Rem) { 15538 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15539 // we don't evaluate one. 15540 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15541 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15542 if (REval == 0) 15543 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15544 if (REval.isSigned() && REval.isAllOnes()) { 15545 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15546 if (LEval.isMinSignedValue()) 15547 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15548 } 15549 } 15550 } 15551 if (Exp->getOpcode() == BO_Comma) { 15552 if (Ctx.getLangOpts().C99) { 15553 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15554 // if it isn't evaluated. 15555 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15556 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15557 } else { 15558 // In both C89 and C++, commas in ICEs are illegal. 15559 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15560 } 15561 } 15562 return Worst(LHSResult, RHSResult); 15563 } 15564 case BO_LAnd: 15565 case BO_LOr: { 15566 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15567 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15568 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15569 // Rare case where the RHS has a comma "side-effect"; we need 15570 // to actually check the condition to see whether the side 15571 // with the comma is evaluated. 15572 if ((Exp->getOpcode() == BO_LAnd) != 15573 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15574 return RHSResult; 15575 return NoDiag(); 15576 } 15577 15578 return Worst(LHSResult, RHSResult); 15579 } 15580 } 15581 llvm_unreachable("invalid binary operator kind"); 15582 } 15583 case Expr::ImplicitCastExprClass: 15584 case Expr::CStyleCastExprClass: 15585 case Expr::CXXFunctionalCastExprClass: 15586 case Expr::CXXStaticCastExprClass: 15587 case Expr::CXXReinterpretCastExprClass: 15588 case Expr::CXXConstCastExprClass: 15589 case Expr::ObjCBridgedCastExprClass: { 15590 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15591 if (isa<ExplicitCastExpr>(E)) { 15592 if (const FloatingLiteral *FL 15593 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15594 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15595 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15596 APSInt IgnoredVal(DestWidth, !DestSigned); 15597 bool Ignored; 15598 // If the value does not fit in the destination type, the behavior is 15599 // undefined, so we are not required to treat it as a constant 15600 // expression. 15601 if (FL->getValue().convertToInteger(IgnoredVal, 15602 llvm::APFloat::rmTowardZero, 15603 &Ignored) & APFloat::opInvalidOp) 15604 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15605 return NoDiag(); 15606 } 15607 } 15608 switch (cast<CastExpr>(E)->getCastKind()) { 15609 case CK_LValueToRValue: 15610 case CK_AtomicToNonAtomic: 15611 case CK_NonAtomicToAtomic: 15612 case CK_NoOp: 15613 case CK_IntegralToBoolean: 15614 case CK_IntegralCast: 15615 return CheckICE(SubExpr, Ctx); 15616 default: 15617 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15618 } 15619 } 15620 case Expr::BinaryConditionalOperatorClass: { 15621 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15622 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15623 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15624 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15625 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15626 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15627 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15628 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15629 return FalseResult; 15630 } 15631 case Expr::ConditionalOperatorClass: { 15632 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15633 // If the condition (ignoring parens) is a __builtin_constant_p call, 15634 // then only the true side is actually considered in an integer constant 15635 // expression, and it is fully evaluated. This is an important GNU 15636 // extension. See GCC PR38377 for discussion. 15637 if (const CallExpr *CallCE 15638 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15639 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15640 return CheckEvalInICE(E, Ctx); 15641 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15642 if (CondResult.Kind == IK_NotICE) 15643 return CondResult; 15644 15645 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15646 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15647 15648 if (TrueResult.Kind == IK_NotICE) 15649 return TrueResult; 15650 if (FalseResult.Kind == IK_NotICE) 15651 return FalseResult; 15652 if (CondResult.Kind == IK_ICEIfUnevaluated) 15653 return CondResult; 15654 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15655 return NoDiag(); 15656 // Rare case where the diagnostics depend on which side is evaluated 15657 // Note that if we get here, CondResult is 0, and at least one of 15658 // TrueResult and FalseResult is non-zero. 15659 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15660 return FalseResult; 15661 return TrueResult; 15662 } 15663 case Expr::CXXDefaultArgExprClass: 15664 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15665 case Expr::CXXDefaultInitExprClass: 15666 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15667 case Expr::ChooseExprClass: { 15668 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15669 } 15670 case Expr::BuiltinBitCastExprClass: { 15671 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15672 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15673 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15674 } 15675 } 15676 15677 llvm_unreachable("Invalid StmtClass!"); 15678 } 15679 15680 /// Evaluate an expression as a C++11 integral constant expression. 15681 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15682 const Expr *E, 15683 llvm::APSInt *Value, 15684 SourceLocation *Loc) { 15685 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15686 if (Loc) *Loc = E->getExprLoc(); 15687 return false; 15688 } 15689 15690 APValue Result; 15691 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15692 return false; 15693 15694 if (!Result.isInt()) { 15695 if (Loc) *Loc = E->getExprLoc(); 15696 return false; 15697 } 15698 15699 if (Value) *Value = Result.getInt(); 15700 return true; 15701 } 15702 15703 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15704 SourceLocation *Loc) const { 15705 assert(!isValueDependent() && 15706 "Expression evaluator can't be called on a dependent expression."); 15707 15708 if (Ctx.getLangOpts().CPlusPlus11) 15709 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15710 15711 ICEDiag D = CheckICE(this, Ctx); 15712 if (D.Kind != IK_ICE) { 15713 if (Loc) *Loc = D.Loc; 15714 return false; 15715 } 15716 return true; 15717 } 15718 15719 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15720 SourceLocation *Loc, 15721 bool isEvaluated) const { 15722 if (isValueDependent()) { 15723 // Expression evaluator can't succeed on a dependent expression. 15724 return None; 15725 } 15726 15727 APSInt Value; 15728 15729 if (Ctx.getLangOpts().CPlusPlus11) { 15730 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15731 return Value; 15732 return None; 15733 } 15734 15735 if (!isIntegerConstantExpr(Ctx, Loc)) 15736 return None; 15737 15738 // The only possible side-effects here are due to UB discovered in the 15739 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15740 // required to treat the expression as an ICE, so we produce the folded 15741 // value. 15742 EvalResult ExprResult; 15743 Expr::EvalStatus Status; 15744 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15745 Info.InConstantContext = true; 15746 15747 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15748 llvm_unreachable("ICE cannot be evaluated!"); 15749 15750 return ExprResult.Val.getInt(); 15751 } 15752 15753 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15754 assert(!isValueDependent() && 15755 "Expression evaluator can't be called on a dependent expression."); 15756 15757 return CheckICE(this, Ctx).Kind == IK_ICE; 15758 } 15759 15760 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15761 SourceLocation *Loc) const { 15762 assert(!isValueDependent() && 15763 "Expression evaluator can't be called on a dependent expression."); 15764 15765 // We support this checking in C++98 mode in order to diagnose compatibility 15766 // issues. 15767 assert(Ctx.getLangOpts().CPlusPlus); 15768 15769 // Build evaluation settings. 15770 Expr::EvalStatus Status; 15771 SmallVector<PartialDiagnosticAt, 8> Diags; 15772 Status.Diag = &Diags; 15773 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15774 15775 APValue Scratch; 15776 bool IsConstExpr = 15777 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15778 // FIXME: We don't produce a diagnostic for this, but the callers that 15779 // call us on arbitrary full-expressions should generally not care. 15780 Info.discardCleanups() && !Status.HasSideEffects; 15781 15782 if (!Diags.empty()) { 15783 IsConstExpr = false; 15784 if (Loc) *Loc = Diags[0].first; 15785 } else if (!IsConstExpr) { 15786 // FIXME: This shouldn't happen. 15787 if (Loc) *Loc = getExprLoc(); 15788 } 15789 15790 return IsConstExpr; 15791 } 15792 15793 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15794 const FunctionDecl *Callee, 15795 ArrayRef<const Expr*> Args, 15796 const Expr *This) const { 15797 assert(!isValueDependent() && 15798 "Expression evaluator can't be called on a dependent expression."); 15799 15800 Expr::EvalStatus Status; 15801 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15802 Info.InConstantContext = true; 15803 15804 LValue ThisVal; 15805 const LValue *ThisPtr = nullptr; 15806 if (This) { 15807 #ifndef NDEBUG 15808 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15809 assert(MD && "Don't provide `this` for non-methods."); 15810 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15811 #endif 15812 if (!This->isValueDependent() && 15813 EvaluateObjectArgument(Info, This, ThisVal) && 15814 !Info.EvalStatus.HasSideEffects) 15815 ThisPtr = &ThisVal; 15816 15817 // Ignore any side-effects from a failed evaluation. This is safe because 15818 // they can't interfere with any other argument evaluation. 15819 Info.EvalStatus.HasSideEffects = false; 15820 } 15821 15822 CallRef Call = Info.CurrentCall->createCall(Callee); 15823 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15824 I != E; ++I) { 15825 unsigned Idx = I - Args.begin(); 15826 if (Idx >= Callee->getNumParams()) 15827 break; 15828 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15829 if ((*I)->isValueDependent() || 15830 !EvaluateCallArg(PVD, *I, Call, Info) || 15831 Info.EvalStatus.HasSideEffects) { 15832 // If evaluation fails, throw away the argument entirely. 15833 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15834 *Slot = APValue(); 15835 } 15836 15837 // Ignore any side-effects from a failed evaluation. This is safe because 15838 // they can't interfere with any other argument evaluation. 15839 Info.EvalStatus.HasSideEffects = false; 15840 } 15841 15842 // Parameter cleanups happen in the caller and are not part of this 15843 // evaluation. 15844 Info.discardCleanups(); 15845 Info.EvalStatus.HasSideEffects = false; 15846 15847 // Build fake call to Callee. 15848 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15849 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15850 FullExpressionRAII Scope(Info); 15851 return Evaluate(Value, Info, this) && Scope.destroy() && 15852 !Info.EvalStatus.HasSideEffects; 15853 } 15854 15855 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15856 SmallVectorImpl< 15857 PartialDiagnosticAt> &Diags) { 15858 // FIXME: It would be useful to check constexpr function templates, but at the 15859 // moment the constant expression evaluator cannot cope with the non-rigorous 15860 // ASTs which we build for dependent expressions. 15861 if (FD->isDependentContext()) 15862 return true; 15863 15864 Expr::EvalStatus Status; 15865 Status.Diag = &Diags; 15866 15867 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15868 Info.InConstantContext = true; 15869 Info.CheckingPotentialConstantExpression = true; 15870 15871 // The constexpr VM attempts to compile all methods to bytecode here. 15872 if (Info.EnableNewConstInterp) { 15873 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15874 return Diags.empty(); 15875 } 15876 15877 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15878 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15879 15880 // Fabricate an arbitrary expression on the stack and pretend that it 15881 // is a temporary being used as the 'this' pointer. 15882 LValue This; 15883 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15884 This.set({&VIE, Info.CurrentCall->Index}); 15885 15886 ArrayRef<const Expr*> Args; 15887 15888 APValue Scratch; 15889 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15890 // Evaluate the call as a constant initializer, to allow the construction 15891 // of objects of non-literal types. 15892 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15893 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15894 } else { 15895 SourceLocation Loc = FD->getLocation(); 15896 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15897 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15898 } 15899 15900 return Diags.empty(); 15901 } 15902 15903 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15904 const FunctionDecl *FD, 15905 SmallVectorImpl< 15906 PartialDiagnosticAt> &Diags) { 15907 assert(!E->isValueDependent() && 15908 "Expression evaluator can't be called on a dependent expression."); 15909 15910 Expr::EvalStatus Status; 15911 Status.Diag = &Diags; 15912 15913 EvalInfo Info(FD->getASTContext(), Status, 15914 EvalInfo::EM_ConstantExpressionUnevaluated); 15915 Info.InConstantContext = true; 15916 Info.CheckingPotentialConstantExpression = true; 15917 15918 // Fabricate a call stack frame to give the arguments a plausible cover story. 15919 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15920 15921 APValue ResultScratch; 15922 Evaluate(ResultScratch, Info, E); 15923 return Diags.empty(); 15924 } 15925 15926 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15927 unsigned Type) const { 15928 if (!getType()->isPointerType()) 15929 return false; 15930 15931 Expr::EvalStatus Status; 15932 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15933 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15934 } 15935 15936 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, 15937 EvalInfo &Info) { 15938 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) 15939 return false; 15940 15941 LValue String; 15942 15943 if (!EvaluatePointer(E, String, Info)) 15944 return false; 15945 15946 QualType CharTy = E->getType()->getPointeeType(); 15947 15948 // Fast path: if it's a string literal, search the string value. 15949 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 15950 String.getLValueBase().dyn_cast<const Expr *>())) { 15951 StringRef Str = S->getBytes(); 15952 int64_t Off = String.Offset.getQuantity(); 15953 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 15954 S->getCharByteWidth() == 1 && 15955 // FIXME: Add fast-path for wchar_t too. 15956 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 15957 Str = Str.substr(Off); 15958 15959 StringRef::size_type Pos = Str.find(0); 15960 if (Pos != StringRef::npos) 15961 Str = Str.substr(0, Pos); 15962 15963 Result = Str.size(); 15964 return true; 15965 } 15966 15967 // Fall through to slow path. 15968 } 15969 15970 // Slow path: scan the bytes of the string looking for the terminating 0. 15971 for (uint64_t Strlen = 0; /**/; ++Strlen) { 15972 APValue Char; 15973 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 15974 !Char.isInt()) 15975 return false; 15976 if (!Char.getInt()) { 15977 Result = Strlen; 15978 return true; 15979 } 15980 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 15981 return false; 15982 } 15983 } 15984 15985 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { 15986 Expr::EvalStatus Status; 15987 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15988 return EvaluateBuiltinStrLen(this, Result, Info); 15989 } 15990