1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 return B.getType(); 83 } 84 85 /// Get an LValue path entry, which is known to not be an array index, as a 86 /// field declaration. 87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 } 90 /// Get an LValue path entry, which is known to not be an array index, as a 91 /// base class declaration. 92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 } 95 /// Determine whether this LValue path entry for a base class names a virtual 96 /// base class. 97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 return E.getAsBaseOrMember().getInt(); 99 } 100 101 /// Given an expression, determine the type used to store the result of 102 /// evaluating that expression. 103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 if (E->isRValue()) 105 return E->getType(); 106 return Ctx.getLValueReferenceType(E->getType()); 107 } 108 109 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 112 return DirectCallee->getAttr<AllocSizeAttr>(); 113 if (const Decl *IndirectCallee = CE->getCalleeDecl()) 114 return IndirectCallee->getAttr<AllocSizeAttr>(); 115 return nullptr; 116 } 117 118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 119 /// This will look through a single cast. 120 /// 121 /// Returns null if we couldn't unwrap a function with alloc_size. 122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 123 if (!E->getType()->isPointerType()) 124 return nullptr; 125 126 E = E->IgnoreParens(); 127 // If we're doing a variable assignment from e.g. malloc(N), there will 128 // probably be a cast of some kind. In exotic cases, we might also see a 129 // top-level ExprWithCleanups. Ignore them either way. 130 if (const auto *FE = dyn_cast<FullExpr>(E)) 131 E = FE->getSubExpr()->IgnoreParens(); 132 133 if (const auto *Cast = dyn_cast<CastExpr>(E)) 134 E = Cast->getSubExpr()->IgnoreParens(); 135 136 if (const auto *CE = dyn_cast<CallExpr>(E)) 137 return getAllocSizeAttr(CE) ? CE : nullptr; 138 return nullptr; 139 } 140 141 /// Determines whether or not the given Base contains a call to a function 142 /// with the alloc_size attribute. 143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 144 const auto *E = Base.dyn_cast<const Expr *>(); 145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 146 } 147 148 /// Determines whether the given kind of constant expression is only ever 149 /// used for name mangling. If so, it's permitted to reference things that we 150 /// can't generate code for (in particular, dllimported functions). 151 static bool isForManglingOnly(ConstantExprKind Kind) { 152 switch (Kind) { 153 case ConstantExprKind::Normal: 154 case ConstantExprKind::ClassTemplateArgument: 155 case ConstantExprKind::ImmediateInvocation: 156 // Note that non-type template arguments of class type are emitted as 157 // template parameter objects. 158 return false; 159 160 case ConstantExprKind::NonClassTemplateArgument: 161 return true; 162 } 163 llvm_unreachable("unknown ConstantExprKind"); 164 } 165 166 static bool isTemplateArgument(ConstantExprKind Kind) { 167 switch (Kind) { 168 case ConstantExprKind::Normal: 169 case ConstantExprKind::ImmediateInvocation: 170 return false; 171 172 case ConstantExprKind::ClassTemplateArgument: 173 case ConstantExprKind::NonClassTemplateArgument: 174 return true; 175 } 176 llvm_unreachable("unknown ConstantExprKind"); 177 } 178 179 /// The bound to claim that an array of unknown bound has. 180 /// The value in MostDerivedArraySize is undefined in this case. So, set it 181 /// to an arbitrary value that's likely to loudly break things if it's used. 182 static const uint64_t AssumedSizeForUnsizedArray = 183 std::numeric_limits<uint64_t>::max() / 2; 184 185 /// Determines if an LValue with the given LValueBase will have an unsized 186 /// array in its designator. 187 /// Find the path length and type of the most-derived subobject in the given 188 /// path, and find the size of the containing array, if any. 189 static unsigned 190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 191 ArrayRef<APValue::LValuePathEntry> Path, 192 uint64_t &ArraySize, QualType &Type, bool &IsArray, 193 bool &FirstEntryIsUnsizedArray) { 194 // This only accepts LValueBases from APValues, and APValues don't support 195 // arrays that lack size info. 196 assert(!isBaseAnAllocSizeCall(Base) && 197 "Unsized arrays shouldn't appear here"); 198 unsigned MostDerivedLength = 0; 199 Type = getType(Base); 200 201 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 202 if (Type->isArrayType()) { 203 const ArrayType *AT = Ctx.getAsArrayType(Type); 204 Type = AT->getElementType(); 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 209 ArraySize = CAT->getSize().getZExtValue(); 210 } else { 211 assert(I == 0 && "unexpected unsized array designator"); 212 FirstEntryIsUnsizedArray = true; 213 ArraySize = AssumedSizeForUnsizedArray; 214 } 215 } else if (Type->isAnyComplexType()) { 216 const ComplexType *CT = Type->castAs<ComplexType>(); 217 Type = CT->getElementType(); 218 ArraySize = 2; 219 MostDerivedLength = I + 1; 220 IsArray = true; 221 } else if (const FieldDecl *FD = getAsField(Path[I])) { 222 Type = FD->getType(); 223 ArraySize = 0; 224 MostDerivedLength = I + 1; 225 IsArray = false; 226 } else { 227 // Path[I] describes a base class. 228 ArraySize = 0; 229 IsArray = false; 230 } 231 } 232 return MostDerivedLength; 233 } 234 235 /// A path from a glvalue to a subobject of that glvalue. 236 struct SubobjectDesignator { 237 /// True if the subobject was named in a manner not supported by C++11. Such 238 /// lvalues can still be folded, but they are not core constant expressions 239 /// and we cannot perform lvalue-to-rvalue conversions on them. 240 unsigned Invalid : 1; 241 242 /// Is this a pointer one past the end of an object? 243 unsigned IsOnePastTheEnd : 1; 244 245 /// Indicator of whether the first entry is an unsized array. 246 unsigned FirstEntryIsAnUnsizedArray : 1; 247 248 /// Indicator of whether the most-derived object is an array element. 249 unsigned MostDerivedIsArrayElement : 1; 250 251 /// The length of the path to the most-derived object of which this is a 252 /// subobject. 253 unsigned MostDerivedPathLength : 28; 254 255 /// The size of the array of which the most-derived object is an element. 256 /// This will always be 0 if the most-derived object is not an array 257 /// element. 0 is not an indicator of whether or not the most-derived object 258 /// is an array, however, because 0-length arrays are allowed. 259 /// 260 /// If the current array is an unsized array, the value of this is 261 /// undefined. 262 uint64_t MostDerivedArraySize; 263 264 /// The type of the most derived object referred to by this address. 265 QualType MostDerivedType; 266 267 typedef APValue::LValuePathEntry PathEntry; 268 269 /// The entries on the path from the glvalue to the designated subobject. 270 SmallVector<PathEntry, 8> Entries; 271 272 SubobjectDesignator() : Invalid(true) {} 273 274 explicit SubobjectDesignator(QualType T) 275 : Invalid(false), IsOnePastTheEnd(false), 276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 277 MostDerivedPathLength(0), MostDerivedArraySize(0), 278 MostDerivedType(T) {} 279 280 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 283 MostDerivedPathLength(0), MostDerivedArraySize(0) { 284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 285 if (!Invalid) { 286 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 287 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 289 if (V.getLValueBase()) { 290 bool IsArray = false; 291 bool FirstIsUnsizedArray = false; 292 MostDerivedPathLength = findMostDerivedSubobject( 293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 294 MostDerivedType, IsArray, FirstIsUnsizedArray); 295 MostDerivedIsArrayElement = IsArray; 296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 297 } 298 } 299 } 300 301 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 302 unsigned NewLength) { 303 if (Invalid) 304 return; 305 306 assert(Base && "cannot truncate path for null pointer"); 307 assert(NewLength <= Entries.size() && "not a truncation"); 308 309 if (NewLength == Entries.size()) 310 return; 311 Entries.resize(NewLength); 312 313 bool IsArray = false; 314 bool FirstIsUnsizedArray = false; 315 MostDerivedPathLength = findMostDerivedSubobject( 316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 317 FirstIsUnsizedArray); 318 MostDerivedIsArrayElement = IsArray; 319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 320 } 321 322 void setInvalid() { 323 Invalid = true; 324 Entries.clear(); 325 } 326 327 /// Determine whether the most derived subobject is an array without a 328 /// known bound. 329 bool isMostDerivedAnUnsizedArray() const { 330 assert(!Invalid && "Calling this makes no sense on invalid designators"); 331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 332 } 333 334 /// Determine what the most derived array's size is. Results in an assertion 335 /// failure if the most derived array lacks a size. 336 uint64_t getMostDerivedArraySize() const { 337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 338 return MostDerivedArraySize; 339 } 340 341 /// Determine whether this is a one-past-the-end pointer. 342 bool isOnePastTheEnd() const { 343 assert(!Invalid); 344 if (IsOnePastTheEnd) 345 return true; 346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 348 MostDerivedArraySize) 349 return true; 350 return false; 351 } 352 353 /// Get the range of valid index adjustments in the form 354 /// {maximum value that can be subtracted from this pointer, 355 /// maximum value that can be added to this pointer} 356 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 357 if (Invalid || isMostDerivedAnUnsizedArray()) 358 return {0, 0}; 359 360 // [expr.add]p4: For the purposes of these operators, a pointer to a 361 // nonarray object behaves the same as a pointer to the first element of 362 // an array of length one with the type of the object as its element type. 363 bool IsArray = MostDerivedPathLength == Entries.size() && 364 MostDerivedIsArrayElement; 365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 366 : (uint64_t)IsOnePastTheEnd; 367 uint64_t ArraySize = 368 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 369 return {ArrayIndex, ArraySize - ArrayIndex}; 370 } 371 372 /// Check that this refers to a valid subobject. 373 bool isValidSubobject() const { 374 if (Invalid) 375 return false; 376 return !isOnePastTheEnd(); 377 } 378 /// Check that this refers to a valid subobject, and if not, produce a 379 /// relevant diagnostic and set the designator as invalid. 380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 381 382 /// Get the type of the designated object. 383 QualType getType(ASTContext &Ctx) const { 384 assert(!Invalid && "invalid designator has no subobject type"); 385 return MostDerivedPathLength == Entries.size() 386 ? MostDerivedType 387 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 388 } 389 390 /// Update this designator to refer to the first element within this array. 391 void addArrayUnchecked(const ConstantArrayType *CAT) { 392 Entries.push_back(PathEntry::ArrayIndex(0)); 393 394 // This is a most-derived object. 395 MostDerivedType = CAT->getElementType(); 396 MostDerivedIsArrayElement = true; 397 MostDerivedArraySize = CAT->getSize().getZExtValue(); 398 MostDerivedPathLength = Entries.size(); 399 } 400 /// Update this designator to refer to the first element within the array of 401 /// elements of type T. This is an array of unknown size. 402 void addUnsizedArrayUnchecked(QualType ElemTy) { 403 Entries.push_back(PathEntry::ArrayIndex(0)); 404 405 MostDerivedType = ElemTy; 406 MostDerivedIsArrayElement = true; 407 // The value in MostDerivedArraySize is undefined in this case. So, set it 408 // to an arbitrary value that's likely to loudly break things if it's 409 // used. 410 MostDerivedArraySize = AssumedSizeForUnsizedArray; 411 MostDerivedPathLength = Entries.size(); 412 } 413 /// Update this designator to refer to the given base or member of this 414 /// object. 415 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 417 418 // If this isn't a base class, it's a new most-derived object. 419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 420 MostDerivedType = FD->getType(); 421 MostDerivedIsArrayElement = false; 422 MostDerivedArraySize = 0; 423 MostDerivedPathLength = Entries.size(); 424 } 425 } 426 /// Update this designator to refer to the given complex component. 427 void addComplexUnchecked(QualType EltTy, bool Imag) { 428 Entries.push_back(PathEntry::ArrayIndex(Imag)); 429 430 // This is technically a most-derived object, though in practice this 431 // is unlikely to matter. 432 MostDerivedType = EltTy; 433 MostDerivedIsArrayElement = true; 434 MostDerivedArraySize = 2; 435 MostDerivedPathLength = Entries.size(); 436 } 437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 439 const APSInt &N); 440 /// Add N to the address of this subobject. 441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 442 if (Invalid || !N) return; 443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 444 if (isMostDerivedAnUnsizedArray()) { 445 diagnoseUnsizedArrayPointerArithmetic(Info, E); 446 // Can't verify -- trust that the user is doing the right thing (or if 447 // not, trust that the caller will catch the bad behavior). 448 // FIXME: Should we reject if this overflows, at least? 449 Entries.back() = PathEntry::ArrayIndex( 450 Entries.back().getAsArrayIndex() + TruncatedN); 451 return; 452 } 453 454 // [expr.add]p4: For the purposes of these operators, a pointer to a 455 // nonarray object behaves the same as a pointer to the first element of 456 // an array of length one with the type of the object as its element type. 457 bool IsArray = MostDerivedPathLength == Entries.size() && 458 MostDerivedIsArrayElement; 459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 460 : (uint64_t)IsOnePastTheEnd; 461 uint64_t ArraySize = 462 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 463 464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 465 // Calculate the actual index in a wide enough type, so we can include 466 // it in the note. 467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 468 (llvm::APInt&)N += ArrayIndex; 469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 470 diagnosePointerArithmetic(Info, E, N); 471 setInvalid(); 472 return; 473 } 474 475 ArrayIndex += TruncatedN; 476 assert(ArrayIndex <= ArraySize && 477 "bounds check succeeded for out-of-bounds index"); 478 479 if (IsArray) 480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 481 else 482 IsOnePastTheEnd = (ArrayIndex != 0); 483 } 484 }; 485 486 /// A scope at the end of which an object can need to be destroyed. 487 enum class ScopeKind { 488 Block, 489 FullExpression, 490 Call 491 }; 492 493 /// A reference to a particular call and its arguments. 494 struct CallRef { 495 CallRef() : OrigCallee(), CallIndex(0), Version() {} 496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 498 499 explicit operator bool() const { return OrigCallee; } 500 501 /// Get the parameter that the caller initialized, corresponding to the 502 /// given parameter in the callee. 503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 505 : PVD; 506 } 507 508 /// The callee at the point where the arguments were evaluated. This might 509 /// be different from the actual callee (a different redeclaration, or a 510 /// virtual override), but this function's parameters are the ones that 511 /// appear in the parameter map. 512 const FunctionDecl *OrigCallee; 513 /// The call index of the frame that holds the argument values. 514 unsigned CallIndex; 515 /// The version of the parameters corresponding to this call. 516 unsigned Version; 517 }; 518 519 /// A stack frame in the constexpr call stack. 520 class CallStackFrame : public interp::Frame { 521 public: 522 EvalInfo &Info; 523 524 /// Parent - The caller of this stack frame. 525 CallStackFrame *Caller; 526 527 /// Callee - The function which was called. 528 const FunctionDecl *Callee; 529 530 /// This - The binding for the this pointer in this call, if any. 531 const LValue *This; 532 533 /// Information on how to find the arguments to this call. Our arguments 534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 535 /// key and this value as the version. 536 CallRef Arguments; 537 538 /// Source location information about the default argument or default 539 /// initializer expression we're evaluating, if any. 540 CurrentSourceLocExprScope CurSourceLocExprScope; 541 542 // Note that we intentionally use std::map here so that references to 543 // values are stable. 544 typedef std::pair<const void *, unsigned> MapKeyTy; 545 typedef std::map<MapKeyTy, APValue> MapTy; 546 /// Temporaries - Temporary lvalues materialized within this stack frame. 547 MapTy Temporaries; 548 549 /// CallLoc - The location of the call expression for this call. 550 SourceLocation CallLoc; 551 552 /// Index - The call index of this call. 553 unsigned Index; 554 555 /// The stack of integers for tracking version numbers for temporaries. 556 SmallVector<unsigned, 2> TempVersionStack = {1}; 557 unsigned CurTempVersion = TempVersionStack.back(); 558 559 unsigned getTempVersion() const { return TempVersionStack.back(); } 560 561 void pushTempVersion() { 562 TempVersionStack.push_back(++CurTempVersion); 563 } 564 565 void popTempVersion() { 566 TempVersionStack.pop_back(); 567 } 568 569 CallRef createCall(const FunctionDecl *Callee) { 570 return {Callee, Index, ++CurTempVersion}; 571 } 572 573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 574 // on the overall stack usage of deeply-recursing constexpr evaluations. 575 // (We should cache this map rather than recomputing it repeatedly.) 576 // But let's try this and see how it goes; we can look into caching the map 577 // as a later change. 578 579 /// LambdaCaptureFields - Mapping from captured variables/this to 580 /// corresponding data members in the closure class. 581 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 582 FieldDecl *LambdaThisCaptureField; 583 584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 585 const FunctionDecl *Callee, const LValue *This, 586 CallRef Arguments); 587 ~CallStackFrame(); 588 589 // Return the temporary for Key whose version number is Version. 590 APValue *getTemporary(const void *Key, unsigned Version) { 591 MapKeyTy KV(Key, Version); 592 auto LB = Temporaries.lower_bound(KV); 593 if (LB != Temporaries.end() && LB->first == KV) 594 return &LB->second; 595 // Pair (Key,Version) wasn't found in the map. Check that no elements 596 // in the map have 'Key' as their key. 597 assert((LB == Temporaries.end() || LB->first.first != Key) && 598 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 599 "Element with key 'Key' found in map"); 600 return nullptr; 601 } 602 603 // Return the current temporary for Key in the map. 604 APValue *getCurrentTemporary(const void *Key) { 605 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 606 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 607 return &std::prev(UB)->second; 608 return nullptr; 609 } 610 611 // Return the version number of the current temporary for Key. 612 unsigned getCurrentTemporaryVersion(const void *Key) const { 613 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 614 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 615 return std::prev(UB)->first.second; 616 return 0; 617 } 618 619 /// Allocate storage for an object of type T in this stack frame. 620 /// Populates LV with a handle to the created object. Key identifies 621 /// the temporary within the stack frame, and must not be reused without 622 /// bumping the temporary version number. 623 template<typename KeyT> 624 APValue &createTemporary(const KeyT *Key, QualType T, 625 ScopeKind Scope, LValue &LV); 626 627 /// Allocate storage for a parameter of a function call made in this frame. 628 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 629 630 void describe(llvm::raw_ostream &OS) override; 631 632 Frame *getCaller() const override { return Caller; } 633 SourceLocation getCallLocation() const override { return CallLoc; } 634 const FunctionDecl *getCallee() const override { return Callee; } 635 636 bool isStdFunction() const { 637 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 638 if (DC->isStdNamespace()) 639 return true; 640 return false; 641 } 642 643 private: 644 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 645 ScopeKind Scope); 646 }; 647 648 /// Temporarily override 'this'. 649 class ThisOverrideRAII { 650 public: 651 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 652 : Frame(Frame), OldThis(Frame.This) { 653 if (Enable) 654 Frame.This = NewThis; 655 } 656 ~ThisOverrideRAII() { 657 Frame.This = OldThis; 658 } 659 private: 660 CallStackFrame &Frame; 661 const LValue *OldThis; 662 }; 663 } 664 665 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 666 const LValue &This, QualType ThisType); 667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 668 APValue::LValueBase LVBase, APValue &Value, 669 QualType T); 670 671 namespace { 672 /// A cleanup, and a flag indicating whether it is lifetime-extended. 673 class Cleanup { 674 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 675 APValue::LValueBase Base; 676 QualType T; 677 678 public: 679 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 680 ScopeKind Scope) 681 : Value(Val, Scope), Base(Base), T(T) {} 682 683 /// Determine whether this cleanup should be performed at the end of the 684 /// given kind of scope. 685 bool isDestroyedAtEndOf(ScopeKind K) const { 686 return (int)Value.getInt() >= (int)K; 687 } 688 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 689 if (RunDestructors) { 690 SourceLocation Loc; 691 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 692 Loc = VD->getLocation(); 693 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 694 Loc = E->getExprLoc(); 695 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 696 } 697 *Value.getPointer() = APValue(); 698 return true; 699 } 700 701 bool hasSideEffect() { 702 return T.isDestructedType(); 703 } 704 }; 705 706 /// A reference to an object whose construction we are currently evaluating. 707 struct ObjectUnderConstruction { 708 APValue::LValueBase Base; 709 ArrayRef<APValue::LValuePathEntry> Path; 710 friend bool operator==(const ObjectUnderConstruction &LHS, 711 const ObjectUnderConstruction &RHS) { 712 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 713 } 714 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 715 return llvm::hash_combine(Obj.Base, Obj.Path); 716 } 717 }; 718 enum class ConstructionPhase { 719 None, 720 Bases, 721 AfterBases, 722 AfterFields, 723 Destroying, 724 DestroyingBases 725 }; 726 } 727 728 namespace llvm { 729 template<> struct DenseMapInfo<ObjectUnderConstruction> { 730 using Base = DenseMapInfo<APValue::LValueBase>; 731 static ObjectUnderConstruction getEmptyKey() { 732 return {Base::getEmptyKey(), {}}; } 733 static ObjectUnderConstruction getTombstoneKey() { 734 return {Base::getTombstoneKey(), {}}; 735 } 736 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 737 return hash_value(Object); 738 } 739 static bool isEqual(const ObjectUnderConstruction &LHS, 740 const ObjectUnderConstruction &RHS) { 741 return LHS == RHS; 742 } 743 }; 744 } 745 746 namespace { 747 /// A dynamically-allocated heap object. 748 struct DynAlloc { 749 /// The value of this heap-allocated object. 750 APValue Value; 751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 752 /// or a CallExpr (the latter is for direct calls to operator new inside 753 /// std::allocator<T>::allocate). 754 const Expr *AllocExpr = nullptr; 755 756 enum Kind { 757 New, 758 ArrayNew, 759 StdAllocator 760 }; 761 762 /// Get the kind of the allocation. This must match between allocation 763 /// and deallocation. 764 Kind getKind() const { 765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 766 return NE->isArray() ? ArrayNew : New; 767 assert(isa<CallExpr>(AllocExpr)); 768 return StdAllocator; 769 } 770 }; 771 772 struct DynAllocOrder { 773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 774 return L.getIndex() < R.getIndex(); 775 } 776 }; 777 778 /// EvalInfo - This is a private struct used by the evaluator to capture 779 /// information about a subexpression as it is folded. It retains information 780 /// about the AST context, but also maintains information about the folded 781 /// expression. 782 /// 783 /// If an expression could be evaluated, it is still possible it is not a C 784 /// "integer constant expression" or constant expression. If not, this struct 785 /// captures information about how and why not. 786 /// 787 /// One bit of information passed *into* the request for constant folding 788 /// indicates whether the subexpression is "evaluated" or not according to C 789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 790 /// evaluate the expression regardless of what the RHS is, but C only allows 791 /// certain things in certain situations. 792 class EvalInfo : public interp::State { 793 public: 794 ASTContext &Ctx; 795 796 /// EvalStatus - Contains information about the evaluation. 797 Expr::EvalStatus &EvalStatus; 798 799 /// CurrentCall - The top of the constexpr call stack. 800 CallStackFrame *CurrentCall; 801 802 /// CallStackDepth - The number of calls in the call stack right now. 803 unsigned CallStackDepth; 804 805 /// NextCallIndex - The next call index to assign. 806 unsigned NextCallIndex; 807 808 /// StepsLeft - The remaining number of evaluation steps we're permitted 809 /// to perform. This is essentially a limit for the number of statements 810 /// we will evaluate. 811 unsigned StepsLeft; 812 813 /// Enable the experimental new constant interpreter. If an expression is 814 /// not supported by the interpreter, an error is triggered. 815 bool EnableNewConstInterp; 816 817 /// BottomFrame - The frame in which evaluation started. This must be 818 /// initialized after CurrentCall and CallStackDepth. 819 CallStackFrame BottomFrame; 820 821 /// A stack of values whose lifetimes end at the end of some surrounding 822 /// evaluation frame. 823 llvm::SmallVector<Cleanup, 16> CleanupStack; 824 825 /// EvaluatingDecl - This is the declaration whose initializer is being 826 /// evaluated, if any. 827 APValue::LValueBase EvaluatingDecl; 828 829 enum class EvaluatingDeclKind { 830 None, 831 /// We're evaluating the construction of EvaluatingDecl. 832 Ctor, 833 /// We're evaluating the destruction of EvaluatingDecl. 834 Dtor, 835 }; 836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 837 838 /// EvaluatingDeclValue - This is the value being constructed for the 839 /// declaration whose initializer is being evaluated, if any. 840 APValue *EvaluatingDeclValue; 841 842 /// Set of objects that are currently being constructed. 843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 844 ObjectsUnderConstruction; 845 846 /// Current heap allocations, along with the location where each was 847 /// allocated. We use std::map here because we need stable addresses 848 /// for the stored APValues. 849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 850 851 /// The number of heap allocations performed so far in this evaluation. 852 unsigned NumHeapAllocs = 0; 853 854 struct EvaluatingConstructorRAII { 855 EvalInfo &EI; 856 ObjectUnderConstruction Object; 857 bool DidInsert; 858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 859 bool HasBases) 860 : EI(EI), Object(Object) { 861 DidInsert = 862 EI.ObjectsUnderConstruction 863 .insert({Object, HasBases ? ConstructionPhase::Bases 864 : ConstructionPhase::AfterBases}) 865 .second; 866 } 867 void finishedConstructingBases() { 868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 869 } 870 void finishedConstructingFields() { 871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 872 } 873 ~EvaluatingConstructorRAII() { 874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 875 } 876 }; 877 878 struct EvaluatingDestructorRAII { 879 EvalInfo &EI; 880 ObjectUnderConstruction Object; 881 bool DidInsert; 882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 883 : EI(EI), Object(Object) { 884 DidInsert = EI.ObjectsUnderConstruction 885 .insert({Object, ConstructionPhase::Destroying}) 886 .second; 887 } 888 void startedDestroyingBases() { 889 EI.ObjectsUnderConstruction[Object] = 890 ConstructionPhase::DestroyingBases; 891 } 892 ~EvaluatingDestructorRAII() { 893 if (DidInsert) 894 EI.ObjectsUnderConstruction.erase(Object); 895 } 896 }; 897 898 ConstructionPhase 899 isEvaluatingCtorDtor(APValue::LValueBase Base, 900 ArrayRef<APValue::LValuePathEntry> Path) { 901 return ObjectsUnderConstruction.lookup({Base, Path}); 902 } 903 904 /// If we're currently speculatively evaluating, the outermost call stack 905 /// depth at which we can mutate state, otherwise 0. 906 unsigned SpeculativeEvaluationDepth = 0; 907 908 /// The current array initialization index, if we're performing array 909 /// initialization. 910 uint64_t ArrayInitIndex = -1; 911 912 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 913 /// notes attached to it will also be stored, otherwise they will not be. 914 bool HasActiveDiagnostic; 915 916 /// Have we emitted a diagnostic explaining why we couldn't constant 917 /// fold (not just why it's not strictly a constant expression)? 918 bool HasFoldFailureDiagnostic; 919 920 /// Whether or not we're in a context where the front end requires a 921 /// constant value. 922 bool InConstantContext; 923 924 /// Whether we're checking that an expression is a potential constant 925 /// expression. If so, do not fail on constructs that could become constant 926 /// later on (such as a use of an undefined global). 927 bool CheckingPotentialConstantExpression = false; 928 929 /// Whether we're checking for an expression that has undefined behavior. 930 /// If so, we will produce warnings if we encounter an operation that is 931 /// always undefined. 932 /// 933 /// Note that we still need to evaluate the expression normally when this 934 /// is set; this is used when evaluating ICEs in C. 935 bool CheckingForUndefinedBehavior = false; 936 937 enum EvaluationMode { 938 /// Evaluate as a constant expression. Stop if we find that the expression 939 /// is not a constant expression. 940 EM_ConstantExpression, 941 942 /// Evaluate as a constant expression. Stop if we find that the expression 943 /// is not a constant expression. Some expressions can be retried in the 944 /// optimizer if we don't constant fold them here, but in an unevaluated 945 /// context we try to fold them immediately since the optimizer never 946 /// gets a chance to look at it. 947 EM_ConstantExpressionUnevaluated, 948 949 /// Fold the expression to a constant. Stop if we hit a side-effect that 950 /// we can't model. 951 EM_ConstantFold, 952 953 /// Evaluate in any way we know how. Don't worry about side-effects that 954 /// can't be modeled. 955 EM_IgnoreSideEffects, 956 } EvalMode; 957 958 /// Are we checking whether the expression is a potential constant 959 /// expression? 960 bool checkingPotentialConstantExpression() const override { 961 return CheckingPotentialConstantExpression; 962 } 963 964 /// Are we checking an expression for overflow? 965 // FIXME: We should check for any kind of undefined or suspicious behavior 966 // in such constructs, not just overflow. 967 bool checkingForUndefinedBehavior() const override { 968 return CheckingForUndefinedBehavior; 969 } 970 971 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 972 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 973 CallStackDepth(0), NextCallIndex(1), 974 StepsLeft(C.getLangOpts().ConstexprStepLimit), 975 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 976 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 977 EvaluatingDecl((const ValueDecl *)nullptr), 978 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 979 HasFoldFailureDiagnostic(false), InConstantContext(false), 980 EvalMode(Mode) {} 981 982 ~EvalInfo() { 983 discardCleanups(); 984 } 985 986 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 987 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 988 EvaluatingDecl = Base; 989 IsEvaluatingDecl = EDK; 990 EvaluatingDeclValue = &Value; 991 } 992 993 bool CheckCallLimit(SourceLocation Loc) { 994 // Don't perform any constexpr calls (other than the call we're checking) 995 // when checking a potential constant expression. 996 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 997 return false; 998 if (NextCallIndex == 0) { 999 // NextCallIndex has wrapped around. 1000 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1001 return false; 1002 } 1003 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1004 return true; 1005 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1006 << getLangOpts().ConstexprCallDepth; 1007 return false; 1008 } 1009 1010 std::pair<CallStackFrame *, unsigned> 1011 getCallFrameAndDepth(unsigned CallIndex) { 1012 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1013 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1014 // be null in this loop. 1015 unsigned Depth = CallStackDepth; 1016 CallStackFrame *Frame = CurrentCall; 1017 while (Frame->Index > CallIndex) { 1018 Frame = Frame->Caller; 1019 --Depth; 1020 } 1021 if (Frame->Index == CallIndex) 1022 return {Frame, Depth}; 1023 return {nullptr, 0}; 1024 } 1025 1026 bool nextStep(const Stmt *S) { 1027 if (!StepsLeft) { 1028 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1029 return false; 1030 } 1031 --StepsLeft; 1032 return true; 1033 } 1034 1035 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1036 1037 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1038 Optional<DynAlloc*> Result; 1039 auto It = HeapAllocs.find(DA); 1040 if (It != HeapAllocs.end()) 1041 Result = &It->second; 1042 return Result; 1043 } 1044 1045 /// Get the allocated storage for the given parameter of the given call. 1046 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1047 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1048 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1049 : nullptr; 1050 } 1051 1052 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1053 struct StdAllocatorCaller { 1054 unsigned FrameIndex; 1055 QualType ElemType; 1056 explicit operator bool() const { return FrameIndex != 0; }; 1057 }; 1058 1059 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1060 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1061 Call = Call->Caller) { 1062 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1063 if (!MD) 1064 continue; 1065 const IdentifierInfo *FnII = MD->getIdentifier(); 1066 if (!FnII || !FnII->isStr(FnName)) 1067 continue; 1068 1069 const auto *CTSD = 1070 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1071 if (!CTSD) 1072 continue; 1073 1074 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1075 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1076 if (CTSD->isInStdNamespace() && ClassII && 1077 ClassII->isStr("allocator") && TAL.size() >= 1 && 1078 TAL[0].getKind() == TemplateArgument::Type) 1079 return {Call->Index, TAL[0].getAsType()}; 1080 } 1081 1082 return {}; 1083 } 1084 1085 void performLifetimeExtension() { 1086 // Disable the cleanups for lifetime-extended temporaries. 1087 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1088 CleanupStack.end(), 1089 [](Cleanup &C) { 1090 return !C.isDestroyedAtEndOf( 1091 ScopeKind::FullExpression); 1092 }), 1093 CleanupStack.end()); 1094 } 1095 1096 /// Throw away any remaining cleanups at the end of evaluation. If any 1097 /// cleanups would have had a side-effect, note that as an unmodeled 1098 /// side-effect and return false. Otherwise, return true. 1099 bool discardCleanups() { 1100 for (Cleanup &C : CleanupStack) { 1101 if (C.hasSideEffect() && !noteSideEffect()) { 1102 CleanupStack.clear(); 1103 return false; 1104 } 1105 } 1106 CleanupStack.clear(); 1107 return true; 1108 } 1109 1110 private: 1111 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1112 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1113 1114 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1115 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1116 1117 void setFoldFailureDiagnostic(bool Flag) override { 1118 HasFoldFailureDiagnostic = Flag; 1119 } 1120 1121 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1122 1123 ASTContext &getCtx() const override { return Ctx; } 1124 1125 // If we have a prior diagnostic, it will be noting that the expression 1126 // isn't a constant expression. This diagnostic is more important, 1127 // unless we require this evaluation to produce a constant expression. 1128 // 1129 // FIXME: We might want to show both diagnostics to the user in 1130 // EM_ConstantFold mode. 1131 bool hasPriorDiagnostic() override { 1132 if (!EvalStatus.Diag->empty()) { 1133 switch (EvalMode) { 1134 case EM_ConstantFold: 1135 case EM_IgnoreSideEffects: 1136 if (!HasFoldFailureDiagnostic) 1137 break; 1138 // We've already failed to fold something. Keep that diagnostic. 1139 LLVM_FALLTHROUGH; 1140 case EM_ConstantExpression: 1141 case EM_ConstantExpressionUnevaluated: 1142 setActiveDiagnostic(false); 1143 return true; 1144 } 1145 } 1146 return false; 1147 } 1148 1149 unsigned getCallStackDepth() override { return CallStackDepth; } 1150 1151 public: 1152 /// Should we continue evaluation after encountering a side-effect that we 1153 /// couldn't model? 1154 bool keepEvaluatingAfterSideEffect() { 1155 switch (EvalMode) { 1156 case EM_IgnoreSideEffects: 1157 return true; 1158 1159 case EM_ConstantExpression: 1160 case EM_ConstantExpressionUnevaluated: 1161 case EM_ConstantFold: 1162 // By default, assume any side effect might be valid in some other 1163 // evaluation of this expression from a different context. 1164 return checkingPotentialConstantExpression() || 1165 checkingForUndefinedBehavior(); 1166 } 1167 llvm_unreachable("Missed EvalMode case"); 1168 } 1169 1170 /// Note that we have had a side-effect, and determine whether we should 1171 /// keep evaluating. 1172 bool noteSideEffect() { 1173 EvalStatus.HasSideEffects = true; 1174 return keepEvaluatingAfterSideEffect(); 1175 } 1176 1177 /// Should we continue evaluation after encountering undefined behavior? 1178 bool keepEvaluatingAfterUndefinedBehavior() { 1179 switch (EvalMode) { 1180 case EM_IgnoreSideEffects: 1181 case EM_ConstantFold: 1182 return true; 1183 1184 case EM_ConstantExpression: 1185 case EM_ConstantExpressionUnevaluated: 1186 return checkingForUndefinedBehavior(); 1187 } 1188 llvm_unreachable("Missed EvalMode case"); 1189 } 1190 1191 /// Note that we hit something that was technically undefined behavior, but 1192 /// that we can evaluate past it (such as signed overflow or floating-point 1193 /// division by zero.) 1194 bool noteUndefinedBehavior() override { 1195 EvalStatus.HasUndefinedBehavior = true; 1196 return keepEvaluatingAfterUndefinedBehavior(); 1197 } 1198 1199 /// Should we continue evaluation as much as possible after encountering a 1200 /// construct which can't be reduced to a value? 1201 bool keepEvaluatingAfterFailure() const override { 1202 if (!StepsLeft) 1203 return false; 1204 1205 switch (EvalMode) { 1206 case EM_ConstantExpression: 1207 case EM_ConstantExpressionUnevaluated: 1208 case EM_ConstantFold: 1209 case EM_IgnoreSideEffects: 1210 return checkingPotentialConstantExpression() || 1211 checkingForUndefinedBehavior(); 1212 } 1213 llvm_unreachable("Missed EvalMode case"); 1214 } 1215 1216 /// Notes that we failed to evaluate an expression that other expressions 1217 /// directly depend on, and determine if we should keep evaluating. This 1218 /// should only be called if we actually intend to keep evaluating. 1219 /// 1220 /// Call noteSideEffect() instead if we may be able to ignore the value that 1221 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1222 /// 1223 /// (Foo(), 1) // use noteSideEffect 1224 /// (Foo() || true) // use noteSideEffect 1225 /// Foo() + 1 // use noteFailure 1226 LLVM_NODISCARD bool noteFailure() { 1227 // Failure when evaluating some expression often means there is some 1228 // subexpression whose evaluation was skipped. Therefore, (because we 1229 // don't track whether we skipped an expression when unwinding after an 1230 // evaluation failure) every evaluation failure that bubbles up from a 1231 // subexpression implies that a side-effect has potentially happened. We 1232 // skip setting the HasSideEffects flag to true until we decide to 1233 // continue evaluating after that point, which happens here. 1234 bool KeepGoing = keepEvaluatingAfterFailure(); 1235 EvalStatus.HasSideEffects |= KeepGoing; 1236 return KeepGoing; 1237 } 1238 1239 class ArrayInitLoopIndex { 1240 EvalInfo &Info; 1241 uint64_t OuterIndex; 1242 1243 public: 1244 ArrayInitLoopIndex(EvalInfo &Info) 1245 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1246 Info.ArrayInitIndex = 0; 1247 } 1248 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1249 1250 operator uint64_t&() { return Info.ArrayInitIndex; } 1251 }; 1252 }; 1253 1254 /// Object used to treat all foldable expressions as constant expressions. 1255 struct FoldConstant { 1256 EvalInfo &Info; 1257 bool Enabled; 1258 bool HadNoPriorDiags; 1259 EvalInfo::EvaluationMode OldMode; 1260 1261 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1262 : Info(Info), 1263 Enabled(Enabled), 1264 HadNoPriorDiags(Info.EvalStatus.Diag && 1265 Info.EvalStatus.Diag->empty() && 1266 !Info.EvalStatus.HasSideEffects), 1267 OldMode(Info.EvalMode) { 1268 if (Enabled) 1269 Info.EvalMode = EvalInfo::EM_ConstantFold; 1270 } 1271 void keepDiagnostics() { Enabled = false; } 1272 ~FoldConstant() { 1273 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1274 !Info.EvalStatus.HasSideEffects) 1275 Info.EvalStatus.Diag->clear(); 1276 Info.EvalMode = OldMode; 1277 } 1278 }; 1279 1280 /// RAII object used to set the current evaluation mode to ignore 1281 /// side-effects. 1282 struct IgnoreSideEffectsRAII { 1283 EvalInfo &Info; 1284 EvalInfo::EvaluationMode OldMode; 1285 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1286 : Info(Info), OldMode(Info.EvalMode) { 1287 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1288 } 1289 1290 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1291 }; 1292 1293 /// RAII object used to optionally suppress diagnostics and side-effects from 1294 /// a speculative evaluation. 1295 class SpeculativeEvaluationRAII { 1296 EvalInfo *Info = nullptr; 1297 Expr::EvalStatus OldStatus; 1298 unsigned OldSpeculativeEvaluationDepth; 1299 1300 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1301 Info = Other.Info; 1302 OldStatus = Other.OldStatus; 1303 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1304 Other.Info = nullptr; 1305 } 1306 1307 void maybeRestoreState() { 1308 if (!Info) 1309 return; 1310 1311 Info->EvalStatus = OldStatus; 1312 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1313 } 1314 1315 public: 1316 SpeculativeEvaluationRAII() = default; 1317 1318 SpeculativeEvaluationRAII( 1319 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1320 : Info(&Info), OldStatus(Info.EvalStatus), 1321 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1322 Info.EvalStatus.Diag = NewDiag; 1323 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1324 } 1325 1326 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1327 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1328 moveFromAndCancel(std::move(Other)); 1329 } 1330 1331 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1332 maybeRestoreState(); 1333 moveFromAndCancel(std::move(Other)); 1334 return *this; 1335 } 1336 1337 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1338 }; 1339 1340 /// RAII object wrapping a full-expression or block scope, and handling 1341 /// the ending of the lifetime of temporaries created within it. 1342 template<ScopeKind Kind> 1343 class ScopeRAII { 1344 EvalInfo &Info; 1345 unsigned OldStackSize; 1346 public: 1347 ScopeRAII(EvalInfo &Info) 1348 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1349 // Push a new temporary version. This is needed to distinguish between 1350 // temporaries created in different iterations of a loop. 1351 Info.CurrentCall->pushTempVersion(); 1352 } 1353 bool destroy(bool RunDestructors = true) { 1354 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1355 OldStackSize = -1U; 1356 return OK; 1357 } 1358 ~ScopeRAII() { 1359 if (OldStackSize != -1U) 1360 destroy(false); 1361 // Body moved to a static method to encourage the compiler to inline away 1362 // instances of this class. 1363 Info.CurrentCall->popTempVersion(); 1364 } 1365 private: 1366 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1367 unsigned OldStackSize) { 1368 assert(OldStackSize <= Info.CleanupStack.size() && 1369 "running cleanups out of order?"); 1370 1371 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1372 // for a full-expression scope. 1373 bool Success = true; 1374 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1375 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1376 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1377 Success = false; 1378 break; 1379 } 1380 } 1381 } 1382 1383 // Compact any retained cleanups. 1384 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1385 if (Kind != ScopeKind::Block) 1386 NewEnd = 1387 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1388 return C.isDestroyedAtEndOf(Kind); 1389 }); 1390 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1391 return Success; 1392 } 1393 }; 1394 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1395 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1396 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1397 } 1398 1399 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1400 CheckSubobjectKind CSK) { 1401 if (Invalid) 1402 return false; 1403 if (isOnePastTheEnd()) { 1404 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1405 << CSK; 1406 setInvalid(); 1407 return false; 1408 } 1409 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1410 // must actually be at least one array element; even a VLA cannot have a 1411 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1412 return true; 1413 } 1414 1415 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1416 const Expr *E) { 1417 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1418 // Do not set the designator as invalid: we can represent this situation, 1419 // and correct handling of __builtin_object_size requires us to do so. 1420 } 1421 1422 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1423 const Expr *E, 1424 const APSInt &N) { 1425 // If we're complaining, we must be able to statically determine the size of 1426 // the most derived array. 1427 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1428 Info.CCEDiag(E, diag::note_constexpr_array_index) 1429 << N << /*array*/ 0 1430 << static_cast<unsigned>(getMostDerivedArraySize()); 1431 else 1432 Info.CCEDiag(E, diag::note_constexpr_array_index) 1433 << N << /*non-array*/ 1; 1434 setInvalid(); 1435 } 1436 1437 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1438 const FunctionDecl *Callee, const LValue *This, 1439 CallRef Call) 1440 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1441 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1442 Info.CurrentCall = this; 1443 ++Info.CallStackDepth; 1444 } 1445 1446 CallStackFrame::~CallStackFrame() { 1447 assert(Info.CurrentCall == this && "calls retired out of order"); 1448 --Info.CallStackDepth; 1449 Info.CurrentCall = Caller; 1450 } 1451 1452 static bool isRead(AccessKinds AK) { 1453 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1454 } 1455 1456 static bool isModification(AccessKinds AK) { 1457 switch (AK) { 1458 case AK_Read: 1459 case AK_ReadObjectRepresentation: 1460 case AK_MemberCall: 1461 case AK_DynamicCast: 1462 case AK_TypeId: 1463 return false; 1464 case AK_Assign: 1465 case AK_Increment: 1466 case AK_Decrement: 1467 case AK_Construct: 1468 case AK_Destroy: 1469 return true; 1470 } 1471 llvm_unreachable("unknown access kind"); 1472 } 1473 1474 static bool isAnyAccess(AccessKinds AK) { 1475 return isRead(AK) || isModification(AK); 1476 } 1477 1478 /// Is this an access per the C++ definition? 1479 static bool isFormalAccess(AccessKinds AK) { 1480 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1481 } 1482 1483 /// Is this kind of axcess valid on an indeterminate object value? 1484 static bool isValidIndeterminateAccess(AccessKinds AK) { 1485 switch (AK) { 1486 case AK_Read: 1487 case AK_Increment: 1488 case AK_Decrement: 1489 // These need the object's value. 1490 return false; 1491 1492 case AK_ReadObjectRepresentation: 1493 case AK_Assign: 1494 case AK_Construct: 1495 case AK_Destroy: 1496 // Construction and destruction don't need the value. 1497 return true; 1498 1499 case AK_MemberCall: 1500 case AK_DynamicCast: 1501 case AK_TypeId: 1502 // These aren't really meaningful on scalars. 1503 return true; 1504 } 1505 llvm_unreachable("unknown access kind"); 1506 } 1507 1508 namespace { 1509 struct ComplexValue { 1510 private: 1511 bool IsInt; 1512 1513 public: 1514 APSInt IntReal, IntImag; 1515 APFloat FloatReal, FloatImag; 1516 1517 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1518 1519 void makeComplexFloat() { IsInt = false; } 1520 bool isComplexFloat() const { return !IsInt; } 1521 APFloat &getComplexFloatReal() { return FloatReal; } 1522 APFloat &getComplexFloatImag() { return FloatImag; } 1523 1524 void makeComplexInt() { IsInt = true; } 1525 bool isComplexInt() const { return IsInt; } 1526 APSInt &getComplexIntReal() { return IntReal; } 1527 APSInt &getComplexIntImag() { return IntImag; } 1528 1529 void moveInto(APValue &v) const { 1530 if (isComplexFloat()) 1531 v = APValue(FloatReal, FloatImag); 1532 else 1533 v = APValue(IntReal, IntImag); 1534 } 1535 void setFrom(const APValue &v) { 1536 assert(v.isComplexFloat() || v.isComplexInt()); 1537 if (v.isComplexFloat()) { 1538 makeComplexFloat(); 1539 FloatReal = v.getComplexFloatReal(); 1540 FloatImag = v.getComplexFloatImag(); 1541 } else { 1542 makeComplexInt(); 1543 IntReal = v.getComplexIntReal(); 1544 IntImag = v.getComplexIntImag(); 1545 } 1546 } 1547 }; 1548 1549 struct LValue { 1550 APValue::LValueBase Base; 1551 CharUnits Offset; 1552 SubobjectDesignator Designator; 1553 bool IsNullPtr : 1; 1554 bool InvalidBase : 1; 1555 1556 const APValue::LValueBase getLValueBase() const { return Base; } 1557 CharUnits &getLValueOffset() { return Offset; } 1558 const CharUnits &getLValueOffset() const { return Offset; } 1559 SubobjectDesignator &getLValueDesignator() { return Designator; } 1560 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1561 bool isNullPointer() const { return IsNullPtr;} 1562 1563 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1564 unsigned getLValueVersion() const { return Base.getVersion(); } 1565 1566 void moveInto(APValue &V) const { 1567 if (Designator.Invalid) 1568 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1569 else { 1570 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1571 V = APValue(Base, Offset, Designator.Entries, 1572 Designator.IsOnePastTheEnd, IsNullPtr); 1573 } 1574 } 1575 void setFrom(ASTContext &Ctx, const APValue &V) { 1576 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1577 Base = V.getLValueBase(); 1578 Offset = V.getLValueOffset(); 1579 InvalidBase = false; 1580 Designator = SubobjectDesignator(Ctx, V); 1581 IsNullPtr = V.isNullPointer(); 1582 } 1583 1584 void set(APValue::LValueBase B, bool BInvalid = false) { 1585 #ifndef NDEBUG 1586 // We only allow a few types of invalid bases. Enforce that here. 1587 if (BInvalid) { 1588 const auto *E = B.get<const Expr *>(); 1589 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1590 "Unexpected type of invalid base"); 1591 } 1592 #endif 1593 1594 Base = B; 1595 Offset = CharUnits::fromQuantity(0); 1596 InvalidBase = BInvalid; 1597 Designator = SubobjectDesignator(getType(B)); 1598 IsNullPtr = false; 1599 } 1600 1601 void setNull(ASTContext &Ctx, QualType PointerTy) { 1602 Base = (const ValueDecl *)nullptr; 1603 Offset = 1604 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1605 InvalidBase = false; 1606 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1607 IsNullPtr = true; 1608 } 1609 1610 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1611 set(B, true); 1612 } 1613 1614 std::string toString(ASTContext &Ctx, QualType T) const { 1615 APValue Printable; 1616 moveInto(Printable); 1617 return Printable.getAsString(Ctx, T); 1618 } 1619 1620 private: 1621 // Check that this LValue is not based on a null pointer. If it is, produce 1622 // a diagnostic and mark the designator as invalid. 1623 template <typename GenDiagType> 1624 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1625 if (Designator.Invalid) 1626 return false; 1627 if (IsNullPtr) { 1628 GenDiag(); 1629 Designator.setInvalid(); 1630 return false; 1631 } 1632 return true; 1633 } 1634 1635 public: 1636 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1637 CheckSubobjectKind CSK) { 1638 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1639 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1640 }); 1641 } 1642 1643 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1644 AccessKinds AK) { 1645 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1646 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1647 }); 1648 } 1649 1650 // Check this LValue refers to an object. If not, set the designator to be 1651 // invalid and emit a diagnostic. 1652 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1653 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1654 Designator.checkSubobject(Info, E, CSK); 1655 } 1656 1657 void addDecl(EvalInfo &Info, const Expr *E, 1658 const Decl *D, bool Virtual = false) { 1659 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1660 Designator.addDeclUnchecked(D, Virtual); 1661 } 1662 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1663 if (!Designator.Entries.empty()) { 1664 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1665 Designator.setInvalid(); 1666 return; 1667 } 1668 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1669 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1670 Designator.FirstEntryIsAnUnsizedArray = true; 1671 Designator.addUnsizedArrayUnchecked(ElemTy); 1672 } 1673 } 1674 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1675 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1676 Designator.addArrayUnchecked(CAT); 1677 } 1678 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1679 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1680 Designator.addComplexUnchecked(EltTy, Imag); 1681 } 1682 void clearIsNullPointer() { 1683 IsNullPtr = false; 1684 } 1685 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1686 const APSInt &Index, CharUnits ElementSize) { 1687 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1688 // but we're not required to diagnose it and it's valid in C++.) 1689 if (!Index) 1690 return; 1691 1692 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1693 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1694 // offsets. 1695 uint64_t Offset64 = Offset.getQuantity(); 1696 uint64_t ElemSize64 = ElementSize.getQuantity(); 1697 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1698 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1699 1700 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1701 Designator.adjustIndex(Info, E, Index); 1702 clearIsNullPointer(); 1703 } 1704 void adjustOffset(CharUnits N) { 1705 Offset += N; 1706 if (N.getQuantity()) 1707 clearIsNullPointer(); 1708 } 1709 }; 1710 1711 struct MemberPtr { 1712 MemberPtr() {} 1713 explicit MemberPtr(const ValueDecl *Decl) : 1714 DeclAndIsDerivedMember(Decl, false), Path() {} 1715 1716 /// The member or (direct or indirect) field referred to by this member 1717 /// pointer, or 0 if this is a null member pointer. 1718 const ValueDecl *getDecl() const { 1719 return DeclAndIsDerivedMember.getPointer(); 1720 } 1721 /// Is this actually a member of some type derived from the relevant class? 1722 bool isDerivedMember() const { 1723 return DeclAndIsDerivedMember.getInt(); 1724 } 1725 /// Get the class which the declaration actually lives in. 1726 const CXXRecordDecl *getContainingRecord() const { 1727 return cast<CXXRecordDecl>( 1728 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1729 } 1730 1731 void moveInto(APValue &V) const { 1732 V = APValue(getDecl(), isDerivedMember(), Path); 1733 } 1734 void setFrom(const APValue &V) { 1735 assert(V.isMemberPointer()); 1736 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1737 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1738 Path.clear(); 1739 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1740 Path.insert(Path.end(), P.begin(), P.end()); 1741 } 1742 1743 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1744 /// whether the member is a member of some class derived from the class type 1745 /// of the member pointer. 1746 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1747 /// Path - The path of base/derived classes from the member declaration's 1748 /// class (exclusive) to the class type of the member pointer (inclusive). 1749 SmallVector<const CXXRecordDecl*, 4> Path; 1750 1751 /// Perform a cast towards the class of the Decl (either up or down the 1752 /// hierarchy). 1753 bool castBack(const CXXRecordDecl *Class) { 1754 assert(!Path.empty()); 1755 const CXXRecordDecl *Expected; 1756 if (Path.size() >= 2) 1757 Expected = Path[Path.size() - 2]; 1758 else 1759 Expected = getContainingRecord(); 1760 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1761 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1762 // if B does not contain the original member and is not a base or 1763 // derived class of the class containing the original member, the result 1764 // of the cast is undefined. 1765 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1766 // (D::*). We consider that to be a language defect. 1767 return false; 1768 } 1769 Path.pop_back(); 1770 return true; 1771 } 1772 /// Perform a base-to-derived member pointer cast. 1773 bool castToDerived(const CXXRecordDecl *Derived) { 1774 if (!getDecl()) 1775 return true; 1776 if (!isDerivedMember()) { 1777 Path.push_back(Derived); 1778 return true; 1779 } 1780 if (!castBack(Derived)) 1781 return false; 1782 if (Path.empty()) 1783 DeclAndIsDerivedMember.setInt(false); 1784 return true; 1785 } 1786 /// Perform a derived-to-base member pointer cast. 1787 bool castToBase(const CXXRecordDecl *Base) { 1788 if (!getDecl()) 1789 return true; 1790 if (Path.empty()) 1791 DeclAndIsDerivedMember.setInt(true); 1792 if (isDerivedMember()) { 1793 Path.push_back(Base); 1794 return true; 1795 } 1796 return castBack(Base); 1797 } 1798 }; 1799 1800 /// Compare two member pointers, which are assumed to be of the same type. 1801 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1802 if (!LHS.getDecl() || !RHS.getDecl()) 1803 return !LHS.getDecl() && !RHS.getDecl(); 1804 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1805 return false; 1806 return LHS.Path == RHS.Path; 1807 } 1808 } 1809 1810 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1811 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1812 const LValue &This, const Expr *E, 1813 bool AllowNonLiteralTypes = false); 1814 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1815 bool InvalidBaseOK = false); 1816 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1817 bool InvalidBaseOK = false); 1818 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1819 EvalInfo &Info); 1820 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1821 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1822 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1825 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1826 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1827 EvalInfo &Info); 1828 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1829 1830 /// Evaluate an integer or fixed point expression into an APResult. 1831 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1832 EvalInfo &Info); 1833 1834 /// Evaluate only a fixed point expression into an APResult. 1835 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1836 EvalInfo &Info); 1837 1838 //===----------------------------------------------------------------------===// 1839 // Misc utilities 1840 //===----------------------------------------------------------------------===// 1841 1842 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1843 /// preserving its value (by extending by up to one bit as needed). 1844 static void negateAsSigned(APSInt &Int) { 1845 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1846 Int = Int.extend(Int.getBitWidth() + 1); 1847 Int.setIsSigned(true); 1848 } 1849 Int = -Int; 1850 } 1851 1852 template<typename KeyT> 1853 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1854 ScopeKind Scope, LValue &LV) { 1855 unsigned Version = getTempVersion(); 1856 APValue::LValueBase Base(Key, Index, Version); 1857 LV.set(Base); 1858 return createLocal(Base, Key, T, Scope); 1859 } 1860 1861 /// Allocate storage for a parameter of a function call made in this frame. 1862 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1863 LValue &LV) { 1864 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1865 APValue::LValueBase Base(PVD, Index, Args.Version); 1866 LV.set(Base); 1867 // We always destroy parameters at the end of the call, even if we'd allow 1868 // them to live to the end of the full-expression at runtime, in order to 1869 // give portable results and match other compilers. 1870 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1871 } 1872 1873 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1874 QualType T, ScopeKind Scope) { 1875 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1876 unsigned Version = Base.getVersion(); 1877 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1878 assert(Result.isAbsent() && "local created multiple times"); 1879 1880 // If we're creating a local immediately in the operand of a speculative 1881 // evaluation, don't register a cleanup to be run outside the speculative 1882 // evaluation context, since we won't actually be able to initialize this 1883 // object. 1884 if (Index <= Info.SpeculativeEvaluationDepth) { 1885 if (T.isDestructedType()) 1886 Info.noteSideEffect(); 1887 } else { 1888 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1889 } 1890 return Result; 1891 } 1892 1893 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1894 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1895 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1896 return nullptr; 1897 } 1898 1899 DynamicAllocLValue DA(NumHeapAllocs++); 1900 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1901 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1902 std::forward_as_tuple(DA), std::tuple<>()); 1903 assert(Result.second && "reused a heap alloc index?"); 1904 Result.first->second.AllocExpr = E; 1905 return &Result.first->second.Value; 1906 } 1907 1908 /// Produce a string describing the given constexpr call. 1909 void CallStackFrame::describe(raw_ostream &Out) { 1910 unsigned ArgIndex = 0; 1911 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1912 !isa<CXXConstructorDecl>(Callee) && 1913 cast<CXXMethodDecl>(Callee)->isInstance(); 1914 1915 if (!IsMemberCall) 1916 Out << *Callee << '('; 1917 1918 if (This && IsMemberCall) { 1919 APValue Val; 1920 This->moveInto(Val); 1921 Val.printPretty(Out, Info.Ctx, 1922 This->Designator.MostDerivedType); 1923 // FIXME: Add parens around Val if needed. 1924 Out << "->" << *Callee << '('; 1925 IsMemberCall = false; 1926 } 1927 1928 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1929 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1930 if (ArgIndex > (unsigned)IsMemberCall) 1931 Out << ", "; 1932 1933 const ParmVarDecl *Param = *I; 1934 APValue *V = Info.getParamSlot(Arguments, Param); 1935 if (V) 1936 V->printPretty(Out, Info.Ctx, Param->getType()); 1937 else 1938 Out << "<...>"; 1939 1940 if (ArgIndex == 0 && IsMemberCall) 1941 Out << "->" << *Callee << '('; 1942 } 1943 1944 Out << ')'; 1945 } 1946 1947 /// Evaluate an expression to see if it had side-effects, and discard its 1948 /// result. 1949 /// \return \c true if the caller should keep evaluating. 1950 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1951 assert(!E->isValueDependent()); 1952 APValue Scratch; 1953 if (!Evaluate(Scratch, Info, E)) 1954 // We don't need the value, but we might have skipped a side effect here. 1955 return Info.noteSideEffect(); 1956 return true; 1957 } 1958 1959 /// Should this call expression be treated as a string literal? 1960 static bool IsStringLiteralCall(const CallExpr *E) { 1961 unsigned Builtin = E->getBuiltinCallee(); 1962 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1963 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1964 } 1965 1966 static bool IsGlobalLValue(APValue::LValueBase B) { 1967 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1968 // constant expression of pointer type that evaluates to... 1969 1970 // ... a null pointer value, or a prvalue core constant expression of type 1971 // std::nullptr_t. 1972 if (!B) return true; 1973 1974 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1975 // ... the address of an object with static storage duration, 1976 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1977 return VD->hasGlobalStorage(); 1978 if (isa<TemplateParamObjectDecl>(D)) 1979 return true; 1980 // ... the address of a function, 1981 // ... the address of a GUID [MS extension], 1982 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(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 IsStringLiteralCall(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 case Expr::ImplicitValueInitExprClass: 2018 // FIXME: 2019 // We can never form an lvalue with an implicit value initialization as its 2020 // base through expression evaluation, so these only appear in one case: the 2021 // implicit variable declaration we invent when checking whether a constexpr 2022 // constructor can produce a constant expression. We must assume that such 2023 // an expression might be a global lvalue. 2024 return true; 2025 } 2026 } 2027 2028 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2029 return LVal.Base.dyn_cast<const ValueDecl*>(); 2030 } 2031 2032 static bool IsLiteralLValue(const LValue &Value) { 2033 if (Value.getLValueCallIndex()) 2034 return false; 2035 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2036 return E && !isa<MaterializeTemporaryExpr>(E); 2037 } 2038 2039 static bool IsWeakLValue(const LValue &Value) { 2040 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2041 return Decl && Decl->isWeak(); 2042 } 2043 2044 static bool isZeroSized(const LValue &Value) { 2045 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2046 if (Decl && isa<VarDecl>(Decl)) { 2047 QualType Ty = Decl->getType(); 2048 if (Ty->isArrayType()) 2049 return Ty->isIncompleteType() || 2050 Decl->getASTContext().getTypeSize(Ty) == 0; 2051 } 2052 return false; 2053 } 2054 2055 static bool HasSameBase(const LValue &A, const LValue &B) { 2056 if (!A.getLValueBase()) 2057 return !B.getLValueBase(); 2058 if (!B.getLValueBase()) 2059 return false; 2060 2061 if (A.getLValueBase().getOpaqueValue() != 2062 B.getLValueBase().getOpaqueValue()) 2063 return false; 2064 2065 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2066 A.getLValueVersion() == B.getLValueVersion(); 2067 } 2068 2069 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2070 assert(Base && "no location for a null lvalue"); 2071 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2072 2073 // For a parameter, find the corresponding call stack frame (if it still 2074 // exists), and point at the parameter of the function definition we actually 2075 // invoked. 2076 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2077 unsigned Idx = PVD->getFunctionScopeIndex(); 2078 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2079 if (F->Arguments.CallIndex == Base.getCallIndex() && 2080 F->Arguments.Version == Base.getVersion() && F->Callee && 2081 Idx < F->Callee->getNumParams()) { 2082 VD = F->Callee->getParamDecl(Idx); 2083 break; 2084 } 2085 } 2086 } 2087 2088 if (VD) 2089 Info.Note(VD->getLocation(), diag::note_declared_at); 2090 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2091 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2092 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2093 // FIXME: Produce a note for dangling pointers too. 2094 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2095 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2096 diag::note_constexpr_dynamic_alloc_here); 2097 } 2098 // We have no information to show for a typeid(T) object. 2099 } 2100 2101 enum class CheckEvaluationResultKind { 2102 ConstantExpression, 2103 FullyInitialized, 2104 }; 2105 2106 /// Materialized temporaries that we've already checked to determine if they're 2107 /// initializsed by a constant expression. 2108 using CheckedTemporaries = 2109 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2110 2111 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2112 EvalInfo &Info, SourceLocation DiagLoc, 2113 QualType Type, const APValue &Value, 2114 ConstantExprKind Kind, 2115 SourceLocation SubobjectLoc, 2116 CheckedTemporaries &CheckedTemps); 2117 2118 /// Check that this reference or pointer core constant expression is a valid 2119 /// value for an address or reference constant expression. Return true if we 2120 /// can fold this expression, whether or not it's a constant expression. 2121 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2122 QualType Type, const LValue &LVal, 2123 ConstantExprKind Kind, 2124 CheckedTemporaries &CheckedTemps) { 2125 bool IsReferenceType = Type->isReferenceType(); 2126 2127 APValue::LValueBase Base = LVal.getLValueBase(); 2128 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2129 2130 const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2131 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2132 2133 // Additional restrictions apply in a template argument. We only enforce the 2134 // C++20 restrictions here; additional syntactic and semantic restrictions 2135 // are applied elsewhere. 2136 if (isTemplateArgument(Kind)) { 2137 int InvalidBaseKind = -1; 2138 StringRef Ident; 2139 if (Base.is<TypeInfoLValue>()) 2140 InvalidBaseKind = 0; 2141 else if (isa_and_nonnull<StringLiteral>(BaseE)) 2142 InvalidBaseKind = 1; 2143 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2144 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2145 InvalidBaseKind = 2; 2146 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2147 InvalidBaseKind = 3; 2148 Ident = PE->getIdentKindName(); 2149 } 2150 2151 if (InvalidBaseKind != -1) { 2152 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2153 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2154 << Ident; 2155 return false; 2156 } 2157 } 2158 2159 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2160 if (FD->isConsteval()) { 2161 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2162 << !Type->isAnyPointerType(); 2163 Info.Note(FD->getLocation(), diag::note_declared_at); 2164 return false; 2165 } 2166 } 2167 2168 // Check that the object is a global. Note that the fake 'this' object we 2169 // manufacture when checking potential constant expressions is conservatively 2170 // assumed to be global here. 2171 if (!IsGlobalLValue(Base)) { 2172 if (Info.getLangOpts().CPlusPlus11) { 2173 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2174 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2175 << IsReferenceType << !Designator.Entries.empty() 2176 << !!VD << VD; 2177 2178 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2179 if (VarD && VarD->isConstexpr()) { 2180 // Non-static local constexpr variables have unintuitive semantics: 2181 // constexpr int a = 1; 2182 // constexpr const int *p = &a; 2183 // ... is invalid because the address of 'a' is not constant. Suggest 2184 // adding a 'static' in this case. 2185 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2186 << VarD 2187 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2188 } else { 2189 NoteLValueLocation(Info, Base); 2190 } 2191 } else { 2192 Info.FFDiag(Loc); 2193 } 2194 // Don't allow references to temporaries to escape. 2195 return false; 2196 } 2197 assert((Info.checkingPotentialConstantExpression() || 2198 LVal.getLValueCallIndex() == 0) && 2199 "have call index for global lvalue"); 2200 2201 if (Base.is<DynamicAllocLValue>()) { 2202 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2203 << IsReferenceType << !Designator.Entries.empty(); 2204 NoteLValueLocation(Info, Base); 2205 return false; 2206 } 2207 2208 if (BaseVD) { 2209 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2210 // Check if this is a thread-local variable. 2211 if (Var->getTLSKind()) 2212 // FIXME: Diagnostic! 2213 return false; 2214 2215 // A dllimport variable never acts like a constant, unless we're 2216 // evaluating a value for use only in name mangling. 2217 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2218 // FIXME: Diagnostic! 2219 return false; 2220 } 2221 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2222 // __declspec(dllimport) must be handled very carefully: 2223 // We must never initialize an expression with the thunk in C++. 2224 // Doing otherwise would allow the same id-expression to yield 2225 // different addresses for the same function in different translation 2226 // units. However, this means that we must dynamically initialize the 2227 // expression with the contents of the import address table at runtime. 2228 // 2229 // The C language has no notion of ODR; furthermore, it has no notion of 2230 // dynamic initialization. This means that we are permitted to 2231 // perform initialization with the address of the thunk. 2232 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2233 FD->hasAttr<DLLImportAttr>()) 2234 // FIXME: Diagnostic! 2235 return false; 2236 } 2237 } else if (const auto *MTE = 2238 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2239 if (CheckedTemps.insert(MTE).second) { 2240 QualType TempType = getType(Base); 2241 if (TempType.isDestructedType()) { 2242 Info.FFDiag(MTE->getExprLoc(), 2243 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2244 << TempType; 2245 return false; 2246 } 2247 2248 APValue *V = MTE->getOrCreateValue(false); 2249 assert(V && "evasluation result refers to uninitialised temporary"); 2250 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2251 Info, MTE->getExprLoc(), TempType, *V, 2252 Kind, SourceLocation(), CheckedTemps)) 2253 return false; 2254 } 2255 } 2256 2257 // Allow address constant expressions to be past-the-end pointers. This is 2258 // an extension: the standard requires them to point to an object. 2259 if (!IsReferenceType) 2260 return true; 2261 2262 // A reference constant expression must refer to an object. 2263 if (!Base) { 2264 // FIXME: diagnostic 2265 Info.CCEDiag(Loc); 2266 return true; 2267 } 2268 2269 // Does this refer one past the end of some object? 2270 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2271 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2272 << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2273 NoteLValueLocation(Info, Base); 2274 } 2275 2276 return true; 2277 } 2278 2279 /// Member pointers are constant expressions unless they point to a 2280 /// non-virtual dllimport member function. 2281 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2282 SourceLocation Loc, 2283 QualType Type, 2284 const APValue &Value, 2285 ConstantExprKind Kind) { 2286 const ValueDecl *Member = Value.getMemberPointerDecl(); 2287 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2288 if (!FD) 2289 return true; 2290 if (FD->isConsteval()) { 2291 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2292 Info.Note(FD->getLocation(), diag::note_declared_at); 2293 return false; 2294 } 2295 return isForManglingOnly(Kind) || FD->isVirtual() || 2296 !FD->hasAttr<DLLImportAttr>(); 2297 } 2298 2299 /// Check that this core constant expression is of literal type, and if not, 2300 /// produce an appropriate diagnostic. 2301 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2302 const LValue *This = nullptr) { 2303 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2304 return true; 2305 2306 // C++1y: A constant initializer for an object o [...] may also invoke 2307 // constexpr constructors for o and its subobjects even if those objects 2308 // are of non-literal class types. 2309 // 2310 // C++11 missed this detail for aggregates, so classes like this: 2311 // struct foo_t { union { int i; volatile int j; } u; }; 2312 // are not (obviously) initializable like so: 2313 // __attribute__((__require_constant_initialization__)) 2314 // static const foo_t x = {{0}}; 2315 // because "i" is a subobject with non-literal initialization (due to the 2316 // volatile member of the union). See: 2317 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2318 // Therefore, we use the C++1y behavior. 2319 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2320 return true; 2321 2322 // Prvalue constant expressions must be of literal types. 2323 if (Info.getLangOpts().CPlusPlus11) 2324 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2325 << E->getType(); 2326 else 2327 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2328 return false; 2329 } 2330 2331 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2332 EvalInfo &Info, SourceLocation DiagLoc, 2333 QualType Type, const APValue &Value, 2334 ConstantExprKind Kind, 2335 SourceLocation SubobjectLoc, 2336 CheckedTemporaries &CheckedTemps) { 2337 if (!Value.hasValue()) { 2338 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2339 << true << Type; 2340 if (SubobjectLoc.isValid()) 2341 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2342 return false; 2343 } 2344 2345 // We allow _Atomic(T) to be initialized from anything that T can be 2346 // initialized from. 2347 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2348 Type = AT->getValueType(); 2349 2350 // Core issue 1454: For a literal constant expression of array or class type, 2351 // each subobject of its value shall have been initialized by a constant 2352 // expression. 2353 if (Value.isArray()) { 2354 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2355 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2356 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2357 Value.getArrayInitializedElt(I), Kind, 2358 SubobjectLoc, CheckedTemps)) 2359 return false; 2360 } 2361 if (!Value.hasArrayFiller()) 2362 return true; 2363 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2364 Value.getArrayFiller(), Kind, SubobjectLoc, 2365 CheckedTemps); 2366 } 2367 if (Value.isUnion() && Value.getUnionField()) { 2368 return CheckEvaluationResult( 2369 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2370 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2371 CheckedTemps); 2372 } 2373 if (Value.isStruct()) { 2374 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2375 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2376 unsigned BaseIndex = 0; 2377 for (const CXXBaseSpecifier &BS : CD->bases()) { 2378 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2379 Value.getStructBase(BaseIndex), Kind, 2380 BS.getBeginLoc(), CheckedTemps)) 2381 return false; 2382 ++BaseIndex; 2383 } 2384 } 2385 for (const auto *I : RD->fields()) { 2386 if (I->isUnnamedBitfield()) 2387 continue; 2388 2389 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2390 Value.getStructField(I->getFieldIndex()), 2391 Kind, I->getLocation(), CheckedTemps)) 2392 return false; 2393 } 2394 } 2395 2396 if (Value.isLValue() && 2397 CERK == CheckEvaluationResultKind::ConstantExpression) { 2398 LValue LVal; 2399 LVal.setFrom(Info.Ctx, Value); 2400 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2401 CheckedTemps); 2402 } 2403 2404 if (Value.isMemberPointer() && 2405 CERK == CheckEvaluationResultKind::ConstantExpression) 2406 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2407 2408 // Everything else is fine. 2409 return true; 2410 } 2411 2412 /// Check that this core constant expression value is a valid value for a 2413 /// constant expression. If not, report an appropriate diagnostic. Does not 2414 /// check that the expression is of literal type. 2415 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2416 QualType Type, const APValue &Value, 2417 ConstantExprKind Kind) { 2418 // Nothing to check for a constant expression of type 'cv void'. 2419 if (Type->isVoidType()) 2420 return true; 2421 2422 CheckedTemporaries CheckedTemps; 2423 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2424 Info, DiagLoc, Type, Value, Kind, 2425 SourceLocation(), CheckedTemps); 2426 } 2427 2428 /// Check that this evaluated value is fully-initialized and can be loaded by 2429 /// an lvalue-to-rvalue conversion. 2430 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2431 QualType Type, const APValue &Value) { 2432 CheckedTemporaries CheckedTemps; 2433 return CheckEvaluationResult( 2434 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2435 ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2436 } 2437 2438 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2439 /// "the allocated storage is deallocated within the evaluation". 2440 static bool CheckMemoryLeaks(EvalInfo &Info) { 2441 if (!Info.HeapAllocs.empty()) { 2442 // We can still fold to a constant despite a compile-time memory leak, 2443 // so long as the heap allocation isn't referenced in the result (we check 2444 // that in CheckConstantExpression). 2445 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2446 diag::note_constexpr_memory_leak) 2447 << unsigned(Info.HeapAllocs.size() - 1); 2448 } 2449 return true; 2450 } 2451 2452 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2453 // A null base expression indicates a null pointer. These are always 2454 // evaluatable, and they are false unless the offset is zero. 2455 if (!Value.getLValueBase()) { 2456 Result = !Value.getLValueOffset().isZero(); 2457 return true; 2458 } 2459 2460 // We have a non-null base. These are generally known to be true, but if it's 2461 // a weak declaration it can be null at runtime. 2462 Result = true; 2463 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2464 return !Decl || !Decl->isWeak(); 2465 } 2466 2467 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2468 switch (Val.getKind()) { 2469 case APValue::None: 2470 case APValue::Indeterminate: 2471 return false; 2472 case APValue::Int: 2473 Result = Val.getInt().getBoolValue(); 2474 return true; 2475 case APValue::FixedPoint: 2476 Result = Val.getFixedPoint().getBoolValue(); 2477 return true; 2478 case APValue::Float: 2479 Result = !Val.getFloat().isZero(); 2480 return true; 2481 case APValue::ComplexInt: 2482 Result = Val.getComplexIntReal().getBoolValue() || 2483 Val.getComplexIntImag().getBoolValue(); 2484 return true; 2485 case APValue::ComplexFloat: 2486 Result = !Val.getComplexFloatReal().isZero() || 2487 !Val.getComplexFloatImag().isZero(); 2488 return true; 2489 case APValue::LValue: 2490 return EvalPointerValueAsBool(Val, Result); 2491 case APValue::MemberPointer: 2492 Result = Val.getMemberPointerDecl(); 2493 return true; 2494 case APValue::Vector: 2495 case APValue::Array: 2496 case APValue::Struct: 2497 case APValue::Union: 2498 case APValue::AddrLabelDiff: 2499 return false; 2500 } 2501 2502 llvm_unreachable("unknown APValue kind"); 2503 } 2504 2505 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2506 EvalInfo &Info) { 2507 assert(!E->isValueDependent()); 2508 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2509 APValue Val; 2510 if (!Evaluate(Val, Info, E)) 2511 return false; 2512 return HandleConversionToBool(Val, Result); 2513 } 2514 2515 template<typename T> 2516 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2517 const T &SrcValue, QualType DestType) { 2518 Info.CCEDiag(E, diag::note_constexpr_overflow) 2519 << SrcValue << DestType; 2520 return Info.noteUndefinedBehavior(); 2521 } 2522 2523 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2524 QualType SrcType, const APFloat &Value, 2525 QualType DestType, APSInt &Result) { 2526 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2527 // Determine whether we are converting to unsigned or signed. 2528 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2529 2530 Result = APSInt(DestWidth, !DestSigned); 2531 bool ignored; 2532 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2533 & APFloat::opInvalidOp) 2534 return HandleOverflow(Info, E, Value, DestType); 2535 return true; 2536 } 2537 2538 /// Get rounding mode used for evaluation of the specified expression. 2539 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2540 /// dynamic. 2541 /// If rounding mode is unknown at compile time, still try to evaluate the 2542 /// expression. If the result is exact, it does not depend on rounding mode. 2543 /// So return "tonearest" mode instead of "dynamic". 2544 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2545 bool &DynamicRM) { 2546 llvm::RoundingMode RM = 2547 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2548 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2549 if (DynamicRM) 2550 RM = llvm::RoundingMode::NearestTiesToEven; 2551 return RM; 2552 } 2553 2554 /// Check if the given evaluation result is allowed for constant evaluation. 2555 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2556 APFloat::opStatus St) { 2557 // In a constant context, assume that any dynamic rounding mode or FP 2558 // exception state matches the default floating-point environment. 2559 if (Info.InConstantContext) 2560 return true; 2561 2562 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2563 if ((St & APFloat::opInexact) && 2564 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2565 // Inexact result means that it depends on rounding mode. If the requested 2566 // mode is dynamic, the evaluation cannot be made in compile time. 2567 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2568 return false; 2569 } 2570 2571 if ((St != APFloat::opOK) && 2572 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2573 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2574 FPO.getAllowFEnvAccess())) { 2575 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2576 return false; 2577 } 2578 2579 if ((St & APFloat::opStatus::opInvalidOp) && 2580 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2581 // There is no usefully definable result. 2582 Info.FFDiag(E); 2583 return false; 2584 } 2585 2586 // FIXME: if: 2587 // - evaluation triggered other FP exception, and 2588 // - exception mode is not "ignore", and 2589 // - the expression being evaluated is not a part of global variable 2590 // initializer, 2591 // the evaluation probably need to be rejected. 2592 return true; 2593 } 2594 2595 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2596 QualType SrcType, QualType DestType, 2597 APFloat &Result) { 2598 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2599 bool DynamicRM; 2600 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2601 APFloat::opStatus St; 2602 APFloat Value = Result; 2603 bool ignored; 2604 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2605 return checkFloatingPointResult(Info, E, St); 2606 } 2607 2608 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2609 QualType DestType, QualType SrcType, 2610 const APSInt &Value) { 2611 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2612 // Figure out if this is a truncate, extend or noop cast. 2613 // If the input is signed, do a sign extend, noop, or truncate. 2614 APSInt Result = Value.extOrTrunc(DestWidth); 2615 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2616 if (DestType->isBooleanType()) 2617 Result = Value.getBoolValue(); 2618 return Result; 2619 } 2620 2621 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2622 const FPOptions FPO, 2623 QualType SrcType, const APSInt &Value, 2624 QualType DestType, APFloat &Result) { 2625 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2626 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2627 APFloat::rmNearestTiesToEven); 2628 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2629 FPO.isFPConstrained()) { 2630 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2631 return false; 2632 } 2633 return true; 2634 } 2635 2636 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2637 APValue &Value, const FieldDecl *FD) { 2638 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2639 2640 if (!Value.isInt()) { 2641 // Trying to store a pointer-cast-to-integer into a bitfield. 2642 // FIXME: In this case, we should provide the diagnostic for casting 2643 // a pointer to an integer. 2644 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2645 Info.FFDiag(E); 2646 return false; 2647 } 2648 2649 APSInt &Int = Value.getInt(); 2650 unsigned OldBitWidth = Int.getBitWidth(); 2651 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2652 if (NewBitWidth < OldBitWidth) 2653 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2654 return true; 2655 } 2656 2657 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2658 llvm::APInt &Res) { 2659 APValue SVal; 2660 if (!Evaluate(SVal, Info, E)) 2661 return false; 2662 if (SVal.isInt()) { 2663 Res = SVal.getInt(); 2664 return true; 2665 } 2666 if (SVal.isFloat()) { 2667 Res = SVal.getFloat().bitcastToAPInt(); 2668 return true; 2669 } 2670 if (SVal.isVector()) { 2671 QualType VecTy = E->getType(); 2672 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2673 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2674 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2675 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2676 Res = llvm::APInt::getNullValue(VecSize); 2677 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2678 APValue &Elt = SVal.getVectorElt(i); 2679 llvm::APInt EltAsInt; 2680 if (Elt.isInt()) { 2681 EltAsInt = Elt.getInt(); 2682 } else if (Elt.isFloat()) { 2683 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2684 } else { 2685 // Don't try to handle vectors of anything other than int or float 2686 // (not sure if it's possible to hit this case). 2687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2688 return false; 2689 } 2690 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2691 if (BigEndian) 2692 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2693 else 2694 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2695 } 2696 return true; 2697 } 2698 // Give up if the input isn't an int, float, or vector. For example, we 2699 // reject "(v4i16)(intptr_t)&a". 2700 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2701 return false; 2702 } 2703 2704 /// Perform the given integer operation, which is known to need at most BitWidth 2705 /// bits, and check for overflow in the original type (if that type was not an 2706 /// unsigned type). 2707 template<typename Operation> 2708 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2709 const APSInt &LHS, const APSInt &RHS, 2710 unsigned BitWidth, Operation Op, 2711 APSInt &Result) { 2712 if (LHS.isUnsigned()) { 2713 Result = Op(LHS, RHS); 2714 return true; 2715 } 2716 2717 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2718 Result = Value.trunc(LHS.getBitWidth()); 2719 if (Result.extend(BitWidth) != Value) { 2720 if (Info.checkingForUndefinedBehavior()) 2721 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2722 diag::warn_integer_constant_overflow) 2723 << Result.toString(10) << E->getType(); 2724 return HandleOverflow(Info, E, Value, E->getType()); 2725 } 2726 return true; 2727 } 2728 2729 /// Perform the given binary integer operation. 2730 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2731 BinaryOperatorKind Opcode, APSInt RHS, 2732 APSInt &Result) { 2733 switch (Opcode) { 2734 default: 2735 Info.FFDiag(E); 2736 return false; 2737 case BO_Mul: 2738 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2739 std::multiplies<APSInt>(), Result); 2740 case BO_Add: 2741 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2742 std::plus<APSInt>(), Result); 2743 case BO_Sub: 2744 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2745 std::minus<APSInt>(), Result); 2746 case BO_And: Result = LHS & RHS; return true; 2747 case BO_Xor: Result = LHS ^ RHS; return true; 2748 case BO_Or: Result = LHS | RHS; return true; 2749 case BO_Div: 2750 case BO_Rem: 2751 if (RHS == 0) { 2752 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2753 return false; 2754 } 2755 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2756 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2757 // this operation and gives the two's complement result. 2758 if (RHS.isNegative() && RHS.isAllOnesValue() && 2759 LHS.isSigned() && LHS.isMinSignedValue()) 2760 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2761 E->getType()); 2762 return true; 2763 case BO_Shl: { 2764 if (Info.getLangOpts().OpenCL) 2765 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2766 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2767 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2768 RHS.isUnsigned()); 2769 else if (RHS.isSigned() && RHS.isNegative()) { 2770 // During constant-folding, a negative shift is an opposite shift. Such 2771 // a shift is not a constant expression. 2772 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2773 RHS = -RHS; 2774 goto shift_right; 2775 } 2776 shift_left: 2777 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2778 // the shifted type. 2779 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2780 if (SA != RHS) { 2781 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2782 << RHS << E->getType() << LHS.getBitWidth(); 2783 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2784 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2785 // operand, and must not overflow the corresponding unsigned type. 2786 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2787 // E1 x 2^E2 module 2^N. 2788 if (LHS.isNegative()) 2789 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2790 else if (LHS.countLeadingZeros() < SA) 2791 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2792 } 2793 Result = LHS << SA; 2794 return true; 2795 } 2796 case BO_Shr: { 2797 if (Info.getLangOpts().OpenCL) 2798 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2799 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2800 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2801 RHS.isUnsigned()); 2802 else if (RHS.isSigned() && RHS.isNegative()) { 2803 // During constant-folding, a negative shift is an opposite shift. Such a 2804 // shift is not a constant expression. 2805 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2806 RHS = -RHS; 2807 goto shift_left; 2808 } 2809 shift_right: 2810 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2811 // shifted type. 2812 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2813 if (SA != RHS) 2814 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2815 << RHS << E->getType() << LHS.getBitWidth(); 2816 Result = LHS >> SA; 2817 return true; 2818 } 2819 2820 case BO_LT: Result = LHS < RHS; return true; 2821 case BO_GT: Result = LHS > RHS; return true; 2822 case BO_LE: Result = LHS <= RHS; return true; 2823 case BO_GE: Result = LHS >= RHS; return true; 2824 case BO_EQ: Result = LHS == RHS; return true; 2825 case BO_NE: Result = LHS != RHS; return true; 2826 case BO_Cmp: 2827 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2828 } 2829 } 2830 2831 /// Perform the given binary floating-point operation, in-place, on LHS. 2832 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2833 APFloat &LHS, BinaryOperatorKind Opcode, 2834 const APFloat &RHS) { 2835 bool DynamicRM; 2836 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2837 APFloat::opStatus St; 2838 switch (Opcode) { 2839 default: 2840 Info.FFDiag(E); 2841 return false; 2842 case BO_Mul: 2843 St = LHS.multiply(RHS, RM); 2844 break; 2845 case BO_Add: 2846 St = LHS.add(RHS, RM); 2847 break; 2848 case BO_Sub: 2849 St = LHS.subtract(RHS, RM); 2850 break; 2851 case BO_Div: 2852 // [expr.mul]p4: 2853 // If the second operand of / or % is zero the behavior is undefined. 2854 if (RHS.isZero()) 2855 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2856 St = LHS.divide(RHS, RM); 2857 break; 2858 } 2859 2860 // [expr.pre]p4: 2861 // If during the evaluation of an expression, the result is not 2862 // mathematically defined [...], the behavior is undefined. 2863 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2864 if (LHS.isNaN()) { 2865 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2866 return Info.noteUndefinedBehavior(); 2867 } 2868 2869 return checkFloatingPointResult(Info, E, St); 2870 } 2871 2872 static bool handleLogicalOpForVector(const APInt &LHSValue, 2873 BinaryOperatorKind Opcode, 2874 const APInt &RHSValue, APInt &Result) { 2875 bool LHS = (LHSValue != 0); 2876 bool RHS = (RHSValue != 0); 2877 2878 if (Opcode == BO_LAnd) 2879 Result = LHS && RHS; 2880 else 2881 Result = LHS || RHS; 2882 return true; 2883 } 2884 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2885 BinaryOperatorKind Opcode, 2886 const APFloat &RHSValue, APInt &Result) { 2887 bool LHS = !LHSValue.isZero(); 2888 bool RHS = !RHSValue.isZero(); 2889 2890 if (Opcode == BO_LAnd) 2891 Result = LHS && RHS; 2892 else 2893 Result = LHS || RHS; 2894 return true; 2895 } 2896 2897 static bool handleLogicalOpForVector(const APValue &LHSValue, 2898 BinaryOperatorKind Opcode, 2899 const APValue &RHSValue, APInt &Result) { 2900 // The result is always an int type, however operands match the first. 2901 if (LHSValue.getKind() == APValue::Int) 2902 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2903 RHSValue.getInt(), Result); 2904 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2905 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2906 RHSValue.getFloat(), Result); 2907 } 2908 2909 template <typename APTy> 2910 static bool 2911 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2912 const APTy &RHSValue, APInt &Result) { 2913 switch (Opcode) { 2914 default: 2915 llvm_unreachable("unsupported binary operator"); 2916 case BO_EQ: 2917 Result = (LHSValue == RHSValue); 2918 break; 2919 case BO_NE: 2920 Result = (LHSValue != RHSValue); 2921 break; 2922 case BO_LT: 2923 Result = (LHSValue < RHSValue); 2924 break; 2925 case BO_GT: 2926 Result = (LHSValue > RHSValue); 2927 break; 2928 case BO_LE: 2929 Result = (LHSValue <= RHSValue); 2930 break; 2931 case BO_GE: 2932 Result = (LHSValue >= RHSValue); 2933 break; 2934 } 2935 2936 return true; 2937 } 2938 2939 static bool handleCompareOpForVector(const APValue &LHSValue, 2940 BinaryOperatorKind Opcode, 2941 const APValue &RHSValue, APInt &Result) { 2942 // The result is always an int type, however operands match the first. 2943 if (LHSValue.getKind() == APValue::Int) 2944 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2945 RHSValue.getInt(), Result); 2946 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2947 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2948 RHSValue.getFloat(), Result); 2949 } 2950 2951 // Perform binary operations for vector types, in place on the LHS. 2952 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2953 BinaryOperatorKind Opcode, 2954 APValue &LHSValue, 2955 const APValue &RHSValue) { 2956 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2957 "Operation not supported on vector types"); 2958 2959 const auto *VT = E->getType()->castAs<VectorType>(); 2960 unsigned NumElements = VT->getNumElements(); 2961 QualType EltTy = VT->getElementType(); 2962 2963 // In the cases (typically C as I've observed) where we aren't evaluating 2964 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2965 // just give up. 2966 if (!LHSValue.isVector()) { 2967 assert(LHSValue.isLValue() && 2968 "A vector result that isn't a vector OR uncalculated LValue"); 2969 Info.FFDiag(E); 2970 return false; 2971 } 2972 2973 assert(LHSValue.getVectorLength() == NumElements && 2974 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2975 2976 SmallVector<APValue, 4> ResultElements; 2977 2978 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2979 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2980 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2981 2982 if (EltTy->isIntegerType()) { 2983 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2984 EltTy->isUnsignedIntegerType()}; 2985 bool Success = true; 2986 2987 if (BinaryOperator::isLogicalOp(Opcode)) 2988 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2989 else if (BinaryOperator::isComparisonOp(Opcode)) 2990 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2991 else 2992 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2993 RHSElt.getInt(), EltResult); 2994 2995 if (!Success) { 2996 Info.FFDiag(E); 2997 return false; 2998 } 2999 ResultElements.emplace_back(EltResult); 3000 3001 } else if (EltTy->isFloatingType()) { 3002 assert(LHSElt.getKind() == APValue::Float && 3003 RHSElt.getKind() == APValue::Float && 3004 "Mismatched LHS/RHS/Result Type"); 3005 APFloat LHSFloat = LHSElt.getFloat(); 3006 3007 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3008 RHSElt.getFloat())) { 3009 Info.FFDiag(E); 3010 return false; 3011 } 3012 3013 ResultElements.emplace_back(LHSFloat); 3014 } 3015 } 3016 3017 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3018 return true; 3019 } 3020 3021 /// Cast an lvalue referring to a base subobject to a derived class, by 3022 /// truncating the lvalue's path to the given length. 3023 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3024 const RecordDecl *TruncatedType, 3025 unsigned TruncatedElements) { 3026 SubobjectDesignator &D = Result.Designator; 3027 3028 // Check we actually point to a derived class object. 3029 if (TruncatedElements == D.Entries.size()) 3030 return true; 3031 assert(TruncatedElements >= D.MostDerivedPathLength && 3032 "not casting to a derived class"); 3033 if (!Result.checkSubobject(Info, E, CSK_Derived)) 3034 return false; 3035 3036 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3037 const RecordDecl *RD = TruncatedType; 3038 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3039 if (RD->isInvalidDecl()) return false; 3040 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3041 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3042 if (isVirtualBaseClass(D.Entries[I])) 3043 Result.Offset -= Layout.getVBaseClassOffset(Base); 3044 else 3045 Result.Offset -= Layout.getBaseClassOffset(Base); 3046 RD = Base; 3047 } 3048 D.Entries.resize(TruncatedElements); 3049 return true; 3050 } 3051 3052 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3053 const CXXRecordDecl *Derived, 3054 const CXXRecordDecl *Base, 3055 const ASTRecordLayout *RL = nullptr) { 3056 if (!RL) { 3057 if (Derived->isInvalidDecl()) return false; 3058 RL = &Info.Ctx.getASTRecordLayout(Derived); 3059 } 3060 3061 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3062 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3063 return true; 3064 } 3065 3066 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3067 const CXXRecordDecl *DerivedDecl, 3068 const CXXBaseSpecifier *Base) { 3069 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3070 3071 if (!Base->isVirtual()) 3072 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3073 3074 SubobjectDesignator &D = Obj.Designator; 3075 if (D.Invalid) 3076 return false; 3077 3078 // Extract most-derived object and corresponding type. 3079 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3080 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3081 return false; 3082 3083 // Find the virtual base class. 3084 if (DerivedDecl->isInvalidDecl()) return false; 3085 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3086 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3087 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3088 return true; 3089 } 3090 3091 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3092 QualType Type, LValue &Result) { 3093 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3094 PathE = E->path_end(); 3095 PathI != PathE; ++PathI) { 3096 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3097 *PathI)) 3098 return false; 3099 Type = (*PathI)->getType(); 3100 } 3101 return true; 3102 } 3103 3104 /// Cast an lvalue referring to a derived class to a known base subobject. 3105 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3106 const CXXRecordDecl *DerivedRD, 3107 const CXXRecordDecl *BaseRD) { 3108 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3109 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3110 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3111 llvm_unreachable("Class must be derived from the passed in base class!"); 3112 3113 for (CXXBasePathElement &Elem : Paths.front()) 3114 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3115 return false; 3116 return true; 3117 } 3118 3119 /// Update LVal to refer to the given field, which must be a member of the type 3120 /// currently described by LVal. 3121 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3122 const FieldDecl *FD, 3123 const ASTRecordLayout *RL = nullptr) { 3124 if (!RL) { 3125 if (FD->getParent()->isInvalidDecl()) return false; 3126 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3127 } 3128 3129 unsigned I = FD->getFieldIndex(); 3130 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3131 LVal.addDecl(Info, E, FD); 3132 return true; 3133 } 3134 3135 /// Update LVal to refer to the given indirect field. 3136 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3137 LValue &LVal, 3138 const IndirectFieldDecl *IFD) { 3139 for (const auto *C : IFD->chain()) 3140 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3141 return false; 3142 return true; 3143 } 3144 3145 /// Get the size of the given type in char units. 3146 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3147 QualType Type, CharUnits &Size) { 3148 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3149 // extension. 3150 if (Type->isVoidType() || Type->isFunctionType()) { 3151 Size = CharUnits::One(); 3152 return true; 3153 } 3154 3155 if (Type->isDependentType()) { 3156 Info.FFDiag(Loc); 3157 return false; 3158 } 3159 3160 if (!Type->isConstantSizeType()) { 3161 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3162 // FIXME: Better diagnostic. 3163 Info.FFDiag(Loc); 3164 return false; 3165 } 3166 3167 Size = Info.Ctx.getTypeSizeInChars(Type); 3168 return true; 3169 } 3170 3171 /// Update a pointer value to model pointer arithmetic. 3172 /// \param Info - Information about the ongoing evaluation. 3173 /// \param E - The expression being evaluated, for diagnostic purposes. 3174 /// \param LVal - The pointer value to be updated. 3175 /// \param EltTy - The pointee type represented by LVal. 3176 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3177 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3178 LValue &LVal, QualType EltTy, 3179 APSInt Adjustment) { 3180 CharUnits SizeOfPointee; 3181 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3182 return false; 3183 3184 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3185 return true; 3186 } 3187 3188 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3189 LValue &LVal, QualType EltTy, 3190 int64_t Adjustment) { 3191 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3192 APSInt::get(Adjustment)); 3193 } 3194 3195 /// Update an lvalue to refer to a component of a complex number. 3196 /// \param Info - Information about the ongoing evaluation. 3197 /// \param LVal - The lvalue to be updated. 3198 /// \param EltTy - The complex number's component type. 3199 /// \param Imag - False for the real component, true for the imaginary. 3200 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3201 LValue &LVal, QualType EltTy, 3202 bool Imag) { 3203 if (Imag) { 3204 CharUnits SizeOfComponent; 3205 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3206 return false; 3207 LVal.Offset += SizeOfComponent; 3208 } 3209 LVal.addComplex(Info, E, EltTy, Imag); 3210 return true; 3211 } 3212 3213 /// Try to evaluate the initializer for a variable declaration. 3214 /// 3215 /// \param Info Information about the ongoing evaluation. 3216 /// \param E An expression to be used when printing diagnostics. 3217 /// \param VD The variable whose initializer should be obtained. 3218 /// \param Version The version of the variable within the frame. 3219 /// \param Frame The frame in which the variable was created. Must be null 3220 /// if this variable is not local to the evaluation. 3221 /// \param Result Filled in with a pointer to the value of the variable. 3222 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3223 const VarDecl *VD, CallStackFrame *Frame, 3224 unsigned Version, APValue *&Result) { 3225 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3226 3227 // If this is a local variable, dig out its value. 3228 if (Frame) { 3229 Result = Frame->getTemporary(VD, Version); 3230 if (Result) 3231 return true; 3232 3233 if (!isa<ParmVarDecl>(VD)) { 3234 // Assume variables referenced within a lambda's call operator that were 3235 // not declared within the call operator are captures and during checking 3236 // of a potential constant expression, assume they are unknown constant 3237 // expressions. 3238 assert(isLambdaCallOperator(Frame->Callee) && 3239 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3240 "missing value for local variable"); 3241 if (Info.checkingPotentialConstantExpression()) 3242 return false; 3243 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3244 // still reachable at all? 3245 Info.FFDiag(E->getBeginLoc(), 3246 diag::note_unimplemented_constexpr_lambda_feature_ast) 3247 << "captures not currently allowed"; 3248 return false; 3249 } 3250 } 3251 3252 // If we're currently evaluating the initializer of this declaration, use that 3253 // in-flight value. 3254 if (Info.EvaluatingDecl == Base) { 3255 Result = Info.EvaluatingDeclValue; 3256 return true; 3257 } 3258 3259 if (isa<ParmVarDecl>(VD)) { 3260 // Assume parameters of a potential constant expression are usable in 3261 // constant expressions. 3262 if (!Info.checkingPotentialConstantExpression() || 3263 !Info.CurrentCall->Callee || 3264 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3265 if (Info.getLangOpts().CPlusPlus11) { 3266 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3267 << VD; 3268 NoteLValueLocation(Info, Base); 3269 } else { 3270 Info.FFDiag(E); 3271 } 3272 } 3273 return false; 3274 } 3275 3276 // Dig out the initializer, and use the declaration which it's attached to. 3277 // FIXME: We should eventually check whether the variable has a reachable 3278 // initializing declaration. 3279 const Expr *Init = VD->getAnyInitializer(VD); 3280 if (!Init) { 3281 // Don't diagnose during potential constant expression checking; an 3282 // initializer might be added later. 3283 if (!Info.checkingPotentialConstantExpression()) { 3284 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3285 << VD; 3286 NoteLValueLocation(Info, Base); 3287 } 3288 return false; 3289 } 3290 3291 if (Init->isValueDependent()) { 3292 // The DeclRefExpr is not value-dependent, but the variable it refers to 3293 // has a value-dependent initializer. This should only happen in 3294 // constant-folding cases, where the variable is not actually of a suitable 3295 // type for use in a constant expression (otherwise the DeclRefExpr would 3296 // have been value-dependent too), so diagnose that. 3297 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3298 if (!Info.checkingPotentialConstantExpression()) { 3299 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3300 ? diag::note_constexpr_ltor_non_constexpr 3301 : diag::note_constexpr_ltor_non_integral, 1) 3302 << VD << VD->getType(); 3303 NoteLValueLocation(Info, Base); 3304 } 3305 return false; 3306 } 3307 3308 // Check that we can fold the initializer. In C++, we will have already done 3309 // this in the cases where it matters for conformance. 3310 if (!VD->evaluateValue()) { 3311 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3312 NoteLValueLocation(Info, Base); 3313 return false; 3314 } 3315 3316 // Check that the variable is actually usable in constant expressions. For a 3317 // const integral variable or a reference, we might have a non-constant 3318 // initializer that we can nonetheless evaluate the initializer for. Such 3319 // variables are not usable in constant expressions. In C++98, the 3320 // initializer also syntactically needs to be an ICE. 3321 // 3322 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3323 // expressions here; doing so would regress diagnostics for things like 3324 // reading from a volatile constexpr variable. 3325 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3326 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3327 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3328 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3329 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3330 NoteLValueLocation(Info, Base); 3331 } 3332 3333 // Never use the initializer of a weak variable, not even for constant 3334 // folding. We can't be sure that this is the definition that will be used. 3335 if (VD->isWeak()) { 3336 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3337 NoteLValueLocation(Info, Base); 3338 return false; 3339 } 3340 3341 Result = VD->getEvaluatedValue(); 3342 return true; 3343 } 3344 3345 /// Get the base index of the given base class within an APValue representing 3346 /// the given derived class. 3347 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3348 const CXXRecordDecl *Base) { 3349 Base = Base->getCanonicalDecl(); 3350 unsigned Index = 0; 3351 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3352 E = Derived->bases_end(); I != E; ++I, ++Index) { 3353 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3354 return Index; 3355 } 3356 3357 llvm_unreachable("base class missing from derived class's bases list"); 3358 } 3359 3360 /// Extract the value of a character from a string literal. 3361 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3362 uint64_t Index) { 3363 assert(!isa<SourceLocExpr>(Lit) && 3364 "SourceLocExpr should have already been converted to a StringLiteral"); 3365 3366 // FIXME: Support MakeStringConstant 3367 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3368 std::string Str; 3369 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3370 assert(Index <= Str.size() && "Index too large"); 3371 return APSInt::getUnsigned(Str.c_str()[Index]); 3372 } 3373 3374 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3375 Lit = PE->getFunctionName(); 3376 const StringLiteral *S = cast<StringLiteral>(Lit); 3377 const ConstantArrayType *CAT = 3378 Info.Ctx.getAsConstantArrayType(S->getType()); 3379 assert(CAT && "string literal isn't an array"); 3380 QualType CharType = CAT->getElementType(); 3381 assert(CharType->isIntegerType() && "unexpected character type"); 3382 3383 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3384 CharType->isUnsignedIntegerType()); 3385 if (Index < S->getLength()) 3386 Value = S->getCodeUnit(Index); 3387 return Value; 3388 } 3389 3390 // Expand a string literal into an array of characters. 3391 // 3392 // FIXME: This is inefficient; we should probably introduce something similar 3393 // to the LLVM ConstantDataArray to make this cheaper. 3394 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3395 APValue &Result, 3396 QualType AllocType = QualType()) { 3397 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3398 AllocType.isNull() ? S->getType() : AllocType); 3399 assert(CAT && "string literal isn't an array"); 3400 QualType CharType = CAT->getElementType(); 3401 assert(CharType->isIntegerType() && "unexpected character type"); 3402 3403 unsigned Elts = CAT->getSize().getZExtValue(); 3404 Result = APValue(APValue::UninitArray(), 3405 std::min(S->getLength(), Elts), Elts); 3406 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3407 CharType->isUnsignedIntegerType()); 3408 if (Result.hasArrayFiller()) 3409 Result.getArrayFiller() = APValue(Value); 3410 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3411 Value = S->getCodeUnit(I); 3412 Result.getArrayInitializedElt(I) = APValue(Value); 3413 } 3414 } 3415 3416 // Expand an array so that it has more than Index filled elements. 3417 static void expandArray(APValue &Array, unsigned Index) { 3418 unsigned Size = Array.getArraySize(); 3419 assert(Index < Size); 3420 3421 // Always at least double the number of elements for which we store a value. 3422 unsigned OldElts = Array.getArrayInitializedElts(); 3423 unsigned NewElts = std::max(Index+1, OldElts * 2); 3424 NewElts = std::min(Size, std::max(NewElts, 8u)); 3425 3426 // Copy the data across. 3427 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3428 for (unsigned I = 0; I != OldElts; ++I) 3429 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3430 for (unsigned I = OldElts; I != NewElts; ++I) 3431 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3432 if (NewValue.hasArrayFiller()) 3433 NewValue.getArrayFiller() = Array.getArrayFiller(); 3434 Array.swap(NewValue); 3435 } 3436 3437 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3438 /// conversion. If it's of class type, we may assume that the copy operation 3439 /// is trivial. Note that this is never true for a union type with fields 3440 /// (because the copy always "reads" the active member) and always true for 3441 /// a non-class type. 3442 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3443 static bool isReadByLvalueToRvalueConversion(QualType T) { 3444 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3445 return !RD || isReadByLvalueToRvalueConversion(RD); 3446 } 3447 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3448 // FIXME: A trivial copy of a union copies the object representation, even if 3449 // the union is empty. 3450 if (RD->isUnion()) 3451 return !RD->field_empty(); 3452 if (RD->isEmpty()) 3453 return false; 3454 3455 for (auto *Field : RD->fields()) 3456 if (!Field->isUnnamedBitfield() && 3457 isReadByLvalueToRvalueConversion(Field->getType())) 3458 return true; 3459 3460 for (auto &BaseSpec : RD->bases()) 3461 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3462 return true; 3463 3464 return false; 3465 } 3466 3467 /// Diagnose an attempt to read from any unreadable field within the specified 3468 /// type, which might be a class type. 3469 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3470 QualType T) { 3471 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3472 if (!RD) 3473 return false; 3474 3475 if (!RD->hasMutableFields()) 3476 return false; 3477 3478 for (auto *Field : RD->fields()) { 3479 // If we're actually going to read this field in some way, then it can't 3480 // be mutable. If we're in a union, then assigning to a mutable field 3481 // (even an empty one) can change the active member, so that's not OK. 3482 // FIXME: Add core issue number for the union case. 3483 if (Field->isMutable() && 3484 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3485 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3486 Info.Note(Field->getLocation(), diag::note_declared_at); 3487 return true; 3488 } 3489 3490 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3491 return true; 3492 } 3493 3494 for (auto &BaseSpec : RD->bases()) 3495 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3496 return true; 3497 3498 // All mutable fields were empty, and thus not actually read. 3499 return false; 3500 } 3501 3502 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3503 APValue::LValueBase Base, 3504 bool MutableSubobject = false) { 3505 // A temporary or transient heap allocation we created. 3506 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3507 return true; 3508 3509 switch (Info.IsEvaluatingDecl) { 3510 case EvalInfo::EvaluatingDeclKind::None: 3511 return false; 3512 3513 case EvalInfo::EvaluatingDeclKind::Ctor: 3514 // The variable whose initializer we're evaluating. 3515 if (Info.EvaluatingDecl == Base) 3516 return true; 3517 3518 // A temporary lifetime-extended by the variable whose initializer we're 3519 // evaluating. 3520 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3521 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3522 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3523 return false; 3524 3525 case EvalInfo::EvaluatingDeclKind::Dtor: 3526 // C++2a [expr.const]p6: 3527 // [during constant destruction] the lifetime of a and its non-mutable 3528 // subobjects (but not its mutable subobjects) [are] considered to start 3529 // within e. 3530 if (MutableSubobject || Base != Info.EvaluatingDecl) 3531 return false; 3532 // FIXME: We can meaningfully extend this to cover non-const objects, but 3533 // we will need special handling: we should be able to access only 3534 // subobjects of such objects that are themselves declared const. 3535 QualType T = getType(Base); 3536 return T.isConstQualified() || T->isReferenceType(); 3537 } 3538 3539 llvm_unreachable("unknown evaluating decl kind"); 3540 } 3541 3542 namespace { 3543 /// A handle to a complete object (an object that is not a subobject of 3544 /// another object). 3545 struct CompleteObject { 3546 /// The identity of the object. 3547 APValue::LValueBase Base; 3548 /// The value of the complete object. 3549 APValue *Value; 3550 /// The type of the complete object. 3551 QualType Type; 3552 3553 CompleteObject() : Value(nullptr) {} 3554 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3555 : Base(Base), Value(Value), Type(Type) {} 3556 3557 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3558 // If this isn't a "real" access (eg, if it's just accessing the type 3559 // info), allow it. We assume the type doesn't change dynamically for 3560 // subobjects of constexpr objects (even though we'd hit UB here if it 3561 // did). FIXME: Is this right? 3562 if (!isAnyAccess(AK)) 3563 return true; 3564 3565 // In C++14 onwards, it is permitted to read a mutable member whose 3566 // lifetime began within the evaluation. 3567 // FIXME: Should we also allow this in C++11? 3568 if (!Info.getLangOpts().CPlusPlus14) 3569 return false; 3570 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3571 } 3572 3573 explicit operator bool() const { return !Type.isNull(); } 3574 }; 3575 } // end anonymous namespace 3576 3577 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3578 bool IsMutable = false) { 3579 // C++ [basic.type.qualifier]p1: 3580 // - A const object is an object of type const T or a non-mutable subobject 3581 // of a const object. 3582 if (ObjType.isConstQualified() && !IsMutable) 3583 SubobjType.addConst(); 3584 // - A volatile object is an object of type const T or a subobject of a 3585 // volatile object. 3586 if (ObjType.isVolatileQualified()) 3587 SubobjType.addVolatile(); 3588 return SubobjType; 3589 } 3590 3591 /// Find the designated sub-object of an rvalue. 3592 template<typename SubobjectHandler> 3593 typename SubobjectHandler::result_type 3594 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3595 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3596 if (Sub.Invalid) 3597 // A diagnostic will have already been produced. 3598 return handler.failed(); 3599 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3600 if (Info.getLangOpts().CPlusPlus11) 3601 Info.FFDiag(E, Sub.isOnePastTheEnd() 3602 ? diag::note_constexpr_access_past_end 3603 : diag::note_constexpr_access_unsized_array) 3604 << handler.AccessKind; 3605 else 3606 Info.FFDiag(E); 3607 return handler.failed(); 3608 } 3609 3610 APValue *O = Obj.Value; 3611 QualType ObjType = Obj.Type; 3612 const FieldDecl *LastField = nullptr; 3613 const FieldDecl *VolatileField = nullptr; 3614 3615 // Walk the designator's path to find the subobject. 3616 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3617 // Reading an indeterminate value is undefined, but assigning over one is OK. 3618 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3619 (O->isIndeterminate() && 3620 !isValidIndeterminateAccess(handler.AccessKind))) { 3621 if (!Info.checkingPotentialConstantExpression()) 3622 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3623 << handler.AccessKind << O->isIndeterminate(); 3624 return handler.failed(); 3625 } 3626 3627 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3628 // const and volatile semantics are not applied on an object under 3629 // {con,de}struction. 3630 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3631 ObjType->isRecordType() && 3632 Info.isEvaluatingCtorDtor( 3633 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3634 Sub.Entries.begin() + I)) != 3635 ConstructionPhase::None) { 3636 ObjType = Info.Ctx.getCanonicalType(ObjType); 3637 ObjType.removeLocalConst(); 3638 ObjType.removeLocalVolatile(); 3639 } 3640 3641 // If this is our last pass, check that the final object type is OK. 3642 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3643 // Accesses to volatile objects are prohibited. 3644 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3645 if (Info.getLangOpts().CPlusPlus) { 3646 int DiagKind; 3647 SourceLocation Loc; 3648 const NamedDecl *Decl = nullptr; 3649 if (VolatileField) { 3650 DiagKind = 2; 3651 Loc = VolatileField->getLocation(); 3652 Decl = VolatileField; 3653 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3654 DiagKind = 1; 3655 Loc = VD->getLocation(); 3656 Decl = VD; 3657 } else { 3658 DiagKind = 0; 3659 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3660 Loc = E->getExprLoc(); 3661 } 3662 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3663 << handler.AccessKind << DiagKind << Decl; 3664 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3665 } else { 3666 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3667 } 3668 return handler.failed(); 3669 } 3670 3671 // If we are reading an object of class type, there may still be more 3672 // things we need to check: if there are any mutable subobjects, we 3673 // cannot perform this read. (This only happens when performing a trivial 3674 // copy or assignment.) 3675 if (ObjType->isRecordType() && 3676 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3677 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3678 return handler.failed(); 3679 } 3680 3681 if (I == N) { 3682 if (!handler.found(*O, ObjType)) 3683 return false; 3684 3685 // If we modified a bit-field, truncate it to the right width. 3686 if (isModification(handler.AccessKind) && 3687 LastField && LastField->isBitField() && 3688 !truncateBitfieldValue(Info, E, *O, LastField)) 3689 return false; 3690 3691 return true; 3692 } 3693 3694 LastField = nullptr; 3695 if (ObjType->isArrayType()) { 3696 // Next subobject is an array element. 3697 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3698 assert(CAT && "vla in literal type?"); 3699 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3700 if (CAT->getSize().ule(Index)) { 3701 // Note, it should not be possible to form a pointer with a valid 3702 // designator which points more than one past the end of the array. 3703 if (Info.getLangOpts().CPlusPlus11) 3704 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3705 << handler.AccessKind; 3706 else 3707 Info.FFDiag(E); 3708 return handler.failed(); 3709 } 3710 3711 ObjType = CAT->getElementType(); 3712 3713 if (O->getArrayInitializedElts() > Index) 3714 O = &O->getArrayInitializedElt(Index); 3715 else if (!isRead(handler.AccessKind)) { 3716 expandArray(*O, Index); 3717 O = &O->getArrayInitializedElt(Index); 3718 } else 3719 O = &O->getArrayFiller(); 3720 } else if (ObjType->isAnyComplexType()) { 3721 // Next subobject is a complex number. 3722 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3723 if (Index > 1) { 3724 if (Info.getLangOpts().CPlusPlus11) 3725 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3726 << handler.AccessKind; 3727 else 3728 Info.FFDiag(E); 3729 return handler.failed(); 3730 } 3731 3732 ObjType = getSubobjectType( 3733 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3734 3735 assert(I == N - 1 && "extracting subobject of scalar?"); 3736 if (O->isComplexInt()) { 3737 return handler.found(Index ? O->getComplexIntImag() 3738 : O->getComplexIntReal(), ObjType); 3739 } else { 3740 assert(O->isComplexFloat()); 3741 return handler.found(Index ? O->getComplexFloatImag() 3742 : O->getComplexFloatReal(), ObjType); 3743 } 3744 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3745 if (Field->isMutable() && 3746 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3747 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3748 << handler.AccessKind << Field; 3749 Info.Note(Field->getLocation(), diag::note_declared_at); 3750 return handler.failed(); 3751 } 3752 3753 // Next subobject is a class, struct or union field. 3754 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3755 if (RD->isUnion()) { 3756 const FieldDecl *UnionField = O->getUnionField(); 3757 if (!UnionField || 3758 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3759 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3760 // Placement new onto an inactive union member makes it active. 3761 O->setUnion(Field, APValue()); 3762 } else { 3763 // FIXME: If O->getUnionValue() is absent, report that there's no 3764 // active union member rather than reporting the prior active union 3765 // member. We'll need to fix nullptr_t to not use APValue() as its 3766 // representation first. 3767 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3768 << handler.AccessKind << Field << !UnionField << UnionField; 3769 return handler.failed(); 3770 } 3771 } 3772 O = &O->getUnionValue(); 3773 } else 3774 O = &O->getStructField(Field->getFieldIndex()); 3775 3776 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3777 LastField = Field; 3778 if (Field->getType().isVolatileQualified()) 3779 VolatileField = Field; 3780 } else { 3781 // Next subobject is a base class. 3782 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3783 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3784 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3785 3786 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3787 } 3788 } 3789 } 3790 3791 namespace { 3792 struct ExtractSubobjectHandler { 3793 EvalInfo &Info; 3794 const Expr *E; 3795 APValue &Result; 3796 const AccessKinds AccessKind; 3797 3798 typedef bool result_type; 3799 bool failed() { return false; } 3800 bool found(APValue &Subobj, QualType SubobjType) { 3801 Result = Subobj; 3802 if (AccessKind == AK_ReadObjectRepresentation) 3803 return true; 3804 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3805 } 3806 bool found(APSInt &Value, QualType SubobjType) { 3807 Result = APValue(Value); 3808 return true; 3809 } 3810 bool found(APFloat &Value, QualType SubobjType) { 3811 Result = APValue(Value); 3812 return true; 3813 } 3814 }; 3815 } // end anonymous namespace 3816 3817 /// Extract the designated sub-object of an rvalue. 3818 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3819 const CompleteObject &Obj, 3820 const SubobjectDesignator &Sub, APValue &Result, 3821 AccessKinds AK = AK_Read) { 3822 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3823 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3824 return findSubobject(Info, E, Obj, Sub, Handler); 3825 } 3826 3827 namespace { 3828 struct ModifySubobjectHandler { 3829 EvalInfo &Info; 3830 APValue &NewVal; 3831 const Expr *E; 3832 3833 typedef bool result_type; 3834 static const AccessKinds AccessKind = AK_Assign; 3835 3836 bool checkConst(QualType QT) { 3837 // Assigning to a const object has undefined behavior. 3838 if (QT.isConstQualified()) { 3839 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3840 return false; 3841 } 3842 return true; 3843 } 3844 3845 bool failed() { return false; } 3846 bool found(APValue &Subobj, QualType SubobjType) { 3847 if (!checkConst(SubobjType)) 3848 return false; 3849 // We've been given ownership of NewVal, so just swap it in. 3850 Subobj.swap(NewVal); 3851 return true; 3852 } 3853 bool found(APSInt &Value, QualType SubobjType) { 3854 if (!checkConst(SubobjType)) 3855 return false; 3856 if (!NewVal.isInt()) { 3857 // Maybe trying to write a cast pointer value into a complex? 3858 Info.FFDiag(E); 3859 return false; 3860 } 3861 Value = NewVal.getInt(); 3862 return true; 3863 } 3864 bool found(APFloat &Value, QualType SubobjType) { 3865 if (!checkConst(SubobjType)) 3866 return false; 3867 Value = NewVal.getFloat(); 3868 return true; 3869 } 3870 }; 3871 } // end anonymous namespace 3872 3873 const AccessKinds ModifySubobjectHandler::AccessKind; 3874 3875 /// Update the designated sub-object of an rvalue to the given value. 3876 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3877 const CompleteObject &Obj, 3878 const SubobjectDesignator &Sub, 3879 APValue &NewVal) { 3880 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3881 return findSubobject(Info, E, Obj, Sub, Handler); 3882 } 3883 3884 /// Find the position where two subobject designators diverge, or equivalently 3885 /// the length of the common initial subsequence. 3886 static unsigned FindDesignatorMismatch(QualType ObjType, 3887 const SubobjectDesignator &A, 3888 const SubobjectDesignator &B, 3889 bool &WasArrayIndex) { 3890 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3891 for (/**/; I != N; ++I) { 3892 if (!ObjType.isNull() && 3893 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3894 // Next subobject is an array element. 3895 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3896 WasArrayIndex = true; 3897 return I; 3898 } 3899 if (ObjType->isAnyComplexType()) 3900 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3901 else 3902 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3903 } else { 3904 if (A.Entries[I].getAsBaseOrMember() != 3905 B.Entries[I].getAsBaseOrMember()) { 3906 WasArrayIndex = false; 3907 return I; 3908 } 3909 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3910 // Next subobject is a field. 3911 ObjType = FD->getType(); 3912 else 3913 // Next subobject is a base class. 3914 ObjType = QualType(); 3915 } 3916 } 3917 WasArrayIndex = false; 3918 return I; 3919 } 3920 3921 /// Determine whether the given subobject designators refer to elements of the 3922 /// same array object. 3923 static bool AreElementsOfSameArray(QualType ObjType, 3924 const SubobjectDesignator &A, 3925 const SubobjectDesignator &B) { 3926 if (A.Entries.size() != B.Entries.size()) 3927 return false; 3928 3929 bool IsArray = A.MostDerivedIsArrayElement; 3930 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3931 // A is a subobject of the array element. 3932 return false; 3933 3934 // If A (and B) designates an array element, the last entry will be the array 3935 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3936 // of length 1' case, and the entire path must match. 3937 bool WasArrayIndex; 3938 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3939 return CommonLength >= A.Entries.size() - IsArray; 3940 } 3941 3942 /// Find the complete object to which an LValue refers. 3943 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3944 AccessKinds AK, const LValue &LVal, 3945 QualType LValType) { 3946 if (LVal.InvalidBase) { 3947 Info.FFDiag(E); 3948 return CompleteObject(); 3949 } 3950 3951 if (!LVal.Base) { 3952 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3953 return CompleteObject(); 3954 } 3955 3956 CallStackFrame *Frame = nullptr; 3957 unsigned Depth = 0; 3958 if (LVal.getLValueCallIndex()) { 3959 std::tie(Frame, Depth) = 3960 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3961 if (!Frame) { 3962 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3963 << AK << LVal.Base.is<const ValueDecl*>(); 3964 NoteLValueLocation(Info, LVal.Base); 3965 return CompleteObject(); 3966 } 3967 } 3968 3969 bool IsAccess = isAnyAccess(AK); 3970 3971 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3972 // is not a constant expression (even if the object is non-volatile). We also 3973 // apply this rule to C++98, in order to conform to the expected 'volatile' 3974 // semantics. 3975 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3976 if (Info.getLangOpts().CPlusPlus) 3977 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3978 << AK << LValType; 3979 else 3980 Info.FFDiag(E); 3981 return CompleteObject(); 3982 } 3983 3984 // Compute value storage location and type of base object. 3985 APValue *BaseVal = nullptr; 3986 QualType BaseType = getType(LVal.Base); 3987 3988 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3989 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3990 // This is the object whose initializer we're evaluating, so its lifetime 3991 // started in the current evaluation. 3992 BaseVal = Info.EvaluatingDeclValue; 3993 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3994 // Allow reading from a GUID declaration. 3995 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3996 if (isModification(AK)) { 3997 // All the remaining cases do not permit modification of the object. 3998 Info.FFDiag(E, diag::note_constexpr_modify_global); 3999 return CompleteObject(); 4000 } 4001 APValue &V = GD->getAsAPValue(); 4002 if (V.isAbsent()) { 4003 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4004 << GD->getType(); 4005 return CompleteObject(); 4006 } 4007 return CompleteObject(LVal.Base, &V, GD->getType()); 4008 } 4009 4010 // Allow reading from template parameter objects. 4011 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4012 if (isModification(AK)) { 4013 Info.FFDiag(E, diag::note_constexpr_modify_global); 4014 return CompleteObject(); 4015 } 4016 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4017 TPO->getType()); 4018 } 4019 4020 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4021 // In C++11, constexpr, non-volatile variables initialized with constant 4022 // expressions are constant expressions too. Inside constexpr functions, 4023 // parameters are constant expressions even if they're non-const. 4024 // In C++1y, objects local to a constant expression (those with a Frame) are 4025 // both readable and writable inside constant expressions. 4026 // In C, such things can also be folded, although they are not ICEs. 4027 const VarDecl *VD = dyn_cast<VarDecl>(D); 4028 if (VD) { 4029 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4030 VD = VDef; 4031 } 4032 if (!VD || VD->isInvalidDecl()) { 4033 Info.FFDiag(E); 4034 return CompleteObject(); 4035 } 4036 4037 bool IsConstant = BaseType.isConstant(Info.Ctx); 4038 4039 // Unless we're looking at a local variable or argument in a constexpr call, 4040 // the variable we're reading must be const. 4041 if (!Frame) { 4042 if (IsAccess && isa<ParmVarDecl>(VD)) { 4043 // Access of a parameter that's not associated with a frame isn't going 4044 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4045 // suitable diagnostic. 4046 } else if (Info.getLangOpts().CPlusPlus14 && 4047 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4048 // OK, we can read and modify an object if we're in the process of 4049 // evaluating its initializer, because its lifetime began in this 4050 // evaluation. 4051 } else if (isModification(AK)) { 4052 // All the remaining cases do not permit modification of the object. 4053 Info.FFDiag(E, diag::note_constexpr_modify_global); 4054 return CompleteObject(); 4055 } else if (VD->isConstexpr()) { 4056 // OK, we can read this variable. 4057 } else if (BaseType->isIntegralOrEnumerationType()) { 4058 if (!IsConstant) { 4059 if (!IsAccess) 4060 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4061 if (Info.getLangOpts().CPlusPlus) { 4062 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4063 Info.Note(VD->getLocation(), diag::note_declared_at); 4064 } else { 4065 Info.FFDiag(E); 4066 } 4067 return CompleteObject(); 4068 } 4069 } else if (!IsAccess) { 4070 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4071 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4072 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4073 // This variable might end up being constexpr. Don't diagnose it yet. 4074 } else if (IsConstant) { 4075 // Keep evaluating to see what we can do. In particular, we support 4076 // folding of const floating-point types, in order to make static const 4077 // data members of such types (supported as an extension) more useful. 4078 if (Info.getLangOpts().CPlusPlus) { 4079 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4080 ? diag::note_constexpr_ltor_non_constexpr 4081 : diag::note_constexpr_ltor_non_integral, 1) 4082 << VD << BaseType; 4083 Info.Note(VD->getLocation(), diag::note_declared_at); 4084 } else { 4085 Info.CCEDiag(E); 4086 } 4087 } else { 4088 // Never allow reading a non-const value. 4089 if (Info.getLangOpts().CPlusPlus) { 4090 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4091 ? diag::note_constexpr_ltor_non_constexpr 4092 : diag::note_constexpr_ltor_non_integral, 1) 4093 << VD << BaseType; 4094 Info.Note(VD->getLocation(), diag::note_declared_at); 4095 } else { 4096 Info.FFDiag(E); 4097 } 4098 return CompleteObject(); 4099 } 4100 } 4101 4102 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4103 return CompleteObject(); 4104 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4105 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4106 if (!Alloc) { 4107 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4108 return CompleteObject(); 4109 } 4110 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4111 LVal.Base.getDynamicAllocType()); 4112 } else { 4113 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4114 4115 if (!Frame) { 4116 if (const MaterializeTemporaryExpr *MTE = 4117 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4118 assert(MTE->getStorageDuration() == SD_Static && 4119 "should have a frame for a non-global materialized temporary"); 4120 4121 // C++20 [expr.const]p4: [DR2126] 4122 // An object or reference is usable in constant expressions if it is 4123 // - a temporary object of non-volatile const-qualified literal type 4124 // whose lifetime is extended to that of a variable that is usable 4125 // in constant expressions 4126 // 4127 // C++20 [expr.const]p5: 4128 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4129 // - a non-volatile glvalue that refers to an object that is usable 4130 // in constant expressions, or 4131 // - a non-volatile glvalue of literal type that refers to a 4132 // non-volatile object whose lifetime began within the evaluation 4133 // of E; 4134 // 4135 // C++11 misses the 'began within the evaluation of e' check and 4136 // instead allows all temporaries, including things like: 4137 // int &&r = 1; 4138 // int x = ++r; 4139 // constexpr int k = r; 4140 // Therefore we use the C++14-onwards rules in C++11 too. 4141 // 4142 // Note that temporaries whose lifetimes began while evaluating a 4143 // variable's constructor are not usable while evaluating the 4144 // corresponding destructor, not even if they're of const-qualified 4145 // types. 4146 if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4147 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4148 if (!IsAccess) 4149 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4150 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4151 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4152 return CompleteObject(); 4153 } 4154 4155 BaseVal = MTE->getOrCreateValue(false); 4156 assert(BaseVal && "got reference to unevaluated temporary"); 4157 } else { 4158 if (!IsAccess) 4159 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4160 APValue Val; 4161 LVal.moveInto(Val); 4162 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4163 << AK 4164 << Val.getAsString(Info.Ctx, 4165 Info.Ctx.getLValueReferenceType(LValType)); 4166 NoteLValueLocation(Info, LVal.Base); 4167 return CompleteObject(); 4168 } 4169 } else { 4170 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4171 assert(BaseVal && "missing value for temporary"); 4172 } 4173 } 4174 4175 // In C++14, we can't safely access any mutable state when we might be 4176 // evaluating after an unmodeled side effect. Parameters are modeled as state 4177 // in the caller, but aren't visible once the call returns, so they can be 4178 // modified in a speculatively-evaluated call. 4179 // 4180 // FIXME: Not all local state is mutable. Allow local constant subobjects 4181 // to be read here (but take care with 'mutable' fields). 4182 unsigned VisibleDepth = Depth; 4183 if (llvm::isa_and_nonnull<ParmVarDecl>( 4184 LVal.Base.dyn_cast<const ValueDecl *>())) 4185 ++VisibleDepth; 4186 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4187 Info.EvalStatus.HasSideEffects) || 4188 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4189 return CompleteObject(); 4190 4191 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4192 } 4193 4194 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4195 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4196 /// glvalue referred to by an entity of reference type. 4197 /// 4198 /// \param Info - Information about the ongoing evaluation. 4199 /// \param Conv - The expression for which we are performing the conversion. 4200 /// Used for diagnostics. 4201 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4202 /// case of a non-class type). 4203 /// \param LVal - The glvalue on which we are attempting to perform this action. 4204 /// \param RVal - The produced value will be placed here. 4205 /// \param WantObjectRepresentation - If true, we're looking for the object 4206 /// representation rather than the value, and in particular, 4207 /// there is no requirement that the result be fully initialized. 4208 static bool 4209 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4210 const LValue &LVal, APValue &RVal, 4211 bool WantObjectRepresentation = false) { 4212 if (LVal.Designator.Invalid) 4213 return false; 4214 4215 // Check for special cases where there is no existing APValue to look at. 4216 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4217 4218 AccessKinds AK = 4219 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4220 4221 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4222 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4223 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4224 // initializer until now for such expressions. Such an expression can't be 4225 // an ICE in C, so this only matters for fold. 4226 if (Type.isVolatileQualified()) { 4227 Info.FFDiag(Conv); 4228 return false; 4229 } 4230 APValue Lit; 4231 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4232 return false; 4233 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4234 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4235 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4236 // Special-case character extraction so we don't have to construct an 4237 // APValue for the whole string. 4238 assert(LVal.Designator.Entries.size() <= 1 && 4239 "Can only read characters from string literals"); 4240 if (LVal.Designator.Entries.empty()) { 4241 // Fail for now for LValue to RValue conversion of an array. 4242 // (This shouldn't show up in C/C++, but it could be triggered by a 4243 // weird EvaluateAsRValue call from a tool.) 4244 Info.FFDiag(Conv); 4245 return false; 4246 } 4247 if (LVal.Designator.isOnePastTheEnd()) { 4248 if (Info.getLangOpts().CPlusPlus11) 4249 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4250 else 4251 Info.FFDiag(Conv); 4252 return false; 4253 } 4254 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4255 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4256 return true; 4257 } 4258 } 4259 4260 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4261 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4262 } 4263 4264 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4265 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4266 QualType LValType, APValue &Val) { 4267 if (LVal.Designator.Invalid) 4268 return false; 4269 4270 if (!Info.getLangOpts().CPlusPlus14) { 4271 Info.FFDiag(E); 4272 return false; 4273 } 4274 4275 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4276 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4277 } 4278 4279 namespace { 4280 struct CompoundAssignSubobjectHandler { 4281 EvalInfo &Info; 4282 const CompoundAssignOperator *E; 4283 QualType PromotedLHSType; 4284 BinaryOperatorKind Opcode; 4285 const APValue &RHS; 4286 4287 static const AccessKinds AccessKind = AK_Assign; 4288 4289 typedef bool result_type; 4290 4291 bool checkConst(QualType QT) { 4292 // Assigning to a const object has undefined behavior. 4293 if (QT.isConstQualified()) { 4294 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4295 return false; 4296 } 4297 return true; 4298 } 4299 4300 bool failed() { return false; } 4301 bool found(APValue &Subobj, QualType SubobjType) { 4302 switch (Subobj.getKind()) { 4303 case APValue::Int: 4304 return found(Subobj.getInt(), SubobjType); 4305 case APValue::Float: 4306 return found(Subobj.getFloat(), SubobjType); 4307 case APValue::ComplexInt: 4308 case APValue::ComplexFloat: 4309 // FIXME: Implement complex compound assignment. 4310 Info.FFDiag(E); 4311 return false; 4312 case APValue::LValue: 4313 return foundPointer(Subobj, SubobjType); 4314 case APValue::Vector: 4315 return foundVector(Subobj, SubobjType); 4316 default: 4317 // FIXME: can this happen? 4318 Info.FFDiag(E); 4319 return false; 4320 } 4321 } 4322 4323 bool foundVector(APValue &Value, QualType SubobjType) { 4324 if (!checkConst(SubobjType)) 4325 return false; 4326 4327 if (!SubobjType->isVectorType()) { 4328 Info.FFDiag(E); 4329 return false; 4330 } 4331 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4332 } 4333 4334 bool found(APSInt &Value, QualType SubobjType) { 4335 if (!checkConst(SubobjType)) 4336 return false; 4337 4338 if (!SubobjType->isIntegerType()) { 4339 // We don't support compound assignment on integer-cast-to-pointer 4340 // values. 4341 Info.FFDiag(E); 4342 return false; 4343 } 4344 4345 if (RHS.isInt()) { 4346 APSInt LHS = 4347 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4348 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4349 return false; 4350 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4351 return true; 4352 } else if (RHS.isFloat()) { 4353 const FPOptions FPO = E->getFPFeaturesInEffect( 4354 Info.Ctx.getLangOpts()); 4355 APFloat FValue(0.0); 4356 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4357 PromotedLHSType, FValue) && 4358 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4359 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4360 Value); 4361 } 4362 4363 Info.FFDiag(E); 4364 return false; 4365 } 4366 bool found(APFloat &Value, QualType SubobjType) { 4367 return checkConst(SubobjType) && 4368 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4369 Value) && 4370 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4371 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4372 } 4373 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4374 if (!checkConst(SubobjType)) 4375 return false; 4376 4377 QualType PointeeType; 4378 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4379 PointeeType = PT->getPointeeType(); 4380 4381 if (PointeeType.isNull() || !RHS.isInt() || 4382 (Opcode != BO_Add && Opcode != BO_Sub)) { 4383 Info.FFDiag(E); 4384 return false; 4385 } 4386 4387 APSInt Offset = RHS.getInt(); 4388 if (Opcode == BO_Sub) 4389 negateAsSigned(Offset); 4390 4391 LValue LVal; 4392 LVal.setFrom(Info.Ctx, Subobj); 4393 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4394 return false; 4395 LVal.moveInto(Subobj); 4396 return true; 4397 } 4398 }; 4399 } // end anonymous namespace 4400 4401 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4402 4403 /// Perform a compound assignment of LVal <op>= RVal. 4404 static bool handleCompoundAssignment(EvalInfo &Info, 4405 const CompoundAssignOperator *E, 4406 const LValue &LVal, QualType LValType, 4407 QualType PromotedLValType, 4408 BinaryOperatorKind Opcode, 4409 const APValue &RVal) { 4410 if (LVal.Designator.Invalid) 4411 return false; 4412 4413 if (!Info.getLangOpts().CPlusPlus14) { 4414 Info.FFDiag(E); 4415 return false; 4416 } 4417 4418 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4419 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4420 RVal }; 4421 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4422 } 4423 4424 namespace { 4425 struct IncDecSubobjectHandler { 4426 EvalInfo &Info; 4427 const UnaryOperator *E; 4428 AccessKinds AccessKind; 4429 APValue *Old; 4430 4431 typedef bool result_type; 4432 4433 bool checkConst(QualType QT) { 4434 // Assigning to a const object has undefined behavior. 4435 if (QT.isConstQualified()) { 4436 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4437 return false; 4438 } 4439 return true; 4440 } 4441 4442 bool failed() { return false; } 4443 bool found(APValue &Subobj, QualType SubobjType) { 4444 // Stash the old value. Also clear Old, so we don't clobber it later 4445 // if we're post-incrementing a complex. 4446 if (Old) { 4447 *Old = Subobj; 4448 Old = nullptr; 4449 } 4450 4451 switch (Subobj.getKind()) { 4452 case APValue::Int: 4453 return found(Subobj.getInt(), SubobjType); 4454 case APValue::Float: 4455 return found(Subobj.getFloat(), SubobjType); 4456 case APValue::ComplexInt: 4457 return found(Subobj.getComplexIntReal(), 4458 SubobjType->castAs<ComplexType>()->getElementType() 4459 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4460 case APValue::ComplexFloat: 4461 return found(Subobj.getComplexFloatReal(), 4462 SubobjType->castAs<ComplexType>()->getElementType() 4463 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4464 case APValue::LValue: 4465 return foundPointer(Subobj, SubobjType); 4466 default: 4467 // FIXME: can this happen? 4468 Info.FFDiag(E); 4469 return false; 4470 } 4471 } 4472 bool found(APSInt &Value, QualType SubobjType) { 4473 if (!checkConst(SubobjType)) 4474 return false; 4475 4476 if (!SubobjType->isIntegerType()) { 4477 // We don't support increment / decrement on integer-cast-to-pointer 4478 // values. 4479 Info.FFDiag(E); 4480 return false; 4481 } 4482 4483 if (Old) *Old = APValue(Value); 4484 4485 // bool arithmetic promotes to int, and the conversion back to bool 4486 // doesn't reduce mod 2^n, so special-case it. 4487 if (SubobjType->isBooleanType()) { 4488 if (AccessKind == AK_Increment) 4489 Value = 1; 4490 else 4491 Value = !Value; 4492 return true; 4493 } 4494 4495 bool WasNegative = Value.isNegative(); 4496 if (AccessKind == AK_Increment) { 4497 ++Value; 4498 4499 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4500 APSInt ActualValue(Value, /*IsUnsigned*/true); 4501 return HandleOverflow(Info, E, ActualValue, SubobjType); 4502 } 4503 } else { 4504 --Value; 4505 4506 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4507 unsigned BitWidth = Value.getBitWidth(); 4508 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4509 ActualValue.setBit(BitWidth); 4510 return HandleOverflow(Info, E, ActualValue, SubobjType); 4511 } 4512 } 4513 return true; 4514 } 4515 bool found(APFloat &Value, QualType SubobjType) { 4516 if (!checkConst(SubobjType)) 4517 return false; 4518 4519 if (Old) *Old = APValue(Value); 4520 4521 APFloat One(Value.getSemantics(), 1); 4522 if (AccessKind == AK_Increment) 4523 Value.add(One, APFloat::rmNearestTiesToEven); 4524 else 4525 Value.subtract(One, APFloat::rmNearestTiesToEven); 4526 return true; 4527 } 4528 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4529 if (!checkConst(SubobjType)) 4530 return false; 4531 4532 QualType PointeeType; 4533 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4534 PointeeType = PT->getPointeeType(); 4535 else { 4536 Info.FFDiag(E); 4537 return false; 4538 } 4539 4540 LValue LVal; 4541 LVal.setFrom(Info.Ctx, Subobj); 4542 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4543 AccessKind == AK_Increment ? 1 : -1)) 4544 return false; 4545 LVal.moveInto(Subobj); 4546 return true; 4547 } 4548 }; 4549 } // end anonymous namespace 4550 4551 /// Perform an increment or decrement on LVal. 4552 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4553 QualType LValType, bool IsIncrement, APValue *Old) { 4554 if (LVal.Designator.Invalid) 4555 return false; 4556 4557 if (!Info.getLangOpts().CPlusPlus14) { 4558 Info.FFDiag(E); 4559 return false; 4560 } 4561 4562 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4563 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4564 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4565 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4566 } 4567 4568 /// Build an lvalue for the object argument of a member function call. 4569 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4570 LValue &This) { 4571 if (Object->getType()->isPointerType() && Object->isRValue()) 4572 return EvaluatePointer(Object, This, Info); 4573 4574 if (Object->isGLValue()) 4575 return EvaluateLValue(Object, This, Info); 4576 4577 if (Object->getType()->isLiteralType(Info.Ctx)) 4578 return EvaluateTemporary(Object, This, Info); 4579 4580 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4581 return false; 4582 } 4583 4584 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4585 /// lvalue referring to the result. 4586 /// 4587 /// \param Info - Information about the ongoing evaluation. 4588 /// \param LV - An lvalue referring to the base of the member pointer. 4589 /// \param RHS - The member pointer expression. 4590 /// \param IncludeMember - Specifies whether the member itself is included in 4591 /// the resulting LValue subobject designator. This is not possible when 4592 /// creating a bound member function. 4593 /// \return The field or method declaration to which the member pointer refers, 4594 /// or 0 if evaluation fails. 4595 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4596 QualType LVType, 4597 LValue &LV, 4598 const Expr *RHS, 4599 bool IncludeMember = true) { 4600 MemberPtr MemPtr; 4601 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4602 return nullptr; 4603 4604 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4605 // member value, the behavior is undefined. 4606 if (!MemPtr.getDecl()) { 4607 // FIXME: Specific diagnostic. 4608 Info.FFDiag(RHS); 4609 return nullptr; 4610 } 4611 4612 if (MemPtr.isDerivedMember()) { 4613 // This is a member of some derived class. Truncate LV appropriately. 4614 // The end of the derived-to-base path for the base object must match the 4615 // derived-to-base path for the member pointer. 4616 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4617 LV.Designator.Entries.size()) { 4618 Info.FFDiag(RHS); 4619 return nullptr; 4620 } 4621 unsigned PathLengthToMember = 4622 LV.Designator.Entries.size() - MemPtr.Path.size(); 4623 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4624 const CXXRecordDecl *LVDecl = getAsBaseClass( 4625 LV.Designator.Entries[PathLengthToMember + I]); 4626 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4627 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4628 Info.FFDiag(RHS); 4629 return nullptr; 4630 } 4631 } 4632 4633 // Truncate the lvalue to the appropriate derived class. 4634 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4635 PathLengthToMember)) 4636 return nullptr; 4637 } else if (!MemPtr.Path.empty()) { 4638 // Extend the LValue path with the member pointer's path. 4639 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4640 MemPtr.Path.size() + IncludeMember); 4641 4642 // Walk down to the appropriate base class. 4643 if (const PointerType *PT = LVType->getAs<PointerType>()) 4644 LVType = PT->getPointeeType(); 4645 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4646 assert(RD && "member pointer access on non-class-type expression"); 4647 // The first class in the path is that of the lvalue. 4648 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4649 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4650 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4651 return nullptr; 4652 RD = Base; 4653 } 4654 // Finally cast to the class containing the member. 4655 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4656 MemPtr.getContainingRecord())) 4657 return nullptr; 4658 } 4659 4660 // Add the member. Note that we cannot build bound member functions here. 4661 if (IncludeMember) { 4662 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4663 if (!HandleLValueMember(Info, RHS, LV, FD)) 4664 return nullptr; 4665 } else if (const IndirectFieldDecl *IFD = 4666 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4667 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4668 return nullptr; 4669 } else { 4670 llvm_unreachable("can't construct reference to bound member function"); 4671 } 4672 } 4673 4674 return MemPtr.getDecl(); 4675 } 4676 4677 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4678 const BinaryOperator *BO, 4679 LValue &LV, 4680 bool IncludeMember = true) { 4681 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4682 4683 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4684 if (Info.noteFailure()) { 4685 MemberPtr MemPtr; 4686 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4687 } 4688 return nullptr; 4689 } 4690 4691 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4692 BO->getRHS(), IncludeMember); 4693 } 4694 4695 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4696 /// the provided lvalue, which currently refers to the base object. 4697 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4698 LValue &Result) { 4699 SubobjectDesignator &D = Result.Designator; 4700 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4701 return false; 4702 4703 QualType TargetQT = E->getType(); 4704 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4705 TargetQT = PT->getPointeeType(); 4706 4707 // Check this cast lands within the final derived-to-base subobject path. 4708 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4709 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4710 << D.MostDerivedType << TargetQT; 4711 return false; 4712 } 4713 4714 // Check the type of the final cast. We don't need to check the path, 4715 // since a cast can only be formed if the path is unique. 4716 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4717 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4718 const CXXRecordDecl *FinalType; 4719 if (NewEntriesSize == D.MostDerivedPathLength) 4720 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4721 else 4722 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4723 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4724 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4725 << D.MostDerivedType << TargetQT; 4726 return false; 4727 } 4728 4729 // Truncate the lvalue to the appropriate derived class. 4730 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4731 } 4732 4733 /// Get the value to use for a default-initialized object of type T. 4734 /// Return false if it encounters something invalid. 4735 static bool getDefaultInitValue(QualType T, APValue &Result) { 4736 bool Success = true; 4737 if (auto *RD = T->getAsCXXRecordDecl()) { 4738 if (RD->isInvalidDecl()) { 4739 Result = APValue(); 4740 return false; 4741 } 4742 if (RD->isUnion()) { 4743 Result = APValue((const FieldDecl *)nullptr); 4744 return true; 4745 } 4746 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4747 std::distance(RD->field_begin(), RD->field_end())); 4748 4749 unsigned Index = 0; 4750 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4751 End = RD->bases_end(); 4752 I != End; ++I, ++Index) 4753 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4754 4755 for (const auto *I : RD->fields()) { 4756 if (I->isUnnamedBitfield()) 4757 continue; 4758 Success &= getDefaultInitValue(I->getType(), 4759 Result.getStructField(I->getFieldIndex())); 4760 } 4761 return Success; 4762 } 4763 4764 if (auto *AT = 4765 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4766 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4767 if (Result.hasArrayFiller()) 4768 Success &= 4769 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4770 4771 return Success; 4772 } 4773 4774 Result = APValue::IndeterminateValue(); 4775 return true; 4776 } 4777 4778 namespace { 4779 enum EvalStmtResult { 4780 /// Evaluation failed. 4781 ESR_Failed, 4782 /// Hit a 'return' statement. 4783 ESR_Returned, 4784 /// Evaluation succeeded. 4785 ESR_Succeeded, 4786 /// Hit a 'continue' statement. 4787 ESR_Continue, 4788 /// Hit a 'break' statement. 4789 ESR_Break, 4790 /// Still scanning for 'case' or 'default' statement. 4791 ESR_CaseNotFound 4792 }; 4793 } 4794 4795 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4796 // We don't need to evaluate the initializer for a static local. 4797 if (!VD->hasLocalStorage()) 4798 return true; 4799 4800 LValue Result; 4801 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4802 ScopeKind::Block, Result); 4803 4804 const Expr *InitE = VD->getInit(); 4805 if (!InitE) { 4806 if (VD->getType()->isDependentType()) 4807 return Info.noteSideEffect(); 4808 return getDefaultInitValue(VD->getType(), Val); 4809 } 4810 if (InitE->isValueDependent()) 4811 return false; 4812 4813 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4814 // Wipe out any partially-computed value, to allow tracking that this 4815 // evaluation failed. 4816 Val = APValue(); 4817 return false; 4818 } 4819 4820 return true; 4821 } 4822 4823 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4824 bool OK = true; 4825 4826 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4827 OK &= EvaluateVarDecl(Info, VD); 4828 4829 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4830 for (auto *BD : DD->bindings()) 4831 if (auto *VD = BD->getHoldingVar()) 4832 OK &= EvaluateDecl(Info, VD); 4833 4834 return OK; 4835 } 4836 4837 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4838 assert(E->isValueDependent()); 4839 if (Info.noteSideEffect()) 4840 return true; 4841 assert(E->containsErrors() && "valid value-dependent expression should never " 4842 "reach invalid code path."); 4843 return false; 4844 } 4845 4846 /// Evaluate a condition (either a variable declaration or an expression). 4847 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4848 const Expr *Cond, bool &Result) { 4849 if (Cond->isValueDependent()) 4850 return false; 4851 FullExpressionRAII Scope(Info); 4852 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4853 return false; 4854 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4855 return false; 4856 return Scope.destroy(); 4857 } 4858 4859 namespace { 4860 /// A location where the result (returned value) of evaluating a 4861 /// statement should be stored. 4862 struct StmtResult { 4863 /// The APValue that should be filled in with the returned value. 4864 APValue &Value; 4865 /// The location containing the result, if any (used to support RVO). 4866 const LValue *Slot; 4867 }; 4868 4869 struct TempVersionRAII { 4870 CallStackFrame &Frame; 4871 4872 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4873 Frame.pushTempVersion(); 4874 } 4875 4876 ~TempVersionRAII() { 4877 Frame.popTempVersion(); 4878 } 4879 }; 4880 4881 } 4882 4883 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4884 const Stmt *S, 4885 const SwitchCase *SC = nullptr); 4886 4887 /// Evaluate the body of a loop, and translate the result as appropriate. 4888 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4889 const Stmt *Body, 4890 const SwitchCase *Case = nullptr) { 4891 BlockScopeRAII Scope(Info); 4892 4893 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4894 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4895 ESR = ESR_Failed; 4896 4897 switch (ESR) { 4898 case ESR_Break: 4899 return ESR_Succeeded; 4900 case ESR_Succeeded: 4901 case ESR_Continue: 4902 return ESR_Continue; 4903 case ESR_Failed: 4904 case ESR_Returned: 4905 case ESR_CaseNotFound: 4906 return ESR; 4907 } 4908 llvm_unreachable("Invalid EvalStmtResult!"); 4909 } 4910 4911 /// Evaluate a switch statement. 4912 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4913 const SwitchStmt *SS) { 4914 BlockScopeRAII Scope(Info); 4915 4916 // Evaluate the switch condition. 4917 APSInt Value; 4918 { 4919 if (const Stmt *Init = SS->getInit()) { 4920 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4921 if (ESR != ESR_Succeeded) { 4922 if (ESR != ESR_Failed && !Scope.destroy()) 4923 ESR = ESR_Failed; 4924 return ESR; 4925 } 4926 } 4927 4928 FullExpressionRAII CondScope(Info); 4929 if (SS->getConditionVariable() && 4930 !EvaluateDecl(Info, SS->getConditionVariable())) 4931 return ESR_Failed; 4932 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4933 return ESR_Failed; 4934 if (!CondScope.destroy()) 4935 return ESR_Failed; 4936 } 4937 4938 // Find the switch case corresponding to the value of the condition. 4939 // FIXME: Cache this lookup. 4940 const SwitchCase *Found = nullptr; 4941 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4942 SC = SC->getNextSwitchCase()) { 4943 if (isa<DefaultStmt>(SC)) { 4944 Found = SC; 4945 continue; 4946 } 4947 4948 const CaseStmt *CS = cast<CaseStmt>(SC); 4949 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4950 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4951 : LHS; 4952 if (LHS <= Value && Value <= RHS) { 4953 Found = SC; 4954 break; 4955 } 4956 } 4957 4958 if (!Found) 4959 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4960 4961 // Search the switch body for the switch case and evaluate it from there. 4962 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4963 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4964 return ESR_Failed; 4965 4966 switch (ESR) { 4967 case ESR_Break: 4968 return ESR_Succeeded; 4969 case ESR_Succeeded: 4970 case ESR_Continue: 4971 case ESR_Failed: 4972 case ESR_Returned: 4973 return ESR; 4974 case ESR_CaseNotFound: 4975 // This can only happen if the switch case is nested within a statement 4976 // expression. We have no intention of supporting that. 4977 Info.FFDiag(Found->getBeginLoc(), 4978 diag::note_constexpr_stmt_expr_unsupported); 4979 return ESR_Failed; 4980 } 4981 llvm_unreachable("Invalid EvalStmtResult!"); 4982 } 4983 4984 // Evaluate a statement. 4985 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4986 const Stmt *S, const SwitchCase *Case) { 4987 if (!Info.nextStep(S)) 4988 return ESR_Failed; 4989 4990 // If we're hunting down a 'case' or 'default' label, recurse through 4991 // substatements until we hit the label. 4992 if (Case) { 4993 switch (S->getStmtClass()) { 4994 case Stmt::CompoundStmtClass: 4995 // FIXME: Precompute which substatement of a compound statement we 4996 // would jump to, and go straight there rather than performing a 4997 // linear scan each time. 4998 case Stmt::LabelStmtClass: 4999 case Stmt::AttributedStmtClass: 5000 case Stmt::DoStmtClass: 5001 break; 5002 5003 case Stmt::CaseStmtClass: 5004 case Stmt::DefaultStmtClass: 5005 if (Case == S) 5006 Case = nullptr; 5007 break; 5008 5009 case Stmt::IfStmtClass: { 5010 // FIXME: Precompute which side of an 'if' we would jump to, and go 5011 // straight there rather than scanning both sides. 5012 const IfStmt *IS = cast<IfStmt>(S); 5013 5014 // Wrap the evaluation in a block scope, in case it's a DeclStmt 5015 // preceded by our switch label. 5016 BlockScopeRAII Scope(Info); 5017 5018 // Step into the init statement in case it brings an (uninitialized) 5019 // variable into scope. 5020 if (const Stmt *Init = IS->getInit()) { 5021 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5022 if (ESR != ESR_CaseNotFound) { 5023 assert(ESR != ESR_Succeeded); 5024 return ESR; 5025 } 5026 } 5027 5028 // Condition variable must be initialized if it exists. 5029 // FIXME: We can skip evaluating the body if there's a condition 5030 // variable, as there can't be any case labels within it. 5031 // (The same is true for 'for' statements.) 5032 5033 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5034 if (ESR == ESR_Failed) 5035 return ESR; 5036 if (ESR != ESR_CaseNotFound) 5037 return Scope.destroy() ? ESR : ESR_Failed; 5038 if (!IS->getElse()) 5039 return ESR_CaseNotFound; 5040 5041 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5042 if (ESR == ESR_Failed) 5043 return ESR; 5044 if (ESR != ESR_CaseNotFound) 5045 return Scope.destroy() ? ESR : ESR_Failed; 5046 return ESR_CaseNotFound; 5047 } 5048 5049 case Stmt::WhileStmtClass: { 5050 EvalStmtResult ESR = 5051 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5052 if (ESR != ESR_Continue) 5053 return ESR; 5054 break; 5055 } 5056 5057 case Stmt::ForStmtClass: { 5058 const ForStmt *FS = cast<ForStmt>(S); 5059 BlockScopeRAII Scope(Info); 5060 5061 // Step into the init statement in case it brings an (uninitialized) 5062 // variable into scope. 5063 if (const Stmt *Init = FS->getInit()) { 5064 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5065 if (ESR != ESR_CaseNotFound) { 5066 assert(ESR != ESR_Succeeded); 5067 return ESR; 5068 } 5069 } 5070 5071 EvalStmtResult ESR = 5072 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5073 if (ESR != ESR_Continue) 5074 return ESR; 5075 if (const auto *Inc = FS->getInc()) { 5076 if (Inc->isValueDependent()) { 5077 if (!EvaluateDependentExpr(Inc, Info)) 5078 return ESR_Failed; 5079 } else { 5080 FullExpressionRAII IncScope(Info); 5081 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5082 return ESR_Failed; 5083 } 5084 } 5085 break; 5086 } 5087 5088 case Stmt::DeclStmtClass: { 5089 // Start the lifetime of any uninitialized variables we encounter. They 5090 // might be used by the selected branch of the switch. 5091 const DeclStmt *DS = cast<DeclStmt>(S); 5092 for (const auto *D : DS->decls()) { 5093 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5094 if (VD->hasLocalStorage() && !VD->getInit()) 5095 if (!EvaluateVarDecl(Info, VD)) 5096 return ESR_Failed; 5097 // FIXME: If the variable has initialization that can't be jumped 5098 // over, bail out of any immediately-surrounding compound-statement 5099 // too. There can't be any case labels here. 5100 } 5101 } 5102 return ESR_CaseNotFound; 5103 } 5104 5105 default: 5106 return ESR_CaseNotFound; 5107 } 5108 } 5109 5110 switch (S->getStmtClass()) { 5111 default: 5112 if (const Expr *E = dyn_cast<Expr>(S)) { 5113 if (E->isValueDependent()) { 5114 if (!EvaluateDependentExpr(E, Info)) 5115 return ESR_Failed; 5116 } else { 5117 // Don't bother evaluating beyond an expression-statement which couldn't 5118 // be evaluated. 5119 // FIXME: Do we need the FullExpressionRAII object here? 5120 // VisitExprWithCleanups should create one when necessary. 5121 FullExpressionRAII Scope(Info); 5122 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5123 return ESR_Failed; 5124 } 5125 return ESR_Succeeded; 5126 } 5127 5128 Info.FFDiag(S->getBeginLoc()); 5129 return ESR_Failed; 5130 5131 case Stmt::NullStmtClass: 5132 return ESR_Succeeded; 5133 5134 case Stmt::DeclStmtClass: { 5135 const DeclStmt *DS = cast<DeclStmt>(S); 5136 for (const auto *D : DS->decls()) { 5137 // Each declaration initialization is its own full-expression. 5138 FullExpressionRAII Scope(Info); 5139 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5140 return ESR_Failed; 5141 if (!Scope.destroy()) 5142 return ESR_Failed; 5143 } 5144 return ESR_Succeeded; 5145 } 5146 5147 case Stmt::ReturnStmtClass: { 5148 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5149 FullExpressionRAII Scope(Info); 5150 if (RetExpr && RetExpr->isValueDependent()) { 5151 EvaluateDependentExpr(RetExpr, Info); 5152 // We know we returned, but we don't know what the value is. 5153 return ESR_Failed; 5154 } 5155 if (RetExpr && 5156 !(Result.Slot 5157 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5158 : Evaluate(Result.Value, Info, RetExpr))) 5159 return ESR_Failed; 5160 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5161 } 5162 5163 case Stmt::CompoundStmtClass: { 5164 BlockScopeRAII Scope(Info); 5165 5166 const CompoundStmt *CS = cast<CompoundStmt>(S); 5167 for (const auto *BI : CS->body()) { 5168 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5169 if (ESR == ESR_Succeeded) 5170 Case = nullptr; 5171 else if (ESR != ESR_CaseNotFound) { 5172 if (ESR != ESR_Failed && !Scope.destroy()) 5173 return ESR_Failed; 5174 return ESR; 5175 } 5176 } 5177 if (Case) 5178 return ESR_CaseNotFound; 5179 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5180 } 5181 5182 case Stmt::IfStmtClass: { 5183 const IfStmt *IS = cast<IfStmt>(S); 5184 5185 // Evaluate the condition, as either a var decl or as an expression. 5186 BlockScopeRAII Scope(Info); 5187 if (const Stmt *Init = IS->getInit()) { 5188 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5189 if (ESR != ESR_Succeeded) { 5190 if (ESR != ESR_Failed && !Scope.destroy()) 5191 return ESR_Failed; 5192 return ESR; 5193 } 5194 } 5195 bool Cond; 5196 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5197 return ESR_Failed; 5198 5199 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5200 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5201 if (ESR != ESR_Succeeded) { 5202 if (ESR != ESR_Failed && !Scope.destroy()) 5203 return ESR_Failed; 5204 return ESR; 5205 } 5206 } 5207 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5208 } 5209 5210 case Stmt::WhileStmtClass: { 5211 const WhileStmt *WS = cast<WhileStmt>(S); 5212 while (true) { 5213 BlockScopeRAII Scope(Info); 5214 bool Continue; 5215 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5216 Continue)) 5217 return ESR_Failed; 5218 if (!Continue) 5219 break; 5220 5221 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5222 if (ESR != ESR_Continue) { 5223 if (ESR != ESR_Failed && !Scope.destroy()) 5224 return ESR_Failed; 5225 return ESR; 5226 } 5227 if (!Scope.destroy()) 5228 return ESR_Failed; 5229 } 5230 return ESR_Succeeded; 5231 } 5232 5233 case Stmt::DoStmtClass: { 5234 const DoStmt *DS = cast<DoStmt>(S); 5235 bool Continue; 5236 do { 5237 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5238 if (ESR != ESR_Continue) 5239 return ESR; 5240 Case = nullptr; 5241 5242 if (DS->getCond()->isValueDependent()) { 5243 EvaluateDependentExpr(DS->getCond(), Info); 5244 // Bailout as we don't know whether to keep going or terminate the loop. 5245 return ESR_Failed; 5246 } 5247 FullExpressionRAII CondScope(Info); 5248 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5249 !CondScope.destroy()) 5250 return ESR_Failed; 5251 } while (Continue); 5252 return ESR_Succeeded; 5253 } 5254 5255 case Stmt::ForStmtClass: { 5256 const ForStmt *FS = cast<ForStmt>(S); 5257 BlockScopeRAII ForScope(Info); 5258 if (FS->getInit()) { 5259 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5260 if (ESR != ESR_Succeeded) { 5261 if (ESR != ESR_Failed && !ForScope.destroy()) 5262 return ESR_Failed; 5263 return ESR; 5264 } 5265 } 5266 while (true) { 5267 BlockScopeRAII IterScope(Info); 5268 bool Continue = true; 5269 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5270 FS->getCond(), Continue)) 5271 return ESR_Failed; 5272 if (!Continue) 5273 break; 5274 5275 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5276 if (ESR != ESR_Continue) { 5277 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5278 return ESR_Failed; 5279 return ESR; 5280 } 5281 5282 if (const auto *Inc = FS->getInc()) { 5283 if (Inc->isValueDependent()) { 5284 if (!EvaluateDependentExpr(Inc, Info)) 5285 return ESR_Failed; 5286 } else { 5287 FullExpressionRAII IncScope(Info); 5288 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5289 return ESR_Failed; 5290 } 5291 } 5292 5293 if (!IterScope.destroy()) 5294 return ESR_Failed; 5295 } 5296 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5297 } 5298 5299 case Stmt::CXXForRangeStmtClass: { 5300 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5301 BlockScopeRAII Scope(Info); 5302 5303 // Evaluate the init-statement if present. 5304 if (FS->getInit()) { 5305 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5306 if (ESR != ESR_Succeeded) { 5307 if (ESR != ESR_Failed && !Scope.destroy()) 5308 return ESR_Failed; 5309 return ESR; 5310 } 5311 } 5312 5313 // Initialize the __range variable. 5314 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5315 if (ESR != ESR_Succeeded) { 5316 if (ESR != ESR_Failed && !Scope.destroy()) 5317 return ESR_Failed; 5318 return ESR; 5319 } 5320 5321 // Create the __begin and __end iterators. 5322 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5323 if (ESR != ESR_Succeeded) { 5324 if (ESR != ESR_Failed && !Scope.destroy()) 5325 return ESR_Failed; 5326 return ESR; 5327 } 5328 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5329 if (ESR != ESR_Succeeded) { 5330 if (ESR != ESR_Failed && !Scope.destroy()) 5331 return ESR_Failed; 5332 return ESR; 5333 } 5334 5335 while (true) { 5336 // Condition: __begin != __end. 5337 { 5338 if (FS->getCond()->isValueDependent()) { 5339 EvaluateDependentExpr(FS->getCond(), Info); 5340 // We don't know whether to keep going or terminate the loop. 5341 return ESR_Failed; 5342 } 5343 bool Continue = true; 5344 FullExpressionRAII CondExpr(Info); 5345 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5346 return ESR_Failed; 5347 if (!Continue) 5348 break; 5349 } 5350 5351 // User's variable declaration, initialized by *__begin. 5352 BlockScopeRAII InnerScope(Info); 5353 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5354 if (ESR != ESR_Succeeded) { 5355 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5356 return ESR_Failed; 5357 return ESR; 5358 } 5359 5360 // Loop body. 5361 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5362 if (ESR != ESR_Continue) { 5363 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5364 return ESR_Failed; 5365 return ESR; 5366 } 5367 if (FS->getInc()->isValueDependent()) { 5368 if (!EvaluateDependentExpr(FS->getInc(), Info)) 5369 return ESR_Failed; 5370 } else { 5371 // Increment: ++__begin 5372 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5373 return ESR_Failed; 5374 } 5375 5376 if (!InnerScope.destroy()) 5377 return ESR_Failed; 5378 } 5379 5380 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5381 } 5382 5383 case Stmt::SwitchStmtClass: 5384 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5385 5386 case Stmt::ContinueStmtClass: 5387 return ESR_Continue; 5388 5389 case Stmt::BreakStmtClass: 5390 return ESR_Break; 5391 5392 case Stmt::LabelStmtClass: 5393 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5394 5395 case Stmt::AttributedStmtClass: 5396 // As a general principle, C++11 attributes can be ignored without 5397 // any semantic impact. 5398 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5399 Case); 5400 5401 case Stmt::CaseStmtClass: 5402 case Stmt::DefaultStmtClass: 5403 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5404 case Stmt::CXXTryStmtClass: 5405 // Evaluate try blocks by evaluating all sub statements. 5406 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5407 } 5408 } 5409 5410 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5411 /// default constructor. If so, we'll fold it whether or not it's marked as 5412 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5413 /// so we need special handling. 5414 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5415 const CXXConstructorDecl *CD, 5416 bool IsValueInitialization) { 5417 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5418 return false; 5419 5420 // Value-initialization does not call a trivial default constructor, so such a 5421 // call is a core constant expression whether or not the constructor is 5422 // constexpr. 5423 if (!CD->isConstexpr() && !IsValueInitialization) { 5424 if (Info.getLangOpts().CPlusPlus11) { 5425 // FIXME: If DiagDecl is an implicitly-declared special member function, 5426 // we should be much more explicit about why it's not constexpr. 5427 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5428 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5429 Info.Note(CD->getLocation(), diag::note_declared_at); 5430 } else { 5431 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5432 } 5433 } 5434 return true; 5435 } 5436 5437 /// CheckConstexprFunction - Check that a function can be called in a constant 5438 /// expression. 5439 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5440 const FunctionDecl *Declaration, 5441 const FunctionDecl *Definition, 5442 const Stmt *Body) { 5443 // Potential constant expressions can contain calls to declared, but not yet 5444 // defined, constexpr functions. 5445 if (Info.checkingPotentialConstantExpression() && !Definition && 5446 Declaration->isConstexpr()) 5447 return false; 5448 5449 // Bail out if the function declaration itself is invalid. We will 5450 // have produced a relevant diagnostic while parsing it, so just 5451 // note the problematic sub-expression. 5452 if (Declaration->isInvalidDecl()) { 5453 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5454 return false; 5455 } 5456 5457 // DR1872: An instantiated virtual constexpr function can't be called in a 5458 // constant expression (prior to C++20). We can still constant-fold such a 5459 // call. 5460 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5461 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5462 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5463 5464 if (Definition && Definition->isInvalidDecl()) { 5465 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5466 return false; 5467 } 5468 5469 // Can we evaluate this function call? 5470 if (Definition && Definition->isConstexpr() && Body) 5471 return true; 5472 5473 if (Info.getLangOpts().CPlusPlus11) { 5474 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5475 5476 // If this function is not constexpr because it is an inherited 5477 // non-constexpr constructor, diagnose that directly. 5478 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5479 if (CD && CD->isInheritingConstructor()) { 5480 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5481 if (!Inherited->isConstexpr()) 5482 DiagDecl = CD = Inherited; 5483 } 5484 5485 // FIXME: If DiagDecl is an implicitly-declared special member function 5486 // or an inheriting constructor, we should be much more explicit about why 5487 // it's not constexpr. 5488 if (CD && CD->isInheritingConstructor()) 5489 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5490 << CD->getInheritedConstructor().getConstructor()->getParent(); 5491 else 5492 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5493 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5494 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5495 } else { 5496 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5497 } 5498 return false; 5499 } 5500 5501 namespace { 5502 struct CheckDynamicTypeHandler { 5503 AccessKinds AccessKind; 5504 typedef bool result_type; 5505 bool failed() { return false; } 5506 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5507 bool found(APSInt &Value, QualType SubobjType) { return true; } 5508 bool found(APFloat &Value, QualType SubobjType) { return true; } 5509 }; 5510 } // end anonymous namespace 5511 5512 /// Check that we can access the notional vptr of an object / determine its 5513 /// dynamic type. 5514 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5515 AccessKinds AK, bool Polymorphic) { 5516 if (This.Designator.Invalid) 5517 return false; 5518 5519 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5520 5521 if (!Obj) 5522 return false; 5523 5524 if (!Obj.Value) { 5525 // The object is not usable in constant expressions, so we can't inspect 5526 // its value to see if it's in-lifetime or what the active union members 5527 // are. We can still check for a one-past-the-end lvalue. 5528 if (This.Designator.isOnePastTheEnd() || 5529 This.Designator.isMostDerivedAnUnsizedArray()) { 5530 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5531 ? diag::note_constexpr_access_past_end 5532 : diag::note_constexpr_access_unsized_array) 5533 << AK; 5534 return false; 5535 } else if (Polymorphic) { 5536 // Conservatively refuse to perform a polymorphic operation if we would 5537 // not be able to read a notional 'vptr' value. 5538 APValue Val; 5539 This.moveInto(Val); 5540 QualType StarThisType = 5541 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5542 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5543 << AK << Val.getAsString(Info.Ctx, StarThisType); 5544 return false; 5545 } 5546 return true; 5547 } 5548 5549 CheckDynamicTypeHandler Handler{AK}; 5550 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5551 } 5552 5553 /// Check that the pointee of the 'this' pointer in a member function call is 5554 /// either within its lifetime or in its period of construction or destruction. 5555 static bool 5556 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5557 const LValue &This, 5558 const CXXMethodDecl *NamedMember) { 5559 return checkDynamicType( 5560 Info, E, This, 5561 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5562 } 5563 5564 struct DynamicType { 5565 /// The dynamic class type of the object. 5566 const CXXRecordDecl *Type; 5567 /// The corresponding path length in the lvalue. 5568 unsigned PathLength; 5569 }; 5570 5571 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5572 unsigned PathLength) { 5573 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5574 Designator.Entries.size() && "invalid path length"); 5575 return (PathLength == Designator.MostDerivedPathLength) 5576 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5577 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5578 } 5579 5580 /// Determine the dynamic type of an object. 5581 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5582 LValue &This, AccessKinds AK) { 5583 // If we don't have an lvalue denoting an object of class type, there is no 5584 // meaningful dynamic type. (We consider objects of non-class type to have no 5585 // dynamic type.) 5586 if (!checkDynamicType(Info, E, This, AK, true)) 5587 return None; 5588 5589 // Refuse to compute a dynamic type in the presence of virtual bases. This 5590 // shouldn't happen other than in constant-folding situations, since literal 5591 // types can't have virtual bases. 5592 // 5593 // Note that consumers of DynamicType assume that the type has no virtual 5594 // bases, and will need modifications if this restriction is relaxed. 5595 const CXXRecordDecl *Class = 5596 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5597 if (!Class || Class->getNumVBases()) { 5598 Info.FFDiag(E); 5599 return None; 5600 } 5601 5602 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5603 // binary search here instead. But the overwhelmingly common case is that 5604 // we're not in the middle of a constructor, so it probably doesn't matter 5605 // in practice. 5606 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5607 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5608 PathLength <= Path.size(); ++PathLength) { 5609 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5610 Path.slice(0, PathLength))) { 5611 case ConstructionPhase::Bases: 5612 case ConstructionPhase::DestroyingBases: 5613 // We're constructing or destroying a base class. This is not the dynamic 5614 // type. 5615 break; 5616 5617 case ConstructionPhase::None: 5618 case ConstructionPhase::AfterBases: 5619 case ConstructionPhase::AfterFields: 5620 case ConstructionPhase::Destroying: 5621 // We've finished constructing the base classes and not yet started 5622 // destroying them again, so this is the dynamic type. 5623 return DynamicType{getBaseClassType(This.Designator, PathLength), 5624 PathLength}; 5625 } 5626 } 5627 5628 // CWG issue 1517: we're constructing a base class of the object described by 5629 // 'This', so that object has not yet begun its period of construction and 5630 // any polymorphic operation on it results in undefined behavior. 5631 Info.FFDiag(E); 5632 return None; 5633 } 5634 5635 /// Perform virtual dispatch. 5636 static const CXXMethodDecl *HandleVirtualDispatch( 5637 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5638 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5639 Optional<DynamicType> DynType = ComputeDynamicType( 5640 Info, E, This, 5641 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5642 if (!DynType) 5643 return nullptr; 5644 5645 // Find the final overrider. It must be declared in one of the classes on the 5646 // path from the dynamic type to the static type. 5647 // FIXME: If we ever allow literal types to have virtual base classes, that 5648 // won't be true. 5649 const CXXMethodDecl *Callee = Found; 5650 unsigned PathLength = DynType->PathLength; 5651 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5652 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5653 const CXXMethodDecl *Overrider = 5654 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5655 if (Overrider) { 5656 Callee = Overrider; 5657 break; 5658 } 5659 } 5660 5661 // C++2a [class.abstract]p6: 5662 // the effect of making a virtual call to a pure virtual function [...] is 5663 // undefined 5664 if (Callee->isPure()) { 5665 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5666 Info.Note(Callee->getLocation(), diag::note_declared_at); 5667 return nullptr; 5668 } 5669 5670 // If necessary, walk the rest of the path to determine the sequence of 5671 // covariant adjustment steps to apply. 5672 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5673 Found->getReturnType())) { 5674 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5675 for (unsigned CovariantPathLength = PathLength + 1; 5676 CovariantPathLength != This.Designator.Entries.size(); 5677 ++CovariantPathLength) { 5678 const CXXRecordDecl *NextClass = 5679 getBaseClassType(This.Designator, CovariantPathLength); 5680 const CXXMethodDecl *Next = 5681 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5682 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5683 Next->getReturnType(), CovariantAdjustmentPath.back())) 5684 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5685 } 5686 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5687 CovariantAdjustmentPath.back())) 5688 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5689 } 5690 5691 // Perform 'this' adjustment. 5692 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5693 return nullptr; 5694 5695 return Callee; 5696 } 5697 5698 /// Perform the adjustment from a value returned by a virtual function to 5699 /// a value of the statically expected type, which may be a pointer or 5700 /// reference to a base class of the returned type. 5701 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5702 APValue &Result, 5703 ArrayRef<QualType> Path) { 5704 assert(Result.isLValue() && 5705 "unexpected kind of APValue for covariant return"); 5706 if (Result.isNullPointer()) 5707 return true; 5708 5709 LValue LVal; 5710 LVal.setFrom(Info.Ctx, Result); 5711 5712 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5713 for (unsigned I = 1; I != Path.size(); ++I) { 5714 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5715 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5716 if (OldClass != NewClass && 5717 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5718 return false; 5719 OldClass = NewClass; 5720 } 5721 5722 LVal.moveInto(Result); 5723 return true; 5724 } 5725 5726 /// Determine whether \p Base, which is known to be a direct base class of 5727 /// \p Derived, is a public base class. 5728 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5729 const CXXRecordDecl *Base) { 5730 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5731 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5732 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5733 return BaseSpec.getAccessSpecifier() == AS_public; 5734 } 5735 llvm_unreachable("Base is not a direct base of Derived"); 5736 } 5737 5738 /// Apply the given dynamic cast operation on the provided lvalue. 5739 /// 5740 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5741 /// to find a suitable target subobject. 5742 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5743 LValue &Ptr) { 5744 // We can't do anything with a non-symbolic pointer value. 5745 SubobjectDesignator &D = Ptr.Designator; 5746 if (D.Invalid) 5747 return false; 5748 5749 // C++ [expr.dynamic.cast]p6: 5750 // If v is a null pointer value, the result is a null pointer value. 5751 if (Ptr.isNullPointer() && !E->isGLValue()) 5752 return true; 5753 5754 // For all the other cases, we need the pointer to point to an object within 5755 // its lifetime / period of construction / destruction, and we need to know 5756 // its dynamic type. 5757 Optional<DynamicType> DynType = 5758 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5759 if (!DynType) 5760 return false; 5761 5762 // C++ [expr.dynamic.cast]p7: 5763 // If T is "pointer to cv void", then the result is a pointer to the most 5764 // derived object 5765 if (E->getType()->isVoidPointerType()) 5766 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5767 5768 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5769 assert(C && "dynamic_cast target is not void pointer nor class"); 5770 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5771 5772 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5773 // C++ [expr.dynamic.cast]p9: 5774 if (!E->isGLValue()) { 5775 // The value of a failed cast to pointer type is the null pointer value 5776 // of the required result type. 5777 Ptr.setNull(Info.Ctx, E->getType()); 5778 return true; 5779 } 5780 5781 // A failed cast to reference type throws [...] std::bad_cast. 5782 unsigned DiagKind; 5783 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5784 DynType->Type->isDerivedFrom(C))) 5785 DiagKind = 0; 5786 else if (!Paths || Paths->begin() == Paths->end()) 5787 DiagKind = 1; 5788 else if (Paths->isAmbiguous(CQT)) 5789 DiagKind = 2; 5790 else { 5791 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5792 DiagKind = 3; 5793 } 5794 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5795 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5796 << Info.Ctx.getRecordType(DynType->Type) 5797 << E->getType().getUnqualifiedType(); 5798 return false; 5799 }; 5800 5801 // Runtime check, phase 1: 5802 // Walk from the base subobject towards the derived object looking for the 5803 // target type. 5804 for (int PathLength = Ptr.Designator.Entries.size(); 5805 PathLength >= (int)DynType->PathLength; --PathLength) { 5806 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5807 if (declaresSameEntity(Class, C)) 5808 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5809 // We can only walk across public inheritance edges. 5810 if (PathLength > (int)DynType->PathLength && 5811 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5812 Class)) 5813 return RuntimeCheckFailed(nullptr); 5814 } 5815 5816 // Runtime check, phase 2: 5817 // Search the dynamic type for an unambiguous public base of type C. 5818 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5819 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5820 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5821 Paths.front().Access == AS_public) { 5822 // Downcast to the dynamic type... 5823 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5824 return false; 5825 // ... then upcast to the chosen base class subobject. 5826 for (CXXBasePathElement &Elem : Paths.front()) 5827 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5828 return false; 5829 return true; 5830 } 5831 5832 // Otherwise, the runtime check fails. 5833 return RuntimeCheckFailed(&Paths); 5834 } 5835 5836 namespace { 5837 struct StartLifetimeOfUnionMemberHandler { 5838 EvalInfo &Info; 5839 const Expr *LHSExpr; 5840 const FieldDecl *Field; 5841 bool DuringInit; 5842 bool Failed = false; 5843 static const AccessKinds AccessKind = AK_Assign; 5844 5845 typedef bool result_type; 5846 bool failed() { return Failed; } 5847 bool found(APValue &Subobj, QualType SubobjType) { 5848 // We are supposed to perform no initialization but begin the lifetime of 5849 // the object. We interpret that as meaning to do what default 5850 // initialization of the object would do if all constructors involved were 5851 // trivial: 5852 // * All base, non-variant member, and array element subobjects' lifetimes 5853 // begin 5854 // * No variant members' lifetimes begin 5855 // * All scalar subobjects whose lifetimes begin have indeterminate values 5856 assert(SubobjType->isUnionType()); 5857 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5858 // This union member is already active. If it's also in-lifetime, there's 5859 // nothing to do. 5860 if (Subobj.getUnionValue().hasValue()) 5861 return true; 5862 } else if (DuringInit) { 5863 // We're currently in the process of initializing a different union 5864 // member. If we carried on, that initialization would attempt to 5865 // store to an inactive union member, resulting in undefined behavior. 5866 Info.FFDiag(LHSExpr, 5867 diag::note_constexpr_union_member_change_during_init); 5868 return false; 5869 } 5870 APValue Result; 5871 Failed = !getDefaultInitValue(Field->getType(), Result); 5872 Subobj.setUnion(Field, Result); 5873 return true; 5874 } 5875 bool found(APSInt &Value, QualType SubobjType) { 5876 llvm_unreachable("wrong value kind for union object"); 5877 } 5878 bool found(APFloat &Value, QualType SubobjType) { 5879 llvm_unreachable("wrong value kind for union object"); 5880 } 5881 }; 5882 } // end anonymous namespace 5883 5884 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5885 5886 /// Handle a builtin simple-assignment or a call to a trivial assignment 5887 /// operator whose left-hand side might involve a union member access. If it 5888 /// does, implicitly start the lifetime of any accessed union elements per 5889 /// C++20 [class.union]5. 5890 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5891 const LValue &LHS) { 5892 if (LHS.InvalidBase || LHS.Designator.Invalid) 5893 return false; 5894 5895 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5896 // C++ [class.union]p5: 5897 // define the set S(E) of subexpressions of E as follows: 5898 unsigned PathLength = LHS.Designator.Entries.size(); 5899 for (const Expr *E = LHSExpr; E != nullptr;) { 5900 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5901 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5902 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5903 // Note that we can't implicitly start the lifetime of a reference, 5904 // so we don't need to proceed any further if we reach one. 5905 if (!FD || FD->getType()->isReferenceType()) 5906 break; 5907 5908 // ... and also contains A.B if B names a union member ... 5909 if (FD->getParent()->isUnion()) { 5910 // ... of a non-class, non-array type, or of a class type with a 5911 // trivial default constructor that is not deleted, or an array of 5912 // such types. 5913 auto *RD = 5914 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5915 if (!RD || RD->hasTrivialDefaultConstructor()) 5916 UnionPathLengths.push_back({PathLength - 1, FD}); 5917 } 5918 5919 E = ME->getBase(); 5920 --PathLength; 5921 assert(declaresSameEntity(FD, 5922 LHS.Designator.Entries[PathLength] 5923 .getAsBaseOrMember().getPointer())); 5924 5925 // -- If E is of the form A[B] and is interpreted as a built-in array 5926 // subscripting operator, S(E) is [S(the array operand, if any)]. 5927 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5928 // Step over an ArrayToPointerDecay implicit cast. 5929 auto *Base = ASE->getBase()->IgnoreImplicit(); 5930 if (!Base->getType()->isArrayType()) 5931 break; 5932 5933 E = Base; 5934 --PathLength; 5935 5936 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5937 // Step over a derived-to-base conversion. 5938 E = ICE->getSubExpr(); 5939 if (ICE->getCastKind() == CK_NoOp) 5940 continue; 5941 if (ICE->getCastKind() != CK_DerivedToBase && 5942 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5943 break; 5944 // Walk path backwards as we walk up from the base to the derived class. 5945 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5946 --PathLength; 5947 (void)Elt; 5948 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5949 LHS.Designator.Entries[PathLength] 5950 .getAsBaseOrMember().getPointer())); 5951 } 5952 5953 // -- Otherwise, S(E) is empty. 5954 } else { 5955 break; 5956 } 5957 } 5958 5959 // Common case: no unions' lifetimes are started. 5960 if (UnionPathLengths.empty()) 5961 return true; 5962 5963 // if modification of X [would access an inactive union member], an object 5964 // of the type of X is implicitly created 5965 CompleteObject Obj = 5966 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5967 if (!Obj) 5968 return false; 5969 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5970 llvm::reverse(UnionPathLengths)) { 5971 // Form a designator for the union object. 5972 SubobjectDesignator D = LHS.Designator; 5973 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5974 5975 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5976 ConstructionPhase::AfterBases; 5977 StartLifetimeOfUnionMemberHandler StartLifetime{ 5978 Info, LHSExpr, LengthAndField.second, DuringInit}; 5979 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5980 return false; 5981 } 5982 5983 return true; 5984 } 5985 5986 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5987 CallRef Call, EvalInfo &Info, 5988 bool NonNull = false) { 5989 LValue LV; 5990 // Create the parameter slot and register its destruction. For a vararg 5991 // argument, create a temporary. 5992 // FIXME: For calling conventions that destroy parameters in the callee, 5993 // should we consider performing destruction when the function returns 5994 // instead? 5995 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5996 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5997 ScopeKind::Call, LV); 5998 if (!EvaluateInPlace(V, Info, LV, Arg)) 5999 return false; 6000 6001 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6002 // undefined behavior, so is non-constant. 6003 if (NonNull && V.isLValue() && V.isNullPointer()) { 6004 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6005 return false; 6006 } 6007 6008 return true; 6009 } 6010 6011 /// Evaluate the arguments to a function call. 6012 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6013 EvalInfo &Info, const FunctionDecl *Callee, 6014 bool RightToLeft = false) { 6015 bool Success = true; 6016 llvm::SmallBitVector ForbiddenNullArgs; 6017 if (Callee->hasAttr<NonNullAttr>()) { 6018 ForbiddenNullArgs.resize(Args.size()); 6019 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6020 if (!Attr->args_size()) { 6021 ForbiddenNullArgs.set(); 6022 break; 6023 } else 6024 for (auto Idx : Attr->args()) { 6025 unsigned ASTIdx = Idx.getASTIndex(); 6026 if (ASTIdx >= Args.size()) 6027 continue; 6028 ForbiddenNullArgs[ASTIdx] = 1; 6029 } 6030 } 6031 } 6032 for (unsigned I = 0; I < Args.size(); I++) { 6033 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6034 const ParmVarDecl *PVD = 6035 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6036 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6037 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6038 // If we're checking for a potential constant expression, evaluate all 6039 // initializers even if some of them fail. 6040 if (!Info.noteFailure()) 6041 return false; 6042 Success = false; 6043 } 6044 } 6045 return Success; 6046 } 6047 6048 /// Perform a trivial copy from Param, which is the parameter of a copy or move 6049 /// constructor or assignment operator. 6050 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6051 const Expr *E, APValue &Result, 6052 bool CopyObjectRepresentation) { 6053 // Find the reference argument. 6054 CallStackFrame *Frame = Info.CurrentCall; 6055 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6056 if (!RefValue) { 6057 Info.FFDiag(E); 6058 return false; 6059 } 6060 6061 // Copy out the contents of the RHS object. 6062 LValue RefLValue; 6063 RefLValue.setFrom(Info.Ctx, *RefValue); 6064 return handleLValueToRValueConversion( 6065 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6066 CopyObjectRepresentation); 6067 } 6068 6069 /// Evaluate a function call. 6070 static bool HandleFunctionCall(SourceLocation CallLoc, 6071 const FunctionDecl *Callee, const LValue *This, 6072 ArrayRef<const Expr *> Args, CallRef Call, 6073 const Stmt *Body, EvalInfo &Info, 6074 APValue &Result, const LValue *ResultSlot) { 6075 if (!Info.CheckCallLimit(CallLoc)) 6076 return false; 6077 6078 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6079 6080 // For a trivial copy or move assignment, perform an APValue copy. This is 6081 // essential for unions, where the operations performed by the assignment 6082 // operator cannot be represented as statements. 6083 // 6084 // Skip this for non-union classes with no fields; in that case, the defaulted 6085 // copy/move does not actually read the object. 6086 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6087 if (MD && MD->isDefaulted() && 6088 (MD->getParent()->isUnion() || 6089 (MD->isTrivial() && 6090 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6091 assert(This && 6092 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6093 APValue RHSValue; 6094 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6095 MD->getParent()->isUnion())) 6096 return false; 6097 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6098 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6099 return false; 6100 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6101 RHSValue)) 6102 return false; 6103 This->moveInto(Result); 6104 return true; 6105 } else if (MD && isLambdaCallOperator(MD)) { 6106 // We're in a lambda; determine the lambda capture field maps unless we're 6107 // just constexpr checking a lambda's call operator. constexpr checking is 6108 // done before the captures have been added to the closure object (unless 6109 // we're inferring constexpr-ness), so we don't have access to them in this 6110 // case. But since we don't need the captures to constexpr check, we can 6111 // just ignore them. 6112 if (!Info.checkingPotentialConstantExpression()) 6113 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6114 Frame.LambdaThisCaptureField); 6115 } 6116 6117 StmtResult Ret = {Result, ResultSlot}; 6118 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6119 if (ESR == ESR_Succeeded) { 6120 if (Callee->getReturnType()->isVoidType()) 6121 return true; 6122 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6123 } 6124 return ESR == ESR_Returned; 6125 } 6126 6127 /// Evaluate a constructor call. 6128 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6129 CallRef Call, 6130 const CXXConstructorDecl *Definition, 6131 EvalInfo &Info, APValue &Result) { 6132 SourceLocation CallLoc = E->getExprLoc(); 6133 if (!Info.CheckCallLimit(CallLoc)) 6134 return false; 6135 6136 const CXXRecordDecl *RD = Definition->getParent(); 6137 if (RD->getNumVBases()) { 6138 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6139 return false; 6140 } 6141 6142 EvalInfo::EvaluatingConstructorRAII EvalObj( 6143 Info, 6144 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6145 RD->getNumBases()); 6146 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6147 6148 // FIXME: Creating an APValue just to hold a nonexistent return value is 6149 // wasteful. 6150 APValue RetVal; 6151 StmtResult Ret = {RetVal, nullptr}; 6152 6153 // If it's a delegating constructor, delegate. 6154 if (Definition->isDelegatingConstructor()) { 6155 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6156 if ((*I)->getInit()->isValueDependent()) { 6157 if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6158 return false; 6159 } else { 6160 FullExpressionRAII InitScope(Info); 6161 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6162 !InitScope.destroy()) 6163 return false; 6164 } 6165 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6166 } 6167 6168 // For a trivial copy or move constructor, perform an APValue copy. This is 6169 // essential for unions (or classes with anonymous union members), where the 6170 // operations performed by the constructor cannot be represented by 6171 // ctor-initializers. 6172 // 6173 // Skip this for empty non-union classes; we should not perform an 6174 // lvalue-to-rvalue conversion on them because their copy constructor does not 6175 // actually read them. 6176 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6177 (Definition->getParent()->isUnion() || 6178 (Definition->isTrivial() && 6179 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6180 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6181 Definition->getParent()->isUnion()); 6182 } 6183 6184 // Reserve space for the struct members. 6185 if (!Result.hasValue()) { 6186 if (!RD->isUnion()) 6187 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6188 std::distance(RD->field_begin(), RD->field_end())); 6189 else 6190 // A union starts with no active member. 6191 Result = APValue((const FieldDecl*)nullptr); 6192 } 6193 6194 if (RD->isInvalidDecl()) return false; 6195 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6196 6197 // A scope for temporaries lifetime-extended by reference members. 6198 BlockScopeRAII LifetimeExtendedScope(Info); 6199 6200 bool Success = true; 6201 unsigned BasesSeen = 0; 6202 #ifndef NDEBUG 6203 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6204 #endif 6205 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6206 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6207 // We might be initializing the same field again if this is an indirect 6208 // field initialization. 6209 if (FieldIt == RD->field_end() || 6210 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6211 assert(Indirect && "fields out of order?"); 6212 return; 6213 } 6214 6215 // Default-initialize any fields with no explicit initializer. 6216 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6217 assert(FieldIt != RD->field_end() && "missing field?"); 6218 if (!FieldIt->isUnnamedBitfield()) 6219 Success &= getDefaultInitValue( 6220 FieldIt->getType(), 6221 Result.getStructField(FieldIt->getFieldIndex())); 6222 } 6223 ++FieldIt; 6224 }; 6225 for (const auto *I : Definition->inits()) { 6226 LValue Subobject = This; 6227 LValue SubobjectParent = This; 6228 APValue *Value = &Result; 6229 6230 // Determine the subobject to initialize. 6231 FieldDecl *FD = nullptr; 6232 if (I->isBaseInitializer()) { 6233 QualType BaseType(I->getBaseClass(), 0); 6234 #ifndef NDEBUG 6235 // Non-virtual base classes are initialized in the order in the class 6236 // definition. We have already checked for virtual base classes. 6237 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6238 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6239 "base class initializers not in expected order"); 6240 ++BaseIt; 6241 #endif 6242 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6243 BaseType->getAsCXXRecordDecl(), &Layout)) 6244 return false; 6245 Value = &Result.getStructBase(BasesSeen++); 6246 } else if ((FD = I->getMember())) { 6247 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6248 return false; 6249 if (RD->isUnion()) { 6250 Result = APValue(FD); 6251 Value = &Result.getUnionValue(); 6252 } else { 6253 SkipToField(FD, false); 6254 Value = &Result.getStructField(FD->getFieldIndex()); 6255 } 6256 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6257 // Walk the indirect field decl's chain to find the object to initialize, 6258 // and make sure we've initialized every step along it. 6259 auto IndirectFieldChain = IFD->chain(); 6260 for (auto *C : IndirectFieldChain) { 6261 FD = cast<FieldDecl>(C); 6262 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6263 // Switch the union field if it differs. This happens if we had 6264 // preceding zero-initialization, and we're now initializing a union 6265 // subobject other than the first. 6266 // FIXME: In this case, the values of the other subobjects are 6267 // specified, since zero-initialization sets all padding bits to zero. 6268 if (!Value->hasValue() || 6269 (Value->isUnion() && Value->getUnionField() != FD)) { 6270 if (CD->isUnion()) 6271 *Value = APValue(FD); 6272 else 6273 // FIXME: This immediately starts the lifetime of all members of 6274 // an anonymous struct. It would be preferable to strictly start 6275 // member lifetime in initialization order. 6276 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6277 } 6278 // Store Subobject as its parent before updating it for the last element 6279 // in the chain. 6280 if (C == IndirectFieldChain.back()) 6281 SubobjectParent = Subobject; 6282 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6283 return false; 6284 if (CD->isUnion()) 6285 Value = &Value->getUnionValue(); 6286 else { 6287 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6288 SkipToField(FD, true); 6289 Value = &Value->getStructField(FD->getFieldIndex()); 6290 } 6291 } 6292 } else { 6293 llvm_unreachable("unknown base initializer kind"); 6294 } 6295 6296 // Need to override This for implicit field initializers as in this case 6297 // This refers to innermost anonymous struct/union containing initializer, 6298 // not to currently constructed class. 6299 const Expr *Init = I->getInit(); 6300 if (Init->isValueDependent()) { 6301 if (!EvaluateDependentExpr(Init, Info)) 6302 return false; 6303 } else { 6304 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6305 isa<CXXDefaultInitExpr>(Init)); 6306 FullExpressionRAII InitScope(Info); 6307 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6308 (FD && FD->isBitField() && 6309 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6310 // If we're checking for a potential constant expression, evaluate all 6311 // initializers even if some of them fail. 6312 if (!Info.noteFailure()) 6313 return false; 6314 Success = false; 6315 } 6316 } 6317 6318 // This is the point at which the dynamic type of the object becomes this 6319 // class type. 6320 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6321 EvalObj.finishedConstructingBases(); 6322 } 6323 6324 // Default-initialize any remaining fields. 6325 if (!RD->isUnion()) { 6326 for (; FieldIt != RD->field_end(); ++FieldIt) { 6327 if (!FieldIt->isUnnamedBitfield()) 6328 Success &= getDefaultInitValue( 6329 FieldIt->getType(), 6330 Result.getStructField(FieldIt->getFieldIndex())); 6331 } 6332 } 6333 6334 EvalObj.finishedConstructingFields(); 6335 6336 return Success && 6337 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6338 LifetimeExtendedScope.destroy(); 6339 } 6340 6341 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6342 ArrayRef<const Expr*> Args, 6343 const CXXConstructorDecl *Definition, 6344 EvalInfo &Info, APValue &Result) { 6345 CallScopeRAII CallScope(Info); 6346 CallRef Call = Info.CurrentCall->createCall(Definition); 6347 if (!EvaluateArgs(Args, Call, Info, Definition)) 6348 return false; 6349 6350 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6351 CallScope.destroy(); 6352 } 6353 6354 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6355 const LValue &This, APValue &Value, 6356 QualType T) { 6357 // Objects can only be destroyed while they're within their lifetimes. 6358 // FIXME: We have no representation for whether an object of type nullptr_t 6359 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6360 // as indeterminate instead? 6361 if (Value.isAbsent() && !T->isNullPtrType()) { 6362 APValue Printable; 6363 This.moveInto(Printable); 6364 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6365 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6366 return false; 6367 } 6368 6369 // Invent an expression for location purposes. 6370 // FIXME: We shouldn't need to do this. 6371 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6372 6373 // For arrays, destroy elements right-to-left. 6374 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6375 uint64_t Size = CAT->getSize().getZExtValue(); 6376 QualType ElemT = CAT->getElementType(); 6377 6378 LValue ElemLV = This; 6379 ElemLV.addArray(Info, &LocE, CAT); 6380 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6381 return false; 6382 6383 // Ensure that we have actual array elements available to destroy; the 6384 // destructors might mutate the value, so we can't run them on the array 6385 // filler. 6386 if (Size && Size > Value.getArrayInitializedElts()) 6387 expandArray(Value, Value.getArraySize() - 1); 6388 6389 for (; Size != 0; --Size) { 6390 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6391 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6392 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6393 return false; 6394 } 6395 6396 // End the lifetime of this array now. 6397 Value = APValue(); 6398 return true; 6399 } 6400 6401 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6402 if (!RD) { 6403 if (T.isDestructedType()) { 6404 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6405 return false; 6406 } 6407 6408 Value = APValue(); 6409 return true; 6410 } 6411 6412 if (RD->getNumVBases()) { 6413 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6414 return false; 6415 } 6416 6417 const CXXDestructorDecl *DD = RD->getDestructor(); 6418 if (!DD && !RD->hasTrivialDestructor()) { 6419 Info.FFDiag(CallLoc); 6420 return false; 6421 } 6422 6423 if (!DD || DD->isTrivial() || 6424 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6425 // A trivial destructor just ends the lifetime of the object. Check for 6426 // this case before checking for a body, because we might not bother 6427 // building a body for a trivial destructor. Note that it doesn't matter 6428 // whether the destructor is constexpr in this case; all trivial 6429 // destructors are constexpr. 6430 // 6431 // If an anonymous union would be destroyed, some enclosing destructor must 6432 // have been explicitly defined, and the anonymous union destruction should 6433 // have no effect. 6434 Value = APValue(); 6435 return true; 6436 } 6437 6438 if (!Info.CheckCallLimit(CallLoc)) 6439 return false; 6440 6441 const FunctionDecl *Definition = nullptr; 6442 const Stmt *Body = DD->getBody(Definition); 6443 6444 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6445 return false; 6446 6447 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6448 6449 // We're now in the period of destruction of this object. 6450 unsigned BasesLeft = RD->getNumBases(); 6451 EvalInfo::EvaluatingDestructorRAII EvalObj( 6452 Info, 6453 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6454 if (!EvalObj.DidInsert) { 6455 // C++2a [class.dtor]p19: 6456 // the behavior is undefined if the destructor is invoked for an object 6457 // whose lifetime has ended 6458 // (Note that formally the lifetime ends when the period of destruction 6459 // begins, even though certain uses of the object remain valid until the 6460 // period of destruction ends.) 6461 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6462 return false; 6463 } 6464 6465 // FIXME: Creating an APValue just to hold a nonexistent return value is 6466 // wasteful. 6467 APValue RetVal; 6468 StmtResult Ret = {RetVal, nullptr}; 6469 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6470 return false; 6471 6472 // A union destructor does not implicitly destroy its members. 6473 if (RD->isUnion()) 6474 return true; 6475 6476 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6477 6478 // We don't have a good way to iterate fields in reverse, so collect all the 6479 // fields first and then walk them backwards. 6480 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6481 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6482 if (FD->isUnnamedBitfield()) 6483 continue; 6484 6485 LValue Subobject = This; 6486 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6487 return false; 6488 6489 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6490 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6491 FD->getType())) 6492 return false; 6493 } 6494 6495 if (BasesLeft != 0) 6496 EvalObj.startedDestroyingBases(); 6497 6498 // Destroy base classes in reverse order. 6499 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6500 --BasesLeft; 6501 6502 QualType BaseType = Base.getType(); 6503 LValue Subobject = This; 6504 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6505 BaseType->getAsCXXRecordDecl(), &Layout)) 6506 return false; 6507 6508 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6509 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6510 BaseType)) 6511 return false; 6512 } 6513 assert(BasesLeft == 0 && "NumBases was wrong?"); 6514 6515 // The period of destruction ends now. The object is gone. 6516 Value = APValue(); 6517 return true; 6518 } 6519 6520 namespace { 6521 struct DestroyObjectHandler { 6522 EvalInfo &Info; 6523 const Expr *E; 6524 const LValue &This; 6525 const AccessKinds AccessKind; 6526 6527 typedef bool result_type; 6528 bool failed() { return false; } 6529 bool found(APValue &Subobj, QualType SubobjType) { 6530 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6531 SubobjType); 6532 } 6533 bool found(APSInt &Value, QualType SubobjType) { 6534 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6535 return false; 6536 } 6537 bool found(APFloat &Value, QualType SubobjType) { 6538 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6539 return false; 6540 } 6541 }; 6542 } 6543 6544 /// Perform a destructor or pseudo-destructor call on the given object, which 6545 /// might in general not be a complete object. 6546 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6547 const LValue &This, QualType ThisType) { 6548 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6549 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6550 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6551 } 6552 6553 /// Destroy and end the lifetime of the given complete object. 6554 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6555 APValue::LValueBase LVBase, APValue &Value, 6556 QualType T) { 6557 // If we've had an unmodeled side-effect, we can't rely on mutable state 6558 // (such as the object we're about to destroy) being correct. 6559 if (Info.EvalStatus.HasSideEffects) 6560 return false; 6561 6562 LValue LV; 6563 LV.set({LVBase}); 6564 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6565 } 6566 6567 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6568 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6569 LValue &Result) { 6570 if (Info.checkingPotentialConstantExpression() || 6571 Info.SpeculativeEvaluationDepth) 6572 return false; 6573 6574 // This is permitted only within a call to std::allocator<T>::allocate. 6575 auto Caller = Info.getStdAllocatorCaller("allocate"); 6576 if (!Caller) { 6577 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6578 ? diag::note_constexpr_new_untyped 6579 : diag::note_constexpr_new); 6580 return false; 6581 } 6582 6583 QualType ElemType = Caller.ElemType; 6584 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6585 Info.FFDiag(E->getExprLoc(), 6586 diag::note_constexpr_new_not_complete_object_type) 6587 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6588 return false; 6589 } 6590 6591 APSInt ByteSize; 6592 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6593 return false; 6594 bool IsNothrow = false; 6595 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6596 EvaluateIgnoredValue(Info, E->getArg(I)); 6597 IsNothrow |= E->getType()->isNothrowT(); 6598 } 6599 6600 CharUnits ElemSize; 6601 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6602 return false; 6603 APInt Size, Remainder; 6604 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6605 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6606 if (Remainder != 0) { 6607 // This likely indicates a bug in the implementation of 'std::allocator'. 6608 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6609 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6610 return false; 6611 } 6612 6613 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6614 if (IsNothrow) { 6615 Result.setNull(Info.Ctx, E->getType()); 6616 return true; 6617 } 6618 6619 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6620 return false; 6621 } 6622 6623 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6624 ArrayType::Normal, 0); 6625 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6626 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6627 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6628 return true; 6629 } 6630 6631 static bool hasVirtualDestructor(QualType T) { 6632 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6633 if (CXXDestructorDecl *DD = RD->getDestructor()) 6634 return DD->isVirtual(); 6635 return false; 6636 } 6637 6638 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6639 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6640 if (CXXDestructorDecl *DD = RD->getDestructor()) 6641 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6642 return nullptr; 6643 } 6644 6645 /// Check that the given object is a suitable pointer to a heap allocation that 6646 /// still exists and is of the right kind for the purpose of a deletion. 6647 /// 6648 /// On success, returns the heap allocation to deallocate. On failure, produces 6649 /// a diagnostic and returns None. 6650 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6651 const LValue &Pointer, 6652 DynAlloc::Kind DeallocKind) { 6653 auto PointerAsString = [&] { 6654 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6655 }; 6656 6657 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6658 if (!DA) { 6659 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6660 << PointerAsString(); 6661 if (Pointer.Base) 6662 NoteLValueLocation(Info, Pointer.Base); 6663 return None; 6664 } 6665 6666 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6667 if (!Alloc) { 6668 Info.FFDiag(E, diag::note_constexpr_double_delete); 6669 return None; 6670 } 6671 6672 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6673 if (DeallocKind != (*Alloc)->getKind()) { 6674 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6675 << DeallocKind << (*Alloc)->getKind() << AllocType; 6676 NoteLValueLocation(Info, Pointer.Base); 6677 return None; 6678 } 6679 6680 bool Subobject = false; 6681 if (DeallocKind == DynAlloc::New) { 6682 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6683 Pointer.Designator.isOnePastTheEnd(); 6684 } else { 6685 Subobject = Pointer.Designator.Entries.size() != 1 || 6686 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6687 } 6688 if (Subobject) { 6689 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6690 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6691 return None; 6692 } 6693 6694 return Alloc; 6695 } 6696 6697 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6698 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6699 if (Info.checkingPotentialConstantExpression() || 6700 Info.SpeculativeEvaluationDepth) 6701 return false; 6702 6703 // This is permitted only within a call to std::allocator<T>::deallocate. 6704 if (!Info.getStdAllocatorCaller("deallocate")) { 6705 Info.FFDiag(E->getExprLoc()); 6706 return true; 6707 } 6708 6709 LValue Pointer; 6710 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6711 return false; 6712 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6713 EvaluateIgnoredValue(Info, E->getArg(I)); 6714 6715 if (Pointer.Designator.Invalid) 6716 return false; 6717 6718 // Deleting a null pointer would have no effect, but it's not permitted by 6719 // std::allocator<T>::deallocate's contract. 6720 if (Pointer.isNullPointer()) { 6721 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6722 return true; 6723 } 6724 6725 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6726 return false; 6727 6728 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6729 return true; 6730 } 6731 6732 //===----------------------------------------------------------------------===// 6733 // Generic Evaluation 6734 //===----------------------------------------------------------------------===// 6735 namespace { 6736 6737 class BitCastBuffer { 6738 // FIXME: We're going to need bit-level granularity when we support 6739 // bit-fields. 6740 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6741 // we don't support a host or target where that is the case. Still, we should 6742 // use a more generic type in case we ever do. 6743 SmallVector<Optional<unsigned char>, 32> Bytes; 6744 6745 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6746 "Need at least 8 bit unsigned char"); 6747 6748 bool TargetIsLittleEndian; 6749 6750 public: 6751 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6752 : Bytes(Width.getQuantity()), 6753 TargetIsLittleEndian(TargetIsLittleEndian) {} 6754 6755 LLVM_NODISCARD 6756 bool readObject(CharUnits Offset, CharUnits Width, 6757 SmallVectorImpl<unsigned char> &Output) const { 6758 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6759 // If a byte of an integer is uninitialized, then the whole integer is 6760 // uninitalized. 6761 if (!Bytes[I.getQuantity()]) 6762 return false; 6763 Output.push_back(*Bytes[I.getQuantity()]); 6764 } 6765 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6766 std::reverse(Output.begin(), Output.end()); 6767 return true; 6768 } 6769 6770 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6771 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6772 std::reverse(Input.begin(), Input.end()); 6773 6774 size_t Index = 0; 6775 for (unsigned char Byte : Input) { 6776 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6777 Bytes[Offset.getQuantity() + Index] = Byte; 6778 ++Index; 6779 } 6780 } 6781 6782 size_t size() { return Bytes.size(); } 6783 }; 6784 6785 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6786 /// target would represent the value at runtime. 6787 class APValueToBufferConverter { 6788 EvalInfo &Info; 6789 BitCastBuffer Buffer; 6790 const CastExpr *BCE; 6791 6792 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6793 const CastExpr *BCE) 6794 : Info(Info), 6795 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6796 BCE(BCE) {} 6797 6798 bool visit(const APValue &Val, QualType Ty) { 6799 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6800 } 6801 6802 // Write out Val with type Ty into Buffer starting at Offset. 6803 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6804 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6805 6806 // As a special case, nullptr_t has an indeterminate value. 6807 if (Ty->isNullPtrType()) 6808 return true; 6809 6810 // Dig through Src to find the byte at SrcOffset. 6811 switch (Val.getKind()) { 6812 case APValue::Indeterminate: 6813 case APValue::None: 6814 return true; 6815 6816 case APValue::Int: 6817 return visitInt(Val.getInt(), Ty, Offset); 6818 case APValue::Float: 6819 return visitFloat(Val.getFloat(), Ty, Offset); 6820 case APValue::Array: 6821 return visitArray(Val, Ty, Offset); 6822 case APValue::Struct: 6823 return visitRecord(Val, Ty, Offset); 6824 6825 case APValue::ComplexInt: 6826 case APValue::ComplexFloat: 6827 case APValue::Vector: 6828 case APValue::FixedPoint: 6829 // FIXME: We should support these. 6830 6831 case APValue::Union: 6832 case APValue::MemberPointer: 6833 case APValue::AddrLabelDiff: { 6834 Info.FFDiag(BCE->getBeginLoc(), 6835 diag::note_constexpr_bit_cast_unsupported_type) 6836 << Ty; 6837 return false; 6838 } 6839 6840 case APValue::LValue: 6841 llvm_unreachable("LValue subobject in bit_cast?"); 6842 } 6843 llvm_unreachable("Unhandled APValue::ValueKind"); 6844 } 6845 6846 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6847 const RecordDecl *RD = Ty->getAsRecordDecl(); 6848 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6849 6850 // Visit the base classes. 6851 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6852 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6853 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6854 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6855 6856 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6857 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6858 return false; 6859 } 6860 } 6861 6862 // Visit the fields. 6863 unsigned FieldIdx = 0; 6864 for (FieldDecl *FD : RD->fields()) { 6865 if (FD->isBitField()) { 6866 Info.FFDiag(BCE->getBeginLoc(), 6867 diag::note_constexpr_bit_cast_unsupported_bitfield); 6868 return false; 6869 } 6870 6871 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6872 6873 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6874 "only bit-fields can have sub-char alignment"); 6875 CharUnits FieldOffset = 6876 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6877 QualType FieldTy = FD->getType(); 6878 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6879 return false; 6880 ++FieldIdx; 6881 } 6882 6883 return true; 6884 } 6885 6886 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6887 const auto *CAT = 6888 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6889 if (!CAT) 6890 return false; 6891 6892 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6893 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6894 unsigned ArraySize = Val.getArraySize(); 6895 // First, initialize the initialized elements. 6896 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6897 const APValue &SubObj = Val.getArrayInitializedElt(I); 6898 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6899 return false; 6900 } 6901 6902 // Next, initialize the rest of the array using the filler. 6903 if (Val.hasArrayFiller()) { 6904 const APValue &Filler = Val.getArrayFiller(); 6905 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6906 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6907 return false; 6908 } 6909 } 6910 6911 return true; 6912 } 6913 6914 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6915 APSInt AdjustedVal = Val; 6916 unsigned Width = AdjustedVal.getBitWidth(); 6917 if (Ty->isBooleanType()) { 6918 Width = Info.Ctx.getTypeSize(Ty); 6919 AdjustedVal = AdjustedVal.extend(Width); 6920 } 6921 6922 SmallVector<unsigned char, 8> Bytes(Width / 8); 6923 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6924 Buffer.writeObject(Offset, Bytes); 6925 return true; 6926 } 6927 6928 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6929 APSInt AsInt(Val.bitcastToAPInt()); 6930 return visitInt(AsInt, Ty, Offset); 6931 } 6932 6933 public: 6934 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6935 const CastExpr *BCE) { 6936 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6937 APValueToBufferConverter Converter(Info, DstSize, BCE); 6938 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6939 return None; 6940 return Converter.Buffer; 6941 } 6942 }; 6943 6944 /// Write an BitCastBuffer into an APValue. 6945 class BufferToAPValueConverter { 6946 EvalInfo &Info; 6947 const BitCastBuffer &Buffer; 6948 const CastExpr *BCE; 6949 6950 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6951 const CastExpr *BCE) 6952 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6953 6954 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6955 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6956 // Ideally this will be unreachable. 6957 llvm::NoneType unsupportedType(QualType Ty) { 6958 Info.FFDiag(BCE->getBeginLoc(), 6959 diag::note_constexpr_bit_cast_unsupported_type) 6960 << Ty; 6961 return None; 6962 } 6963 6964 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6965 Info.FFDiag(BCE->getBeginLoc(), 6966 diag::note_constexpr_bit_cast_unrepresentable_value) 6967 << Ty << Val.toString(/*Radix=*/10); 6968 return None; 6969 } 6970 6971 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6972 const EnumType *EnumSugar = nullptr) { 6973 if (T->isNullPtrType()) { 6974 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6975 return APValue((Expr *)nullptr, 6976 /*Offset=*/CharUnits::fromQuantity(NullValue), 6977 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6978 } 6979 6980 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6981 6982 // Work around floating point types that contain unused padding bytes. This 6983 // is really just `long double` on x86, which is the only fundamental type 6984 // with padding bytes. 6985 if (T->isRealFloatingType()) { 6986 const llvm::fltSemantics &Semantics = 6987 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6988 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6989 assert(NumBits % 8 == 0); 6990 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6991 if (NumBytes != SizeOf) 6992 SizeOf = NumBytes; 6993 } 6994 6995 SmallVector<uint8_t, 8> Bytes; 6996 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6997 // If this is std::byte or unsigned char, then its okay to store an 6998 // indeterminate value. 6999 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7000 bool IsUChar = 7001 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7002 T->isSpecificBuiltinType(BuiltinType::Char_U)); 7003 if (!IsStdByte && !IsUChar) { 7004 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7005 Info.FFDiag(BCE->getExprLoc(), 7006 diag::note_constexpr_bit_cast_indet_dest) 7007 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7008 return None; 7009 } 7010 7011 return APValue::IndeterminateValue(); 7012 } 7013 7014 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7015 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7016 7017 if (T->isIntegralOrEnumerationType()) { 7018 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7019 7020 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7021 if (IntWidth != Val.getBitWidth()) { 7022 APSInt Truncated = Val.trunc(IntWidth); 7023 if (Truncated.extend(Val.getBitWidth()) != Val) 7024 return unrepresentableValue(QualType(T, 0), Val); 7025 Val = Truncated; 7026 } 7027 7028 return APValue(Val); 7029 } 7030 7031 if (T->isRealFloatingType()) { 7032 const llvm::fltSemantics &Semantics = 7033 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7034 return APValue(APFloat(Semantics, Val)); 7035 } 7036 7037 return unsupportedType(QualType(T, 0)); 7038 } 7039 7040 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7041 const RecordDecl *RD = RTy->getAsRecordDecl(); 7042 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7043 7044 unsigned NumBases = 0; 7045 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7046 NumBases = CXXRD->getNumBases(); 7047 7048 APValue ResultVal(APValue::UninitStruct(), NumBases, 7049 std::distance(RD->field_begin(), RD->field_end())); 7050 7051 // Visit the base classes. 7052 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7053 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7054 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7055 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7056 if (BaseDecl->isEmpty() || 7057 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7058 continue; 7059 7060 Optional<APValue> SubObj = visitType( 7061 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7062 if (!SubObj) 7063 return None; 7064 ResultVal.getStructBase(I) = *SubObj; 7065 } 7066 } 7067 7068 // Visit the fields. 7069 unsigned FieldIdx = 0; 7070 for (FieldDecl *FD : RD->fields()) { 7071 // FIXME: We don't currently support bit-fields. A lot of the logic for 7072 // this is in CodeGen, so we need to factor it around. 7073 if (FD->isBitField()) { 7074 Info.FFDiag(BCE->getBeginLoc(), 7075 diag::note_constexpr_bit_cast_unsupported_bitfield); 7076 return None; 7077 } 7078 7079 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7080 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7081 7082 CharUnits FieldOffset = 7083 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7084 Offset; 7085 QualType FieldTy = FD->getType(); 7086 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7087 if (!SubObj) 7088 return None; 7089 ResultVal.getStructField(FieldIdx) = *SubObj; 7090 ++FieldIdx; 7091 } 7092 7093 return ResultVal; 7094 } 7095 7096 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7097 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7098 assert(!RepresentationType.isNull() && 7099 "enum forward decl should be caught by Sema"); 7100 const auto *AsBuiltin = 7101 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7102 // Recurse into the underlying type. Treat std::byte transparently as 7103 // unsigned char. 7104 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7105 } 7106 7107 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7108 size_t Size = Ty->getSize().getLimitedValue(); 7109 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7110 7111 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7112 for (size_t I = 0; I != Size; ++I) { 7113 Optional<APValue> ElementValue = 7114 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7115 if (!ElementValue) 7116 return None; 7117 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7118 } 7119 7120 return ArrayValue; 7121 } 7122 7123 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7124 return unsupportedType(QualType(Ty, 0)); 7125 } 7126 7127 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7128 QualType Can = Ty.getCanonicalType(); 7129 7130 switch (Can->getTypeClass()) { 7131 #define TYPE(Class, Base) \ 7132 case Type::Class: \ 7133 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7134 #define ABSTRACT_TYPE(Class, Base) 7135 #define NON_CANONICAL_TYPE(Class, Base) \ 7136 case Type::Class: \ 7137 llvm_unreachable("non-canonical type should be impossible!"); 7138 #define DEPENDENT_TYPE(Class, Base) \ 7139 case Type::Class: \ 7140 llvm_unreachable( \ 7141 "dependent types aren't supported in the constant evaluator!"); 7142 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7143 case Type::Class: \ 7144 llvm_unreachable("either dependent or not canonical!"); 7145 #include "clang/AST/TypeNodes.inc" 7146 } 7147 llvm_unreachable("Unhandled Type::TypeClass"); 7148 } 7149 7150 public: 7151 // Pull out a full value of type DstType. 7152 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7153 const CastExpr *BCE) { 7154 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7155 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7156 } 7157 }; 7158 7159 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7160 QualType Ty, EvalInfo *Info, 7161 const ASTContext &Ctx, 7162 bool CheckingDest) { 7163 Ty = Ty.getCanonicalType(); 7164 7165 auto diag = [&](int Reason) { 7166 if (Info) 7167 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7168 << CheckingDest << (Reason == 4) << Reason; 7169 return false; 7170 }; 7171 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7172 if (Info) 7173 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7174 << NoteTy << Construct << Ty; 7175 return false; 7176 }; 7177 7178 if (Ty->isUnionType()) 7179 return diag(0); 7180 if (Ty->isPointerType()) 7181 return diag(1); 7182 if (Ty->isMemberPointerType()) 7183 return diag(2); 7184 if (Ty.isVolatileQualified()) 7185 return diag(3); 7186 7187 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7188 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7189 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7190 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7191 CheckingDest)) 7192 return note(1, BS.getType(), BS.getBeginLoc()); 7193 } 7194 for (FieldDecl *FD : Record->fields()) { 7195 if (FD->getType()->isReferenceType()) 7196 return diag(4); 7197 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7198 CheckingDest)) 7199 return note(0, FD->getType(), FD->getBeginLoc()); 7200 } 7201 } 7202 7203 if (Ty->isArrayType() && 7204 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7205 Info, Ctx, CheckingDest)) 7206 return false; 7207 7208 return true; 7209 } 7210 7211 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7212 const ASTContext &Ctx, 7213 const CastExpr *BCE) { 7214 bool DestOK = checkBitCastConstexprEligibilityType( 7215 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7216 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7217 BCE->getBeginLoc(), 7218 BCE->getSubExpr()->getType(), Info, Ctx, false); 7219 return SourceOK; 7220 } 7221 7222 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7223 APValue &SourceValue, 7224 const CastExpr *BCE) { 7225 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7226 "no host or target supports non 8-bit chars"); 7227 assert(SourceValue.isLValue() && 7228 "LValueToRValueBitcast requires an lvalue operand!"); 7229 7230 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7231 return false; 7232 7233 LValue SourceLValue; 7234 APValue SourceRValue; 7235 SourceLValue.setFrom(Info.Ctx, SourceValue); 7236 if (!handleLValueToRValueConversion( 7237 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7238 SourceRValue, /*WantObjectRepresentation=*/true)) 7239 return false; 7240 7241 // Read out SourceValue into a char buffer. 7242 Optional<BitCastBuffer> Buffer = 7243 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7244 if (!Buffer) 7245 return false; 7246 7247 // Write out the buffer into a new APValue. 7248 Optional<APValue> MaybeDestValue = 7249 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7250 if (!MaybeDestValue) 7251 return false; 7252 7253 DestValue = std::move(*MaybeDestValue); 7254 return true; 7255 } 7256 7257 template <class Derived> 7258 class ExprEvaluatorBase 7259 : public ConstStmtVisitor<Derived, bool> { 7260 private: 7261 Derived &getDerived() { return static_cast<Derived&>(*this); } 7262 bool DerivedSuccess(const APValue &V, const Expr *E) { 7263 return getDerived().Success(V, E); 7264 } 7265 bool DerivedZeroInitialization(const Expr *E) { 7266 return getDerived().ZeroInitialization(E); 7267 } 7268 7269 // Check whether a conditional operator with a non-constant condition is a 7270 // potential constant expression. If neither arm is a potential constant 7271 // expression, then the conditional operator is not either. 7272 template<typename ConditionalOperator> 7273 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7274 assert(Info.checkingPotentialConstantExpression()); 7275 7276 // Speculatively evaluate both arms. 7277 SmallVector<PartialDiagnosticAt, 8> Diag; 7278 { 7279 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7280 StmtVisitorTy::Visit(E->getFalseExpr()); 7281 if (Diag.empty()) 7282 return; 7283 } 7284 7285 { 7286 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7287 Diag.clear(); 7288 StmtVisitorTy::Visit(E->getTrueExpr()); 7289 if (Diag.empty()) 7290 return; 7291 } 7292 7293 Error(E, diag::note_constexpr_conditional_never_const); 7294 } 7295 7296 7297 template<typename ConditionalOperator> 7298 bool HandleConditionalOperator(const ConditionalOperator *E) { 7299 bool BoolResult; 7300 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7301 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7302 CheckPotentialConstantConditional(E); 7303 return false; 7304 } 7305 if (Info.noteFailure()) { 7306 StmtVisitorTy::Visit(E->getTrueExpr()); 7307 StmtVisitorTy::Visit(E->getFalseExpr()); 7308 } 7309 return false; 7310 } 7311 7312 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7313 return StmtVisitorTy::Visit(EvalExpr); 7314 } 7315 7316 protected: 7317 EvalInfo &Info; 7318 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7319 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7320 7321 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7322 return Info.CCEDiag(E, D); 7323 } 7324 7325 bool ZeroInitialization(const Expr *E) { return Error(E); } 7326 7327 public: 7328 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7329 7330 EvalInfo &getEvalInfo() { return Info; } 7331 7332 /// Report an evaluation error. This should only be called when an error is 7333 /// first discovered. When propagating an error, just return false. 7334 bool Error(const Expr *E, diag::kind D) { 7335 Info.FFDiag(E, D); 7336 return false; 7337 } 7338 bool Error(const Expr *E) { 7339 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7340 } 7341 7342 bool VisitStmt(const Stmt *) { 7343 llvm_unreachable("Expression evaluator should not be called on stmts"); 7344 } 7345 bool VisitExpr(const Expr *E) { 7346 return Error(E); 7347 } 7348 7349 bool VisitConstantExpr(const ConstantExpr *E) { 7350 if (E->hasAPValueResult()) 7351 return DerivedSuccess(E->getAPValueResult(), E); 7352 7353 return StmtVisitorTy::Visit(E->getSubExpr()); 7354 } 7355 7356 bool VisitParenExpr(const ParenExpr *E) 7357 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7358 bool VisitUnaryExtension(const UnaryOperator *E) 7359 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7360 bool VisitUnaryPlus(const UnaryOperator *E) 7361 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7362 bool VisitChooseExpr(const ChooseExpr *E) 7363 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7364 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7365 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7366 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7367 { return StmtVisitorTy::Visit(E->getReplacement()); } 7368 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7369 TempVersionRAII RAII(*Info.CurrentCall); 7370 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7371 return StmtVisitorTy::Visit(E->getExpr()); 7372 } 7373 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7374 TempVersionRAII RAII(*Info.CurrentCall); 7375 // The initializer may not have been parsed yet, or might be erroneous. 7376 if (!E->getExpr()) 7377 return Error(E); 7378 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7379 return StmtVisitorTy::Visit(E->getExpr()); 7380 } 7381 7382 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7383 FullExpressionRAII Scope(Info); 7384 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7385 } 7386 7387 // Temporaries are registered when created, so we don't care about 7388 // CXXBindTemporaryExpr. 7389 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7390 return StmtVisitorTy::Visit(E->getSubExpr()); 7391 } 7392 7393 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7394 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7395 return static_cast<Derived*>(this)->VisitCastExpr(E); 7396 } 7397 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7398 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7399 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7400 return static_cast<Derived*>(this)->VisitCastExpr(E); 7401 } 7402 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7403 return static_cast<Derived*>(this)->VisitCastExpr(E); 7404 } 7405 7406 bool VisitBinaryOperator(const BinaryOperator *E) { 7407 switch (E->getOpcode()) { 7408 default: 7409 return Error(E); 7410 7411 case BO_Comma: 7412 VisitIgnoredValue(E->getLHS()); 7413 return StmtVisitorTy::Visit(E->getRHS()); 7414 7415 case BO_PtrMemD: 7416 case BO_PtrMemI: { 7417 LValue Obj; 7418 if (!HandleMemberPointerAccess(Info, E, Obj)) 7419 return false; 7420 APValue Result; 7421 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7422 return false; 7423 return DerivedSuccess(Result, E); 7424 } 7425 } 7426 } 7427 7428 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7429 return StmtVisitorTy::Visit(E->getSemanticForm()); 7430 } 7431 7432 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7433 // Evaluate and cache the common expression. We treat it as a temporary, 7434 // even though it's not quite the same thing. 7435 LValue CommonLV; 7436 if (!Evaluate(Info.CurrentCall->createTemporary( 7437 E->getOpaqueValue(), 7438 getStorageType(Info.Ctx, E->getOpaqueValue()), 7439 ScopeKind::FullExpression, CommonLV), 7440 Info, E->getCommon())) 7441 return false; 7442 7443 return HandleConditionalOperator(E); 7444 } 7445 7446 bool VisitConditionalOperator(const ConditionalOperator *E) { 7447 bool IsBcpCall = false; 7448 // If the condition (ignoring parens) is a __builtin_constant_p call, 7449 // the result is a constant expression if it can be folded without 7450 // side-effects. This is an important GNU extension. See GCC PR38377 7451 // for discussion. 7452 if (const CallExpr *CallCE = 7453 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7454 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7455 IsBcpCall = true; 7456 7457 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7458 // constant expression; we can't check whether it's potentially foldable. 7459 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7460 // it would return 'false' in this mode. 7461 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7462 return false; 7463 7464 FoldConstant Fold(Info, IsBcpCall); 7465 if (!HandleConditionalOperator(E)) { 7466 Fold.keepDiagnostics(); 7467 return false; 7468 } 7469 7470 return true; 7471 } 7472 7473 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7474 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7475 return DerivedSuccess(*Value, E); 7476 7477 const Expr *Source = E->getSourceExpr(); 7478 if (!Source) 7479 return Error(E); 7480 if (Source == E) { // sanity checking. 7481 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7482 return Error(E); 7483 } 7484 return StmtVisitorTy::Visit(Source); 7485 } 7486 7487 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7488 for (const Expr *SemE : E->semantics()) { 7489 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7490 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7491 // result expression: there could be two different LValues that would 7492 // refer to the same object in that case, and we can't model that. 7493 if (SemE == E->getResultExpr()) 7494 return Error(E); 7495 7496 // Unique OVEs get evaluated if and when we encounter them when 7497 // emitting the rest of the semantic form, rather than eagerly. 7498 if (OVE->isUnique()) 7499 continue; 7500 7501 LValue LV; 7502 if (!Evaluate(Info.CurrentCall->createTemporary( 7503 OVE, getStorageType(Info.Ctx, OVE), 7504 ScopeKind::FullExpression, LV), 7505 Info, OVE->getSourceExpr())) 7506 return false; 7507 } else if (SemE == E->getResultExpr()) { 7508 if (!StmtVisitorTy::Visit(SemE)) 7509 return false; 7510 } else { 7511 if (!EvaluateIgnoredValue(Info, SemE)) 7512 return false; 7513 } 7514 } 7515 return true; 7516 } 7517 7518 bool VisitCallExpr(const CallExpr *E) { 7519 APValue Result; 7520 if (!handleCallExpr(E, Result, nullptr)) 7521 return false; 7522 return DerivedSuccess(Result, E); 7523 } 7524 7525 bool handleCallExpr(const CallExpr *E, APValue &Result, 7526 const LValue *ResultSlot) { 7527 CallScopeRAII CallScope(Info); 7528 7529 const Expr *Callee = E->getCallee()->IgnoreParens(); 7530 QualType CalleeType = Callee->getType(); 7531 7532 const FunctionDecl *FD = nullptr; 7533 LValue *This = nullptr, ThisVal; 7534 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7535 bool HasQualifier = false; 7536 7537 CallRef Call; 7538 7539 // Extract function decl and 'this' pointer from the callee. 7540 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7541 const CXXMethodDecl *Member = nullptr; 7542 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7543 // Explicit bound member calls, such as x.f() or p->g(); 7544 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7545 return false; 7546 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7547 if (!Member) 7548 return Error(Callee); 7549 This = &ThisVal; 7550 HasQualifier = ME->hasQualifier(); 7551 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7552 // Indirect bound member calls ('.*' or '->*'). 7553 const ValueDecl *D = 7554 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7555 if (!D) 7556 return false; 7557 Member = dyn_cast<CXXMethodDecl>(D); 7558 if (!Member) 7559 return Error(Callee); 7560 This = &ThisVal; 7561 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7562 if (!Info.getLangOpts().CPlusPlus20) 7563 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7564 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7565 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7566 } else 7567 return Error(Callee); 7568 FD = Member; 7569 } else if (CalleeType->isFunctionPointerType()) { 7570 LValue CalleeLV; 7571 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7572 return false; 7573 7574 if (!CalleeLV.getLValueOffset().isZero()) 7575 return Error(Callee); 7576 FD = dyn_cast_or_null<FunctionDecl>( 7577 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7578 if (!FD) 7579 return Error(Callee); 7580 // Don't call function pointers which have been cast to some other type. 7581 // Per DR (no number yet), the caller and callee can differ in noexcept. 7582 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7583 CalleeType->getPointeeType(), FD->getType())) { 7584 return Error(E); 7585 } 7586 7587 // For an (overloaded) assignment expression, evaluate the RHS before the 7588 // LHS. 7589 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7590 if (OCE && OCE->isAssignmentOp()) { 7591 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7592 Call = Info.CurrentCall->createCall(FD); 7593 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7594 Info, FD, /*RightToLeft=*/true)) 7595 return false; 7596 } 7597 7598 // Overloaded operator calls to member functions are represented as normal 7599 // calls with '*this' as the first argument. 7600 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7601 if (MD && !MD->isStatic()) { 7602 // FIXME: When selecting an implicit conversion for an overloaded 7603 // operator delete, we sometimes try to evaluate calls to conversion 7604 // operators without a 'this' parameter! 7605 if (Args.empty()) 7606 return Error(E); 7607 7608 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7609 return false; 7610 This = &ThisVal; 7611 Args = Args.slice(1); 7612 } else if (MD && MD->isLambdaStaticInvoker()) { 7613 // Map the static invoker for the lambda back to the call operator. 7614 // Conveniently, we don't have to slice out the 'this' argument (as is 7615 // being done for the non-static case), since a static member function 7616 // doesn't have an implicit argument passed in. 7617 const CXXRecordDecl *ClosureClass = MD->getParent(); 7618 assert( 7619 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7620 "Number of captures must be zero for conversion to function-ptr"); 7621 7622 const CXXMethodDecl *LambdaCallOp = 7623 ClosureClass->getLambdaCallOperator(); 7624 7625 // Set 'FD', the function that will be called below, to the call 7626 // operator. If the closure object represents a generic lambda, find 7627 // the corresponding specialization of the call operator. 7628 7629 if (ClosureClass->isGenericLambda()) { 7630 assert(MD->isFunctionTemplateSpecialization() && 7631 "A generic lambda's static-invoker function must be a " 7632 "template specialization"); 7633 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7634 FunctionTemplateDecl *CallOpTemplate = 7635 LambdaCallOp->getDescribedFunctionTemplate(); 7636 void *InsertPos = nullptr; 7637 FunctionDecl *CorrespondingCallOpSpecialization = 7638 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7639 assert(CorrespondingCallOpSpecialization && 7640 "We must always have a function call operator specialization " 7641 "that corresponds to our static invoker specialization"); 7642 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7643 } else 7644 FD = LambdaCallOp; 7645 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7646 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7647 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7648 LValue Ptr; 7649 if (!HandleOperatorNewCall(Info, E, Ptr)) 7650 return false; 7651 Ptr.moveInto(Result); 7652 return CallScope.destroy(); 7653 } else { 7654 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7655 } 7656 } 7657 } else 7658 return Error(E); 7659 7660 // Evaluate the arguments now if we've not already done so. 7661 if (!Call) { 7662 Call = Info.CurrentCall->createCall(FD); 7663 if (!EvaluateArgs(Args, Call, Info, FD)) 7664 return false; 7665 } 7666 7667 SmallVector<QualType, 4> CovariantAdjustmentPath; 7668 if (This) { 7669 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7670 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7671 // Perform virtual dispatch, if necessary. 7672 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7673 CovariantAdjustmentPath); 7674 if (!FD) 7675 return false; 7676 } else { 7677 // Check that the 'this' pointer points to an object of the right type. 7678 // FIXME: If this is an assignment operator call, we may need to change 7679 // the active union member before we check this. 7680 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7681 return false; 7682 } 7683 } 7684 7685 // Destructor calls are different enough that they have their own codepath. 7686 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7687 assert(This && "no 'this' pointer for destructor call"); 7688 return HandleDestruction(Info, E, *This, 7689 Info.Ctx.getRecordType(DD->getParent())) && 7690 CallScope.destroy(); 7691 } 7692 7693 const FunctionDecl *Definition = nullptr; 7694 Stmt *Body = FD->getBody(Definition); 7695 7696 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7697 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7698 Body, Info, Result, ResultSlot)) 7699 return false; 7700 7701 if (!CovariantAdjustmentPath.empty() && 7702 !HandleCovariantReturnAdjustment(Info, E, Result, 7703 CovariantAdjustmentPath)) 7704 return false; 7705 7706 return CallScope.destroy(); 7707 } 7708 7709 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7710 return StmtVisitorTy::Visit(E->getInitializer()); 7711 } 7712 bool VisitInitListExpr(const InitListExpr *E) { 7713 if (E->getNumInits() == 0) 7714 return DerivedZeroInitialization(E); 7715 if (E->getNumInits() == 1) 7716 return StmtVisitorTy::Visit(E->getInit(0)); 7717 return Error(E); 7718 } 7719 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7720 return DerivedZeroInitialization(E); 7721 } 7722 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7723 return DerivedZeroInitialization(E); 7724 } 7725 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7726 return DerivedZeroInitialization(E); 7727 } 7728 7729 /// A member expression where the object is a prvalue is itself a prvalue. 7730 bool VisitMemberExpr(const MemberExpr *E) { 7731 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7732 "missing temporary materialization conversion"); 7733 assert(!E->isArrow() && "missing call to bound member function?"); 7734 7735 APValue Val; 7736 if (!Evaluate(Val, Info, E->getBase())) 7737 return false; 7738 7739 QualType BaseTy = E->getBase()->getType(); 7740 7741 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7742 if (!FD) return Error(E); 7743 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7744 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7745 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7746 7747 // Note: there is no lvalue base here. But this case should only ever 7748 // happen in C or in C++98, where we cannot be evaluating a constexpr 7749 // constructor, which is the only case the base matters. 7750 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7751 SubobjectDesignator Designator(BaseTy); 7752 Designator.addDeclUnchecked(FD); 7753 7754 APValue Result; 7755 return extractSubobject(Info, E, Obj, Designator, Result) && 7756 DerivedSuccess(Result, E); 7757 } 7758 7759 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7760 APValue Val; 7761 if (!Evaluate(Val, Info, E->getBase())) 7762 return false; 7763 7764 if (Val.isVector()) { 7765 SmallVector<uint32_t, 4> Indices; 7766 E->getEncodedElementAccess(Indices); 7767 if (Indices.size() == 1) { 7768 // Return scalar. 7769 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7770 } else { 7771 // Construct new APValue vector. 7772 SmallVector<APValue, 4> Elts; 7773 for (unsigned I = 0; I < Indices.size(); ++I) { 7774 Elts.push_back(Val.getVectorElt(Indices[I])); 7775 } 7776 APValue VecResult(Elts.data(), Indices.size()); 7777 return DerivedSuccess(VecResult, E); 7778 } 7779 } 7780 7781 return false; 7782 } 7783 7784 bool VisitCastExpr(const CastExpr *E) { 7785 switch (E->getCastKind()) { 7786 default: 7787 break; 7788 7789 case CK_AtomicToNonAtomic: { 7790 APValue AtomicVal; 7791 // This does not need to be done in place even for class/array types: 7792 // atomic-to-non-atomic conversion implies copying the object 7793 // representation. 7794 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7795 return false; 7796 return DerivedSuccess(AtomicVal, E); 7797 } 7798 7799 case CK_NoOp: 7800 case CK_UserDefinedConversion: 7801 return StmtVisitorTy::Visit(E->getSubExpr()); 7802 7803 case CK_LValueToRValue: { 7804 LValue LVal; 7805 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7806 return false; 7807 APValue RVal; 7808 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7809 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7810 LVal, RVal)) 7811 return false; 7812 return DerivedSuccess(RVal, E); 7813 } 7814 case CK_LValueToRValueBitCast: { 7815 APValue DestValue, SourceValue; 7816 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7817 return false; 7818 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7819 return false; 7820 return DerivedSuccess(DestValue, E); 7821 } 7822 7823 case CK_AddressSpaceConversion: { 7824 APValue Value; 7825 if (!Evaluate(Value, Info, E->getSubExpr())) 7826 return false; 7827 return DerivedSuccess(Value, E); 7828 } 7829 } 7830 7831 return Error(E); 7832 } 7833 7834 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7835 return VisitUnaryPostIncDec(UO); 7836 } 7837 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7838 return VisitUnaryPostIncDec(UO); 7839 } 7840 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7841 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7842 return Error(UO); 7843 7844 LValue LVal; 7845 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7846 return false; 7847 APValue RVal; 7848 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7849 UO->isIncrementOp(), &RVal)) 7850 return false; 7851 return DerivedSuccess(RVal, UO); 7852 } 7853 7854 bool VisitStmtExpr(const StmtExpr *E) { 7855 // We will have checked the full-expressions inside the statement expression 7856 // when they were completed, and don't need to check them again now. 7857 llvm::SaveAndRestore<bool> NotCheckingForUB( 7858 Info.CheckingForUndefinedBehavior, false); 7859 7860 const CompoundStmt *CS = E->getSubStmt(); 7861 if (CS->body_empty()) 7862 return true; 7863 7864 BlockScopeRAII Scope(Info); 7865 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7866 BE = CS->body_end(); 7867 /**/; ++BI) { 7868 if (BI + 1 == BE) { 7869 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7870 if (!FinalExpr) { 7871 Info.FFDiag((*BI)->getBeginLoc(), 7872 diag::note_constexpr_stmt_expr_unsupported); 7873 return false; 7874 } 7875 return this->Visit(FinalExpr) && Scope.destroy(); 7876 } 7877 7878 APValue ReturnValue; 7879 StmtResult Result = { ReturnValue, nullptr }; 7880 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7881 if (ESR != ESR_Succeeded) { 7882 // FIXME: If the statement-expression terminated due to 'return', 7883 // 'break', or 'continue', it would be nice to propagate that to 7884 // the outer statement evaluation rather than bailing out. 7885 if (ESR != ESR_Failed) 7886 Info.FFDiag((*BI)->getBeginLoc(), 7887 diag::note_constexpr_stmt_expr_unsupported); 7888 return false; 7889 } 7890 } 7891 7892 llvm_unreachable("Return from function from the loop above."); 7893 } 7894 7895 /// Visit a value which is evaluated, but whose value is ignored. 7896 void VisitIgnoredValue(const Expr *E) { 7897 EvaluateIgnoredValue(Info, E); 7898 } 7899 7900 /// Potentially visit a MemberExpr's base expression. 7901 void VisitIgnoredBaseExpression(const Expr *E) { 7902 // While MSVC doesn't evaluate the base expression, it does diagnose the 7903 // presence of side-effecting behavior. 7904 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7905 return; 7906 VisitIgnoredValue(E); 7907 } 7908 }; 7909 7910 } // namespace 7911 7912 //===----------------------------------------------------------------------===// 7913 // Common base class for lvalue and temporary evaluation. 7914 //===----------------------------------------------------------------------===// 7915 namespace { 7916 template<class Derived> 7917 class LValueExprEvaluatorBase 7918 : public ExprEvaluatorBase<Derived> { 7919 protected: 7920 LValue &Result; 7921 bool InvalidBaseOK; 7922 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7923 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7924 7925 bool Success(APValue::LValueBase B) { 7926 Result.set(B); 7927 return true; 7928 } 7929 7930 bool evaluatePointer(const Expr *E, LValue &Result) { 7931 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7932 } 7933 7934 public: 7935 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7936 : ExprEvaluatorBaseTy(Info), Result(Result), 7937 InvalidBaseOK(InvalidBaseOK) {} 7938 7939 bool Success(const APValue &V, const Expr *E) { 7940 Result.setFrom(this->Info.Ctx, V); 7941 return true; 7942 } 7943 7944 bool VisitMemberExpr(const MemberExpr *E) { 7945 // Handle non-static data members. 7946 QualType BaseTy; 7947 bool EvalOK; 7948 if (E->isArrow()) { 7949 EvalOK = evaluatePointer(E->getBase(), Result); 7950 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7951 } else if (E->getBase()->isRValue()) { 7952 assert(E->getBase()->getType()->isRecordType()); 7953 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7954 BaseTy = E->getBase()->getType(); 7955 } else { 7956 EvalOK = this->Visit(E->getBase()); 7957 BaseTy = E->getBase()->getType(); 7958 } 7959 if (!EvalOK) { 7960 if (!InvalidBaseOK) 7961 return false; 7962 Result.setInvalid(E); 7963 return true; 7964 } 7965 7966 const ValueDecl *MD = E->getMemberDecl(); 7967 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7968 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7969 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7970 (void)BaseTy; 7971 if (!HandleLValueMember(this->Info, E, Result, FD)) 7972 return false; 7973 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7974 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7975 return false; 7976 } else 7977 return this->Error(E); 7978 7979 if (MD->getType()->isReferenceType()) { 7980 APValue RefValue; 7981 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7982 RefValue)) 7983 return false; 7984 return Success(RefValue, E); 7985 } 7986 return true; 7987 } 7988 7989 bool VisitBinaryOperator(const BinaryOperator *E) { 7990 switch (E->getOpcode()) { 7991 default: 7992 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7993 7994 case BO_PtrMemD: 7995 case BO_PtrMemI: 7996 return HandleMemberPointerAccess(this->Info, E, Result); 7997 } 7998 } 7999 8000 bool VisitCastExpr(const CastExpr *E) { 8001 switch (E->getCastKind()) { 8002 default: 8003 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8004 8005 case CK_DerivedToBase: 8006 case CK_UncheckedDerivedToBase: 8007 if (!this->Visit(E->getSubExpr())) 8008 return false; 8009 8010 // Now figure out the necessary offset to add to the base LV to get from 8011 // the derived class to the base class. 8012 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8013 Result); 8014 } 8015 } 8016 }; 8017 } 8018 8019 //===----------------------------------------------------------------------===// 8020 // LValue Evaluation 8021 // 8022 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8023 // function designators (in C), decl references to void objects (in C), and 8024 // temporaries (if building with -Wno-address-of-temporary). 8025 // 8026 // LValue evaluation produces values comprising a base expression of one of the 8027 // following types: 8028 // - Declarations 8029 // * VarDecl 8030 // * FunctionDecl 8031 // - Literals 8032 // * CompoundLiteralExpr in C (and in global scope in C++) 8033 // * StringLiteral 8034 // * PredefinedExpr 8035 // * ObjCStringLiteralExpr 8036 // * ObjCEncodeExpr 8037 // * AddrLabelExpr 8038 // * BlockExpr 8039 // * CallExpr for a MakeStringConstant builtin 8040 // - typeid(T) expressions, as TypeInfoLValues 8041 // - Locals and temporaries 8042 // * MaterializeTemporaryExpr 8043 // * Any Expr, with a CallIndex indicating the function in which the temporary 8044 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8045 // from the AST (FIXME). 8046 // * A MaterializeTemporaryExpr that has static storage duration, with no 8047 // CallIndex, for a lifetime-extended temporary. 8048 // * The ConstantExpr that is currently being evaluated during evaluation of an 8049 // immediate invocation. 8050 // plus an offset in bytes. 8051 //===----------------------------------------------------------------------===// 8052 namespace { 8053 class LValueExprEvaluator 8054 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8055 public: 8056 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8057 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8058 8059 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8060 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8061 8062 bool VisitDeclRefExpr(const DeclRefExpr *E); 8063 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8064 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8065 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8066 bool VisitMemberExpr(const MemberExpr *E); 8067 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8068 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8069 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8070 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8071 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8072 bool VisitUnaryDeref(const UnaryOperator *E); 8073 bool VisitUnaryReal(const UnaryOperator *E); 8074 bool VisitUnaryImag(const UnaryOperator *E); 8075 bool VisitUnaryPreInc(const UnaryOperator *UO) { 8076 return VisitUnaryPreIncDec(UO); 8077 } 8078 bool VisitUnaryPreDec(const UnaryOperator *UO) { 8079 return VisitUnaryPreIncDec(UO); 8080 } 8081 bool VisitBinAssign(const BinaryOperator *BO); 8082 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8083 8084 bool VisitCastExpr(const CastExpr *E) { 8085 switch (E->getCastKind()) { 8086 default: 8087 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8088 8089 case CK_LValueBitCast: 8090 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8091 if (!Visit(E->getSubExpr())) 8092 return false; 8093 Result.Designator.setInvalid(); 8094 return true; 8095 8096 case CK_BaseToDerived: 8097 if (!Visit(E->getSubExpr())) 8098 return false; 8099 return HandleBaseToDerivedCast(Info, E, Result); 8100 8101 case CK_Dynamic: 8102 if (!Visit(E->getSubExpr())) 8103 return false; 8104 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8105 } 8106 } 8107 }; 8108 } // end anonymous namespace 8109 8110 /// Evaluate an expression as an lvalue. This can be legitimately called on 8111 /// expressions which are not glvalues, in three cases: 8112 /// * function designators in C, and 8113 /// * "extern void" objects 8114 /// * @selector() expressions in Objective-C 8115 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8116 bool InvalidBaseOK) { 8117 assert(!E->isValueDependent()); 8118 assert(E->isGLValue() || E->getType()->isFunctionType() || 8119 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8120 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8121 } 8122 8123 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8124 const NamedDecl *D = E->getDecl(); 8125 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8126 return Success(cast<ValueDecl>(D)); 8127 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8128 return VisitVarDecl(E, VD); 8129 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8130 return Visit(BD->getBinding()); 8131 return Error(E); 8132 } 8133 8134 8135 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8136 8137 // If we are within a lambda's call operator, check whether the 'VD' referred 8138 // to within 'E' actually represents a lambda-capture that maps to a 8139 // data-member/field within the closure object, and if so, evaluate to the 8140 // field or what the field refers to. 8141 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8142 isa<DeclRefExpr>(E) && 8143 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8144 // We don't always have a complete capture-map when checking or inferring if 8145 // the function call operator meets the requirements of a constexpr function 8146 // - but we don't need to evaluate the captures to determine constexprness 8147 // (dcl.constexpr C++17). 8148 if (Info.checkingPotentialConstantExpression()) 8149 return false; 8150 8151 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8152 // Start with 'Result' referring to the complete closure object... 8153 Result = *Info.CurrentCall->This; 8154 // ... then update it to refer to the field of the closure object 8155 // that represents the capture. 8156 if (!HandleLValueMember(Info, E, Result, FD)) 8157 return false; 8158 // And if the field is of reference type, update 'Result' to refer to what 8159 // the field refers to. 8160 if (FD->getType()->isReferenceType()) { 8161 APValue RVal; 8162 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8163 RVal)) 8164 return false; 8165 Result.setFrom(Info.Ctx, RVal); 8166 } 8167 return true; 8168 } 8169 } 8170 8171 CallStackFrame *Frame = nullptr; 8172 unsigned Version = 0; 8173 if (VD->hasLocalStorage()) { 8174 // Only if a local variable was declared in the function currently being 8175 // evaluated, do we expect to be able to find its value in the current 8176 // frame. (Otherwise it was likely declared in an enclosing context and 8177 // could either have a valid evaluatable value (for e.g. a constexpr 8178 // variable) or be ill-formed (and trigger an appropriate evaluation 8179 // diagnostic)). 8180 CallStackFrame *CurrFrame = Info.CurrentCall; 8181 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8182 // Function parameters are stored in some caller's frame. (Usually the 8183 // immediate caller, but for an inherited constructor they may be more 8184 // distant.) 8185 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8186 if (CurrFrame->Arguments) { 8187 VD = CurrFrame->Arguments.getOrigParam(PVD); 8188 Frame = 8189 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8190 Version = CurrFrame->Arguments.Version; 8191 } 8192 } else { 8193 Frame = CurrFrame; 8194 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8195 } 8196 } 8197 } 8198 8199 if (!VD->getType()->isReferenceType()) { 8200 if (Frame) { 8201 Result.set({VD, Frame->Index, Version}); 8202 return true; 8203 } 8204 return Success(VD); 8205 } 8206 8207 if (!Info.getLangOpts().CPlusPlus11) { 8208 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8209 << VD << VD->getType(); 8210 Info.Note(VD->getLocation(), diag::note_declared_at); 8211 } 8212 8213 APValue *V; 8214 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8215 return false; 8216 if (!V->hasValue()) { 8217 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8218 // adjust the diagnostic to say that. 8219 if (!Info.checkingPotentialConstantExpression()) 8220 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8221 return false; 8222 } 8223 return Success(*V, E); 8224 } 8225 8226 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8227 const MaterializeTemporaryExpr *E) { 8228 // Walk through the expression to find the materialized temporary itself. 8229 SmallVector<const Expr *, 2> CommaLHSs; 8230 SmallVector<SubobjectAdjustment, 2> Adjustments; 8231 const Expr *Inner = 8232 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8233 8234 // If we passed any comma operators, evaluate their LHSs. 8235 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8236 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8237 return false; 8238 8239 // A materialized temporary with static storage duration can appear within the 8240 // result of a constant expression evaluation, so we need to preserve its 8241 // value for use outside this evaluation. 8242 APValue *Value; 8243 if (E->getStorageDuration() == SD_Static) { 8244 // FIXME: What about SD_Thread? 8245 Value = E->getOrCreateValue(true); 8246 *Value = APValue(); 8247 Result.set(E); 8248 } else { 8249 Value = &Info.CurrentCall->createTemporary( 8250 E, E->getType(), 8251 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8252 : ScopeKind::Block, 8253 Result); 8254 } 8255 8256 QualType Type = Inner->getType(); 8257 8258 // Materialize the temporary itself. 8259 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8260 *Value = APValue(); 8261 return false; 8262 } 8263 8264 // Adjust our lvalue to refer to the desired subobject. 8265 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8266 --I; 8267 switch (Adjustments[I].Kind) { 8268 case SubobjectAdjustment::DerivedToBaseAdjustment: 8269 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8270 Type, Result)) 8271 return false; 8272 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8273 break; 8274 8275 case SubobjectAdjustment::FieldAdjustment: 8276 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8277 return false; 8278 Type = Adjustments[I].Field->getType(); 8279 break; 8280 8281 case SubobjectAdjustment::MemberPointerAdjustment: 8282 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8283 Adjustments[I].Ptr.RHS)) 8284 return false; 8285 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8286 break; 8287 } 8288 } 8289 8290 return true; 8291 } 8292 8293 bool 8294 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8295 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8296 "lvalue compound literal in c++?"); 8297 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8298 // only see this when folding in C, so there's no standard to follow here. 8299 return Success(E); 8300 } 8301 8302 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8303 TypeInfoLValue TypeInfo; 8304 8305 if (!E->isPotentiallyEvaluated()) { 8306 if (E->isTypeOperand()) 8307 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8308 else 8309 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8310 } else { 8311 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8312 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8313 << E->getExprOperand()->getType() 8314 << E->getExprOperand()->getSourceRange(); 8315 } 8316 8317 if (!Visit(E->getExprOperand())) 8318 return false; 8319 8320 Optional<DynamicType> DynType = 8321 ComputeDynamicType(Info, E, Result, AK_TypeId); 8322 if (!DynType) 8323 return false; 8324 8325 TypeInfo = 8326 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8327 } 8328 8329 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8330 } 8331 8332 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8333 return Success(E->getGuidDecl()); 8334 } 8335 8336 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8337 // Handle static data members. 8338 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8339 VisitIgnoredBaseExpression(E->getBase()); 8340 return VisitVarDecl(E, VD); 8341 } 8342 8343 // Handle static member functions. 8344 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8345 if (MD->isStatic()) { 8346 VisitIgnoredBaseExpression(E->getBase()); 8347 return Success(MD); 8348 } 8349 } 8350 8351 // Handle non-static data members. 8352 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8353 } 8354 8355 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8356 // FIXME: Deal with vectors as array subscript bases. 8357 if (E->getBase()->getType()->isVectorType()) 8358 return Error(E); 8359 8360 APSInt Index; 8361 bool Success = true; 8362 8363 // C++17's rules require us to evaluate the LHS first, regardless of which 8364 // side is the base. 8365 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8366 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8367 : !EvaluateInteger(SubExpr, Index, Info)) { 8368 if (!Info.noteFailure()) 8369 return false; 8370 Success = false; 8371 } 8372 } 8373 8374 return Success && 8375 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8376 } 8377 8378 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8379 return evaluatePointer(E->getSubExpr(), Result); 8380 } 8381 8382 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8383 if (!Visit(E->getSubExpr())) 8384 return false; 8385 // __real is a no-op on scalar lvalues. 8386 if (E->getSubExpr()->getType()->isAnyComplexType()) 8387 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8388 return true; 8389 } 8390 8391 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8392 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8393 "lvalue __imag__ on scalar?"); 8394 if (!Visit(E->getSubExpr())) 8395 return false; 8396 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8397 return true; 8398 } 8399 8400 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8401 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8402 return Error(UO); 8403 8404 if (!this->Visit(UO->getSubExpr())) 8405 return false; 8406 8407 return handleIncDec( 8408 this->Info, UO, Result, UO->getSubExpr()->getType(), 8409 UO->isIncrementOp(), nullptr); 8410 } 8411 8412 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8413 const CompoundAssignOperator *CAO) { 8414 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8415 return Error(CAO); 8416 8417 bool Success = true; 8418 8419 // C++17 onwards require that we evaluate the RHS first. 8420 APValue RHS; 8421 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8422 if (!Info.noteFailure()) 8423 return false; 8424 Success = false; 8425 } 8426 8427 // The overall lvalue result is the result of evaluating the LHS. 8428 if (!this->Visit(CAO->getLHS()) || !Success) 8429 return false; 8430 8431 return handleCompoundAssignment( 8432 this->Info, CAO, 8433 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8434 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8435 } 8436 8437 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8438 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8439 return Error(E); 8440 8441 bool Success = true; 8442 8443 // C++17 onwards require that we evaluate the RHS first. 8444 APValue NewVal; 8445 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8446 if (!Info.noteFailure()) 8447 return false; 8448 Success = false; 8449 } 8450 8451 if (!this->Visit(E->getLHS()) || !Success) 8452 return false; 8453 8454 if (Info.getLangOpts().CPlusPlus20 && 8455 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8456 return false; 8457 8458 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8459 NewVal); 8460 } 8461 8462 //===----------------------------------------------------------------------===// 8463 // Pointer Evaluation 8464 //===----------------------------------------------------------------------===// 8465 8466 /// Attempts to compute the number of bytes available at the pointer 8467 /// returned by a function with the alloc_size attribute. Returns true if we 8468 /// were successful. Places an unsigned number into `Result`. 8469 /// 8470 /// This expects the given CallExpr to be a call to a function with an 8471 /// alloc_size attribute. 8472 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8473 const CallExpr *Call, 8474 llvm::APInt &Result) { 8475 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8476 8477 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8478 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8479 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8480 if (Call->getNumArgs() <= SizeArgNo) 8481 return false; 8482 8483 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8484 Expr::EvalResult ExprResult; 8485 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8486 return false; 8487 Into = ExprResult.Val.getInt(); 8488 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8489 return false; 8490 Into = Into.zextOrSelf(BitsInSizeT); 8491 return true; 8492 }; 8493 8494 APSInt SizeOfElem; 8495 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8496 return false; 8497 8498 if (!AllocSize->getNumElemsParam().isValid()) { 8499 Result = std::move(SizeOfElem); 8500 return true; 8501 } 8502 8503 APSInt NumberOfElems; 8504 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8505 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8506 return false; 8507 8508 bool Overflow; 8509 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8510 if (Overflow) 8511 return false; 8512 8513 Result = std::move(BytesAvailable); 8514 return true; 8515 } 8516 8517 /// Convenience function. LVal's base must be a call to an alloc_size 8518 /// function. 8519 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8520 const LValue &LVal, 8521 llvm::APInt &Result) { 8522 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8523 "Can't get the size of a non alloc_size function"); 8524 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8525 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8526 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8527 } 8528 8529 /// Attempts to evaluate the given LValueBase as the result of a call to 8530 /// a function with the alloc_size attribute. If it was possible to do so, this 8531 /// function will return true, make Result's Base point to said function call, 8532 /// and mark Result's Base as invalid. 8533 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8534 LValue &Result) { 8535 if (Base.isNull()) 8536 return false; 8537 8538 // Because we do no form of static analysis, we only support const variables. 8539 // 8540 // Additionally, we can't support parameters, nor can we support static 8541 // variables (in the latter case, use-before-assign isn't UB; in the former, 8542 // we have no clue what they'll be assigned to). 8543 const auto *VD = 8544 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8545 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8546 return false; 8547 8548 const Expr *Init = VD->getAnyInitializer(); 8549 if (!Init) 8550 return false; 8551 8552 const Expr *E = Init->IgnoreParens(); 8553 if (!tryUnwrapAllocSizeCall(E)) 8554 return false; 8555 8556 // Store E instead of E unwrapped so that the type of the LValue's base is 8557 // what the user wanted. 8558 Result.setInvalid(E); 8559 8560 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8561 Result.addUnsizedArray(Info, E, Pointee); 8562 return true; 8563 } 8564 8565 namespace { 8566 class PointerExprEvaluator 8567 : public ExprEvaluatorBase<PointerExprEvaluator> { 8568 LValue &Result; 8569 bool InvalidBaseOK; 8570 8571 bool Success(const Expr *E) { 8572 Result.set(E); 8573 return true; 8574 } 8575 8576 bool evaluateLValue(const Expr *E, LValue &Result) { 8577 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8578 } 8579 8580 bool evaluatePointer(const Expr *E, LValue &Result) { 8581 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8582 } 8583 8584 bool visitNonBuiltinCallExpr(const CallExpr *E); 8585 public: 8586 8587 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8588 : ExprEvaluatorBaseTy(info), Result(Result), 8589 InvalidBaseOK(InvalidBaseOK) {} 8590 8591 bool Success(const APValue &V, const Expr *E) { 8592 Result.setFrom(Info.Ctx, V); 8593 return true; 8594 } 8595 bool ZeroInitialization(const Expr *E) { 8596 Result.setNull(Info.Ctx, E->getType()); 8597 return true; 8598 } 8599 8600 bool VisitBinaryOperator(const BinaryOperator *E); 8601 bool VisitCastExpr(const CastExpr* E); 8602 bool VisitUnaryAddrOf(const UnaryOperator *E); 8603 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8604 { return Success(E); } 8605 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8606 if (E->isExpressibleAsConstantInitializer()) 8607 return Success(E); 8608 if (Info.noteFailure()) 8609 EvaluateIgnoredValue(Info, E->getSubExpr()); 8610 return Error(E); 8611 } 8612 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8613 { return Success(E); } 8614 bool VisitCallExpr(const CallExpr *E); 8615 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8616 bool VisitBlockExpr(const BlockExpr *E) { 8617 if (!E->getBlockDecl()->hasCaptures()) 8618 return Success(E); 8619 return Error(E); 8620 } 8621 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8622 // Can't look at 'this' when checking a potential constant expression. 8623 if (Info.checkingPotentialConstantExpression()) 8624 return false; 8625 if (!Info.CurrentCall->This) { 8626 if (Info.getLangOpts().CPlusPlus11) 8627 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8628 else 8629 Info.FFDiag(E); 8630 return false; 8631 } 8632 Result = *Info.CurrentCall->This; 8633 // If we are inside a lambda's call operator, the 'this' expression refers 8634 // to the enclosing '*this' object (either by value or reference) which is 8635 // either copied into the closure object's field that represents the '*this' 8636 // or refers to '*this'. 8637 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8638 // Ensure we actually have captured 'this'. (an error will have 8639 // been previously reported if not). 8640 if (!Info.CurrentCall->LambdaThisCaptureField) 8641 return false; 8642 8643 // Update 'Result' to refer to the data member/field of the closure object 8644 // that represents the '*this' capture. 8645 if (!HandleLValueMember(Info, E, Result, 8646 Info.CurrentCall->LambdaThisCaptureField)) 8647 return false; 8648 // If we captured '*this' by reference, replace the field with its referent. 8649 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8650 ->isPointerType()) { 8651 APValue RVal; 8652 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8653 RVal)) 8654 return false; 8655 8656 Result.setFrom(Info.Ctx, RVal); 8657 } 8658 } 8659 return true; 8660 } 8661 8662 bool VisitCXXNewExpr(const CXXNewExpr *E); 8663 8664 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8665 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8666 APValue LValResult = E->EvaluateInContext( 8667 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8668 Result.setFrom(Info.Ctx, LValResult); 8669 return true; 8670 } 8671 8672 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { 8673 std::string ResultStr = E->ComputeName(Info.Ctx); 8674 8675 Info.Ctx.SYCLUniqueStableNameEvaluatedValues[E] = ResultStr; 8676 8677 QualType CharTy = Info.Ctx.CharTy.withConst(); 8678 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), 8679 ResultStr.size() + 1); 8680 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, 8681 ArrayType::Normal, 0); 8682 8683 StringLiteral *SL = 8684 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, 8685 /*Pascal*/ false, ArrayTy, E->getLocation()); 8686 8687 evaluateLValue(SL, Result); 8688 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); 8689 return true; 8690 } 8691 8692 // FIXME: Missing: @protocol, @selector 8693 }; 8694 } // end anonymous namespace 8695 8696 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8697 bool InvalidBaseOK) { 8698 assert(!E->isValueDependent()); 8699 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8700 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8701 } 8702 8703 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8704 if (E->getOpcode() != BO_Add && 8705 E->getOpcode() != BO_Sub) 8706 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8707 8708 const Expr *PExp = E->getLHS(); 8709 const Expr *IExp = E->getRHS(); 8710 if (IExp->getType()->isPointerType()) 8711 std::swap(PExp, IExp); 8712 8713 bool EvalPtrOK = evaluatePointer(PExp, Result); 8714 if (!EvalPtrOK && !Info.noteFailure()) 8715 return false; 8716 8717 llvm::APSInt Offset; 8718 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8719 return false; 8720 8721 if (E->getOpcode() == BO_Sub) 8722 negateAsSigned(Offset); 8723 8724 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8725 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8726 } 8727 8728 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8729 return evaluateLValue(E->getSubExpr(), Result); 8730 } 8731 8732 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8733 const Expr *SubExpr = E->getSubExpr(); 8734 8735 switch (E->getCastKind()) { 8736 default: 8737 break; 8738 case CK_BitCast: 8739 case CK_CPointerToObjCPointerCast: 8740 case CK_BlockPointerToObjCPointerCast: 8741 case CK_AnyPointerToBlockPointerCast: 8742 case CK_AddressSpaceConversion: 8743 if (!Visit(SubExpr)) 8744 return false; 8745 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8746 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8747 // also static_casts, but we disallow them as a resolution to DR1312. 8748 if (!E->getType()->isVoidPointerType()) { 8749 if (!Result.InvalidBase && !Result.Designator.Invalid && 8750 !Result.IsNullPtr && 8751 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8752 E->getType()->getPointeeType()) && 8753 Info.getStdAllocatorCaller("allocate")) { 8754 // Inside a call to std::allocator::allocate and friends, we permit 8755 // casting from void* back to cv1 T* for a pointer that points to a 8756 // cv2 T. 8757 } else { 8758 Result.Designator.setInvalid(); 8759 if (SubExpr->getType()->isVoidPointerType()) 8760 CCEDiag(E, diag::note_constexpr_invalid_cast) 8761 << 3 << SubExpr->getType(); 8762 else 8763 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8764 } 8765 } 8766 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8767 ZeroInitialization(E); 8768 return true; 8769 8770 case CK_DerivedToBase: 8771 case CK_UncheckedDerivedToBase: 8772 if (!evaluatePointer(E->getSubExpr(), Result)) 8773 return false; 8774 if (!Result.Base && Result.Offset.isZero()) 8775 return true; 8776 8777 // Now figure out the necessary offset to add to the base LV to get from 8778 // the derived class to the base class. 8779 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8780 castAs<PointerType>()->getPointeeType(), 8781 Result); 8782 8783 case CK_BaseToDerived: 8784 if (!Visit(E->getSubExpr())) 8785 return false; 8786 if (!Result.Base && Result.Offset.isZero()) 8787 return true; 8788 return HandleBaseToDerivedCast(Info, E, Result); 8789 8790 case CK_Dynamic: 8791 if (!Visit(E->getSubExpr())) 8792 return false; 8793 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8794 8795 case CK_NullToPointer: 8796 VisitIgnoredValue(E->getSubExpr()); 8797 return ZeroInitialization(E); 8798 8799 case CK_IntegralToPointer: { 8800 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8801 8802 APValue Value; 8803 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8804 break; 8805 8806 if (Value.isInt()) { 8807 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8808 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8809 Result.Base = (Expr*)nullptr; 8810 Result.InvalidBase = false; 8811 Result.Offset = CharUnits::fromQuantity(N); 8812 Result.Designator.setInvalid(); 8813 Result.IsNullPtr = false; 8814 return true; 8815 } else { 8816 // Cast is of an lvalue, no need to change value. 8817 Result.setFrom(Info.Ctx, Value); 8818 return true; 8819 } 8820 } 8821 8822 case CK_ArrayToPointerDecay: { 8823 if (SubExpr->isGLValue()) { 8824 if (!evaluateLValue(SubExpr, Result)) 8825 return false; 8826 } else { 8827 APValue &Value = Info.CurrentCall->createTemporary( 8828 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8829 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8830 return false; 8831 } 8832 // The result is a pointer to the first element of the array. 8833 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8834 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8835 Result.addArray(Info, E, CAT); 8836 else 8837 Result.addUnsizedArray(Info, E, AT->getElementType()); 8838 return true; 8839 } 8840 8841 case CK_FunctionToPointerDecay: 8842 return evaluateLValue(SubExpr, Result); 8843 8844 case CK_LValueToRValue: { 8845 LValue LVal; 8846 if (!evaluateLValue(E->getSubExpr(), LVal)) 8847 return false; 8848 8849 APValue RVal; 8850 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8851 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8852 LVal, RVal)) 8853 return InvalidBaseOK && 8854 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8855 return Success(RVal, E); 8856 } 8857 } 8858 8859 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8860 } 8861 8862 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8863 UnaryExprOrTypeTrait ExprKind) { 8864 // C++ [expr.alignof]p3: 8865 // When alignof is applied to a reference type, the result is the 8866 // alignment of the referenced type. 8867 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8868 T = Ref->getPointeeType(); 8869 8870 if (T.getQualifiers().hasUnaligned()) 8871 return CharUnits::One(); 8872 8873 const bool AlignOfReturnsPreferred = 8874 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8875 8876 // __alignof is defined to return the preferred alignment. 8877 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8878 // as well. 8879 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8880 return Info.Ctx.toCharUnitsFromBits( 8881 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8882 // alignof and _Alignof are defined to return the ABI alignment. 8883 else if (ExprKind == UETT_AlignOf) 8884 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8885 else 8886 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8887 } 8888 8889 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8890 UnaryExprOrTypeTrait ExprKind) { 8891 E = E->IgnoreParens(); 8892 8893 // The kinds of expressions that we have special-case logic here for 8894 // should be kept up to date with the special checks for those 8895 // expressions in Sema. 8896 8897 // alignof decl is always accepted, even if it doesn't make sense: we default 8898 // to 1 in those cases. 8899 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8900 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8901 /*RefAsPointee*/true); 8902 8903 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8904 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8905 /*RefAsPointee*/true); 8906 8907 return GetAlignOfType(Info, E->getType(), ExprKind); 8908 } 8909 8910 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8911 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8912 return Info.Ctx.getDeclAlign(VD); 8913 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8914 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8915 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8916 } 8917 8918 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8919 /// __builtin_is_aligned and __builtin_assume_aligned. 8920 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8921 EvalInfo &Info, APSInt &Alignment) { 8922 if (!EvaluateInteger(E, Alignment, Info)) 8923 return false; 8924 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8925 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8926 return false; 8927 } 8928 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8929 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8930 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8931 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8932 << MaxValue << ForType << Alignment; 8933 return false; 8934 } 8935 // Ensure both alignment and source value have the same bit width so that we 8936 // don't assert when computing the resulting value. 8937 APSInt ExtAlignment = 8938 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8939 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8940 "Alignment should not be changed by ext/trunc"); 8941 Alignment = ExtAlignment; 8942 assert(Alignment.getBitWidth() == SrcWidth); 8943 return true; 8944 } 8945 8946 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8947 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8948 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8949 return true; 8950 8951 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8952 return false; 8953 8954 Result.setInvalid(E); 8955 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8956 Result.addUnsizedArray(Info, E, PointeeTy); 8957 return true; 8958 } 8959 8960 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8961 if (IsStringLiteralCall(E)) 8962 return Success(E); 8963 8964 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8965 return VisitBuiltinCallExpr(E, BuiltinOp); 8966 8967 return visitNonBuiltinCallExpr(E); 8968 } 8969 8970 // Determine if T is a character type for which we guarantee that 8971 // sizeof(T) == 1. 8972 static bool isOneByteCharacterType(QualType T) { 8973 return T->isCharType() || T->isChar8Type(); 8974 } 8975 8976 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8977 unsigned BuiltinOp) { 8978 switch (BuiltinOp) { 8979 case Builtin::BI__builtin_addressof: 8980 return evaluateLValue(E->getArg(0), Result); 8981 case Builtin::BI__builtin_assume_aligned: { 8982 // We need to be very careful here because: if the pointer does not have the 8983 // asserted alignment, then the behavior is undefined, and undefined 8984 // behavior is non-constant. 8985 if (!evaluatePointer(E->getArg(0), Result)) 8986 return false; 8987 8988 LValue OffsetResult(Result); 8989 APSInt Alignment; 8990 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8991 Alignment)) 8992 return false; 8993 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8994 8995 if (E->getNumArgs() > 2) { 8996 APSInt Offset; 8997 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8998 return false; 8999 9000 int64_t AdditionalOffset = -Offset.getZExtValue(); 9001 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 9002 } 9003 9004 // If there is a base object, then it must have the correct alignment. 9005 if (OffsetResult.Base) { 9006 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 9007 9008 if (BaseAlignment < Align) { 9009 Result.Designator.setInvalid(); 9010 // FIXME: Add support to Diagnostic for long / long long. 9011 CCEDiag(E->getArg(0), 9012 diag::note_constexpr_baa_insufficient_alignment) << 0 9013 << (unsigned)BaseAlignment.getQuantity() 9014 << (unsigned)Align.getQuantity(); 9015 return false; 9016 } 9017 } 9018 9019 // The offset must also have the correct alignment. 9020 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9021 Result.Designator.setInvalid(); 9022 9023 (OffsetResult.Base 9024 ? CCEDiag(E->getArg(0), 9025 diag::note_constexpr_baa_insufficient_alignment) << 1 9026 : CCEDiag(E->getArg(0), 9027 diag::note_constexpr_baa_value_insufficient_alignment)) 9028 << (int)OffsetResult.Offset.getQuantity() 9029 << (unsigned)Align.getQuantity(); 9030 return false; 9031 } 9032 9033 return true; 9034 } 9035 case Builtin::BI__builtin_align_up: 9036 case Builtin::BI__builtin_align_down: { 9037 if (!evaluatePointer(E->getArg(0), Result)) 9038 return false; 9039 APSInt Alignment; 9040 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9041 Alignment)) 9042 return false; 9043 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9044 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9045 // For align_up/align_down, we can return the same value if the alignment 9046 // is known to be greater or equal to the requested value. 9047 if (PtrAlign.getQuantity() >= Alignment) 9048 return true; 9049 9050 // The alignment could be greater than the minimum at run-time, so we cannot 9051 // infer much about the resulting pointer value. One case is possible: 9052 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9053 // can infer the correct index if the requested alignment is smaller than 9054 // the base alignment so we can perform the computation on the offset. 9055 if (BaseAlignment.getQuantity() >= Alignment) { 9056 assert(Alignment.getBitWidth() <= 64 && 9057 "Cannot handle > 64-bit address-space"); 9058 uint64_t Alignment64 = Alignment.getZExtValue(); 9059 CharUnits NewOffset = CharUnits::fromQuantity( 9060 BuiltinOp == Builtin::BI__builtin_align_down 9061 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9062 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9063 Result.adjustOffset(NewOffset - Result.Offset); 9064 // TODO: diagnose out-of-bounds values/only allow for arrays? 9065 return true; 9066 } 9067 // Otherwise, we cannot constant-evaluate the result. 9068 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9069 << Alignment; 9070 return false; 9071 } 9072 case Builtin::BI__builtin_operator_new: 9073 return HandleOperatorNewCall(Info, E, Result); 9074 case Builtin::BI__builtin_launder: 9075 return evaluatePointer(E->getArg(0), Result); 9076 case Builtin::BIstrchr: 9077 case Builtin::BIwcschr: 9078 case Builtin::BImemchr: 9079 case Builtin::BIwmemchr: 9080 if (Info.getLangOpts().CPlusPlus11) 9081 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9082 << /*isConstexpr*/0 << /*isConstructor*/0 9083 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9084 else 9085 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9086 LLVM_FALLTHROUGH; 9087 case Builtin::BI__builtin_strchr: 9088 case Builtin::BI__builtin_wcschr: 9089 case Builtin::BI__builtin_memchr: 9090 case Builtin::BI__builtin_char_memchr: 9091 case Builtin::BI__builtin_wmemchr: { 9092 if (!Visit(E->getArg(0))) 9093 return false; 9094 APSInt Desired; 9095 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9096 return false; 9097 uint64_t MaxLength = uint64_t(-1); 9098 if (BuiltinOp != Builtin::BIstrchr && 9099 BuiltinOp != Builtin::BIwcschr && 9100 BuiltinOp != Builtin::BI__builtin_strchr && 9101 BuiltinOp != Builtin::BI__builtin_wcschr) { 9102 APSInt N; 9103 if (!EvaluateInteger(E->getArg(2), N, Info)) 9104 return false; 9105 MaxLength = N.getExtValue(); 9106 } 9107 // We cannot find the value if there are no candidates to match against. 9108 if (MaxLength == 0u) 9109 return ZeroInitialization(E); 9110 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9111 Result.Designator.Invalid) 9112 return false; 9113 QualType CharTy = Result.Designator.getType(Info.Ctx); 9114 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9115 BuiltinOp == Builtin::BI__builtin_memchr; 9116 assert(IsRawByte || 9117 Info.Ctx.hasSameUnqualifiedType( 9118 CharTy, E->getArg(0)->getType()->getPointeeType())); 9119 // Pointers to const void may point to objects of incomplete type. 9120 if (IsRawByte && CharTy->isIncompleteType()) { 9121 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9122 return false; 9123 } 9124 // Give up on byte-oriented matching against multibyte elements. 9125 // FIXME: We can compare the bytes in the correct order. 9126 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9127 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9128 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9129 << CharTy; 9130 return false; 9131 } 9132 // Figure out what value we're actually looking for (after converting to 9133 // the corresponding unsigned type if necessary). 9134 uint64_t DesiredVal; 9135 bool StopAtNull = false; 9136 switch (BuiltinOp) { 9137 case Builtin::BIstrchr: 9138 case Builtin::BI__builtin_strchr: 9139 // strchr compares directly to the passed integer, and therefore 9140 // always fails if given an int that is not a char. 9141 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9142 E->getArg(1)->getType(), 9143 Desired), 9144 Desired)) 9145 return ZeroInitialization(E); 9146 StopAtNull = true; 9147 LLVM_FALLTHROUGH; 9148 case Builtin::BImemchr: 9149 case Builtin::BI__builtin_memchr: 9150 case Builtin::BI__builtin_char_memchr: 9151 // memchr compares by converting both sides to unsigned char. That's also 9152 // correct for strchr if we get this far (to cope with plain char being 9153 // unsigned in the strchr case). 9154 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9155 break; 9156 9157 case Builtin::BIwcschr: 9158 case Builtin::BI__builtin_wcschr: 9159 StopAtNull = true; 9160 LLVM_FALLTHROUGH; 9161 case Builtin::BIwmemchr: 9162 case Builtin::BI__builtin_wmemchr: 9163 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9164 DesiredVal = Desired.getZExtValue(); 9165 break; 9166 } 9167 9168 for (; MaxLength; --MaxLength) { 9169 APValue Char; 9170 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9171 !Char.isInt()) 9172 return false; 9173 if (Char.getInt().getZExtValue() == DesiredVal) 9174 return true; 9175 if (StopAtNull && !Char.getInt()) 9176 break; 9177 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9178 return false; 9179 } 9180 // Not found: return nullptr. 9181 return ZeroInitialization(E); 9182 } 9183 9184 case Builtin::BImemcpy: 9185 case Builtin::BImemmove: 9186 case Builtin::BIwmemcpy: 9187 case Builtin::BIwmemmove: 9188 if (Info.getLangOpts().CPlusPlus11) 9189 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9190 << /*isConstexpr*/0 << /*isConstructor*/0 9191 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9192 else 9193 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9194 LLVM_FALLTHROUGH; 9195 case Builtin::BI__builtin_memcpy: 9196 case Builtin::BI__builtin_memmove: 9197 case Builtin::BI__builtin_wmemcpy: 9198 case Builtin::BI__builtin_wmemmove: { 9199 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9200 BuiltinOp == Builtin::BIwmemmove || 9201 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9202 BuiltinOp == Builtin::BI__builtin_wmemmove; 9203 bool Move = BuiltinOp == Builtin::BImemmove || 9204 BuiltinOp == Builtin::BIwmemmove || 9205 BuiltinOp == Builtin::BI__builtin_memmove || 9206 BuiltinOp == Builtin::BI__builtin_wmemmove; 9207 9208 // The result of mem* is the first argument. 9209 if (!Visit(E->getArg(0))) 9210 return false; 9211 LValue Dest = Result; 9212 9213 LValue Src; 9214 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9215 return false; 9216 9217 APSInt N; 9218 if (!EvaluateInteger(E->getArg(2), N, Info)) 9219 return false; 9220 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9221 9222 // If the size is zero, we treat this as always being a valid no-op. 9223 // (Even if one of the src and dest pointers is null.) 9224 if (!N) 9225 return true; 9226 9227 // Otherwise, if either of the operands is null, we can't proceed. Don't 9228 // try to determine the type of the copied objects, because there aren't 9229 // any. 9230 if (!Src.Base || !Dest.Base) { 9231 APValue Val; 9232 (!Src.Base ? Src : Dest).moveInto(Val); 9233 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9234 << Move << WChar << !!Src.Base 9235 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9236 return false; 9237 } 9238 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9239 return false; 9240 9241 // We require that Src and Dest are both pointers to arrays of 9242 // trivially-copyable type. (For the wide version, the designator will be 9243 // invalid if the designated object is not a wchar_t.) 9244 QualType T = Dest.Designator.getType(Info.Ctx); 9245 QualType SrcT = Src.Designator.getType(Info.Ctx); 9246 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9247 // FIXME: Consider using our bit_cast implementation to support this. 9248 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9249 return false; 9250 } 9251 if (T->isIncompleteType()) { 9252 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9253 return false; 9254 } 9255 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9256 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9257 return false; 9258 } 9259 9260 // Figure out how many T's we're copying. 9261 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9262 if (!WChar) { 9263 uint64_t Remainder; 9264 llvm::APInt OrigN = N; 9265 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9266 if (Remainder) { 9267 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9268 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9269 << (unsigned)TSize; 9270 return false; 9271 } 9272 } 9273 9274 // Check that the copying will remain within the arrays, just so that we 9275 // can give a more meaningful diagnostic. This implicitly also checks that 9276 // N fits into 64 bits. 9277 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9278 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9279 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9280 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9281 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9282 << N.toString(10, /*Signed*/false); 9283 return false; 9284 } 9285 uint64_t NElems = N.getZExtValue(); 9286 uint64_t NBytes = NElems * TSize; 9287 9288 // Check for overlap. 9289 int Direction = 1; 9290 if (HasSameBase(Src, Dest)) { 9291 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9292 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9293 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9294 // Dest is inside the source region. 9295 if (!Move) { 9296 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9297 return false; 9298 } 9299 // For memmove and friends, copy backwards. 9300 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9301 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9302 return false; 9303 Direction = -1; 9304 } else if (!Move && SrcOffset >= DestOffset && 9305 SrcOffset - DestOffset < NBytes) { 9306 // Src is inside the destination region for memcpy: invalid. 9307 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9308 return false; 9309 } 9310 } 9311 9312 while (true) { 9313 APValue Val; 9314 // FIXME: Set WantObjectRepresentation to true if we're copying a 9315 // char-like type? 9316 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9317 !handleAssignment(Info, E, Dest, T, Val)) 9318 return false; 9319 // Do not iterate past the last element; if we're copying backwards, that 9320 // might take us off the start of the array. 9321 if (--NElems == 0) 9322 return true; 9323 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9324 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9325 return false; 9326 } 9327 } 9328 9329 default: 9330 break; 9331 } 9332 9333 return visitNonBuiltinCallExpr(E); 9334 } 9335 9336 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9337 APValue &Result, const InitListExpr *ILE, 9338 QualType AllocType); 9339 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9340 APValue &Result, 9341 const CXXConstructExpr *CCE, 9342 QualType AllocType); 9343 9344 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9345 if (!Info.getLangOpts().CPlusPlus20) 9346 Info.CCEDiag(E, diag::note_constexpr_new); 9347 9348 // We cannot speculatively evaluate a delete expression. 9349 if (Info.SpeculativeEvaluationDepth) 9350 return false; 9351 9352 FunctionDecl *OperatorNew = E->getOperatorNew(); 9353 9354 bool IsNothrow = false; 9355 bool IsPlacement = false; 9356 if (OperatorNew->isReservedGlobalPlacementOperator() && 9357 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9358 // FIXME Support array placement new. 9359 assert(E->getNumPlacementArgs() == 1); 9360 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9361 return false; 9362 if (Result.Designator.Invalid) 9363 return false; 9364 IsPlacement = true; 9365 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9366 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9367 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9368 return false; 9369 } else if (E->getNumPlacementArgs()) { 9370 // The only new-placement list we support is of the form (std::nothrow). 9371 // 9372 // FIXME: There is no restriction on this, but it's not clear that any 9373 // other form makes any sense. We get here for cases such as: 9374 // 9375 // new (std::align_val_t{N}) X(int) 9376 // 9377 // (which should presumably be valid only if N is a multiple of 9378 // alignof(int), and in any case can't be deallocated unless N is 9379 // alignof(X) and X has new-extended alignment). 9380 if (E->getNumPlacementArgs() != 1 || 9381 !E->getPlacementArg(0)->getType()->isNothrowT()) 9382 return Error(E, diag::note_constexpr_new_placement); 9383 9384 LValue Nothrow; 9385 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9386 return false; 9387 IsNothrow = true; 9388 } 9389 9390 const Expr *Init = E->getInitializer(); 9391 const InitListExpr *ResizedArrayILE = nullptr; 9392 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9393 bool ValueInit = false; 9394 9395 QualType AllocType = E->getAllocatedType(); 9396 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9397 const Expr *Stripped = *ArraySize; 9398 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9399 Stripped = ICE->getSubExpr()) 9400 if (ICE->getCastKind() != CK_NoOp && 9401 ICE->getCastKind() != CK_IntegralCast) 9402 break; 9403 9404 llvm::APSInt ArrayBound; 9405 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9406 return false; 9407 9408 // C++ [expr.new]p9: 9409 // The expression is erroneous if: 9410 // -- [...] its value before converting to size_t [or] applying the 9411 // second standard conversion sequence is less than zero 9412 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9413 if (IsNothrow) 9414 return ZeroInitialization(E); 9415 9416 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9417 << ArrayBound << (*ArraySize)->getSourceRange(); 9418 return false; 9419 } 9420 9421 // -- its value is such that the size of the allocated object would 9422 // exceed the implementation-defined limit 9423 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9424 ArrayBound) > 9425 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9426 if (IsNothrow) 9427 return ZeroInitialization(E); 9428 9429 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9430 << ArrayBound << (*ArraySize)->getSourceRange(); 9431 return false; 9432 } 9433 9434 // -- the new-initializer is a braced-init-list and the number of 9435 // array elements for which initializers are provided [...] 9436 // exceeds the number of elements to initialize 9437 if (!Init) { 9438 // No initialization is performed. 9439 } else if (isa<CXXScalarValueInitExpr>(Init) || 9440 isa<ImplicitValueInitExpr>(Init)) { 9441 ValueInit = true; 9442 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9443 ResizedArrayCCE = CCE; 9444 } else { 9445 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9446 assert(CAT && "unexpected type for array initializer"); 9447 9448 unsigned Bits = 9449 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9450 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9451 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9452 if (InitBound.ugt(AllocBound)) { 9453 if (IsNothrow) 9454 return ZeroInitialization(E); 9455 9456 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9457 << AllocBound.toString(10, /*Signed=*/false) 9458 << InitBound.toString(10, /*Signed=*/false) 9459 << (*ArraySize)->getSourceRange(); 9460 return false; 9461 } 9462 9463 // If the sizes differ, we must have an initializer list, and we need 9464 // special handling for this case when we initialize. 9465 if (InitBound != AllocBound) 9466 ResizedArrayILE = cast<InitListExpr>(Init); 9467 } 9468 9469 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9470 ArrayType::Normal, 0); 9471 } else { 9472 assert(!AllocType->isArrayType() && 9473 "array allocation with non-array new"); 9474 } 9475 9476 APValue *Val; 9477 if (IsPlacement) { 9478 AccessKinds AK = AK_Construct; 9479 struct FindObjectHandler { 9480 EvalInfo &Info; 9481 const Expr *E; 9482 QualType AllocType; 9483 const AccessKinds AccessKind; 9484 APValue *Value; 9485 9486 typedef bool result_type; 9487 bool failed() { return false; } 9488 bool found(APValue &Subobj, QualType SubobjType) { 9489 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9490 // old name of the object to be used to name the new object. 9491 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9492 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9493 SubobjType << AllocType; 9494 return false; 9495 } 9496 Value = &Subobj; 9497 return true; 9498 } 9499 bool found(APSInt &Value, QualType SubobjType) { 9500 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9501 return false; 9502 } 9503 bool found(APFloat &Value, QualType SubobjType) { 9504 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9505 return false; 9506 } 9507 } Handler = {Info, E, AllocType, AK, nullptr}; 9508 9509 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9510 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9511 return false; 9512 9513 Val = Handler.Value; 9514 9515 // [basic.life]p1: 9516 // The lifetime of an object o of type T ends when [...] the storage 9517 // which the object occupies is [...] reused by an object that is not 9518 // nested within o (6.6.2). 9519 *Val = APValue(); 9520 } else { 9521 // Perform the allocation and obtain a pointer to the resulting object. 9522 Val = Info.createHeapAlloc(E, AllocType, Result); 9523 if (!Val) 9524 return false; 9525 } 9526 9527 if (ValueInit) { 9528 ImplicitValueInitExpr VIE(AllocType); 9529 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9530 return false; 9531 } else if (ResizedArrayILE) { 9532 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9533 AllocType)) 9534 return false; 9535 } else if (ResizedArrayCCE) { 9536 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9537 AllocType)) 9538 return false; 9539 } else if (Init) { 9540 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9541 return false; 9542 } else if (!getDefaultInitValue(AllocType, *Val)) { 9543 return false; 9544 } 9545 9546 // Array new returns a pointer to the first element, not a pointer to the 9547 // array. 9548 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9549 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9550 9551 return true; 9552 } 9553 //===----------------------------------------------------------------------===// 9554 // Member Pointer Evaluation 9555 //===----------------------------------------------------------------------===// 9556 9557 namespace { 9558 class MemberPointerExprEvaluator 9559 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9560 MemberPtr &Result; 9561 9562 bool Success(const ValueDecl *D) { 9563 Result = MemberPtr(D); 9564 return true; 9565 } 9566 public: 9567 9568 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9569 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9570 9571 bool Success(const APValue &V, const Expr *E) { 9572 Result.setFrom(V); 9573 return true; 9574 } 9575 bool ZeroInitialization(const Expr *E) { 9576 return Success((const ValueDecl*)nullptr); 9577 } 9578 9579 bool VisitCastExpr(const CastExpr *E); 9580 bool VisitUnaryAddrOf(const UnaryOperator *E); 9581 }; 9582 } // end anonymous namespace 9583 9584 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9585 EvalInfo &Info) { 9586 assert(!E->isValueDependent()); 9587 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9588 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9589 } 9590 9591 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9592 switch (E->getCastKind()) { 9593 default: 9594 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9595 9596 case CK_NullToMemberPointer: 9597 VisitIgnoredValue(E->getSubExpr()); 9598 return ZeroInitialization(E); 9599 9600 case CK_BaseToDerivedMemberPointer: { 9601 if (!Visit(E->getSubExpr())) 9602 return false; 9603 if (E->path_empty()) 9604 return true; 9605 // Base-to-derived member pointer casts store the path in derived-to-base 9606 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9607 // the wrong end of the derived->base arc, so stagger the path by one class. 9608 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9609 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9610 PathI != PathE; ++PathI) { 9611 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9612 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9613 if (!Result.castToDerived(Derived)) 9614 return Error(E); 9615 } 9616 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9617 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9618 return Error(E); 9619 return true; 9620 } 9621 9622 case CK_DerivedToBaseMemberPointer: 9623 if (!Visit(E->getSubExpr())) 9624 return false; 9625 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9626 PathE = E->path_end(); PathI != PathE; ++PathI) { 9627 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9628 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9629 if (!Result.castToBase(Base)) 9630 return Error(E); 9631 } 9632 return true; 9633 } 9634 } 9635 9636 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9637 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9638 // member can be formed. 9639 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9640 } 9641 9642 //===----------------------------------------------------------------------===// 9643 // Record Evaluation 9644 //===----------------------------------------------------------------------===// 9645 9646 namespace { 9647 class RecordExprEvaluator 9648 : public ExprEvaluatorBase<RecordExprEvaluator> { 9649 const LValue &This; 9650 APValue &Result; 9651 public: 9652 9653 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9654 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9655 9656 bool Success(const APValue &V, const Expr *E) { 9657 Result = V; 9658 return true; 9659 } 9660 bool ZeroInitialization(const Expr *E) { 9661 return ZeroInitialization(E, E->getType()); 9662 } 9663 bool ZeroInitialization(const Expr *E, QualType T); 9664 9665 bool VisitCallExpr(const CallExpr *E) { 9666 return handleCallExpr(E, Result, &This); 9667 } 9668 bool VisitCastExpr(const CastExpr *E); 9669 bool VisitInitListExpr(const InitListExpr *E); 9670 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9671 return VisitCXXConstructExpr(E, E->getType()); 9672 } 9673 bool VisitLambdaExpr(const LambdaExpr *E); 9674 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9675 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9676 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9677 bool VisitBinCmp(const BinaryOperator *E); 9678 }; 9679 } 9680 9681 /// Perform zero-initialization on an object of non-union class type. 9682 /// C++11 [dcl.init]p5: 9683 /// To zero-initialize an object or reference of type T means: 9684 /// [...] 9685 /// -- if T is a (possibly cv-qualified) non-union class type, 9686 /// each non-static data member and each base-class subobject is 9687 /// zero-initialized 9688 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9689 const RecordDecl *RD, 9690 const LValue &This, APValue &Result) { 9691 assert(!RD->isUnion() && "Expected non-union class type"); 9692 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9693 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9694 std::distance(RD->field_begin(), RD->field_end())); 9695 9696 if (RD->isInvalidDecl()) return false; 9697 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9698 9699 if (CD) { 9700 unsigned Index = 0; 9701 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9702 End = CD->bases_end(); I != End; ++I, ++Index) { 9703 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9704 LValue Subobject = This; 9705 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9706 return false; 9707 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9708 Result.getStructBase(Index))) 9709 return false; 9710 } 9711 } 9712 9713 for (const auto *I : RD->fields()) { 9714 // -- if T is a reference type, no initialization is performed. 9715 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9716 continue; 9717 9718 LValue Subobject = This; 9719 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9720 return false; 9721 9722 ImplicitValueInitExpr VIE(I->getType()); 9723 if (!EvaluateInPlace( 9724 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9725 return false; 9726 } 9727 9728 return true; 9729 } 9730 9731 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9732 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9733 if (RD->isInvalidDecl()) return false; 9734 if (RD->isUnion()) { 9735 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9736 // object's first non-static named data member is zero-initialized 9737 RecordDecl::field_iterator I = RD->field_begin(); 9738 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9739 ++I; 9740 if (I == RD->field_end()) { 9741 Result = APValue((const FieldDecl*)nullptr); 9742 return true; 9743 } 9744 9745 LValue Subobject = This; 9746 if (!HandleLValueMember(Info, E, Subobject, *I)) 9747 return false; 9748 Result = APValue(*I); 9749 ImplicitValueInitExpr VIE(I->getType()); 9750 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9751 } 9752 9753 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9754 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9755 return false; 9756 } 9757 9758 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9759 } 9760 9761 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9762 switch (E->getCastKind()) { 9763 default: 9764 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9765 9766 case CK_ConstructorConversion: 9767 return Visit(E->getSubExpr()); 9768 9769 case CK_DerivedToBase: 9770 case CK_UncheckedDerivedToBase: { 9771 APValue DerivedObject; 9772 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9773 return false; 9774 if (!DerivedObject.isStruct()) 9775 return Error(E->getSubExpr()); 9776 9777 // Derived-to-base rvalue conversion: just slice off the derived part. 9778 APValue *Value = &DerivedObject; 9779 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9780 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9781 PathE = E->path_end(); PathI != PathE; ++PathI) { 9782 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9783 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9784 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9785 RD = Base; 9786 } 9787 Result = *Value; 9788 return true; 9789 } 9790 } 9791 } 9792 9793 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9794 if (E->isTransparent()) 9795 return Visit(E->getInit(0)); 9796 9797 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9798 if (RD->isInvalidDecl()) return false; 9799 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9800 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9801 9802 EvalInfo::EvaluatingConstructorRAII EvalObj( 9803 Info, 9804 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9805 CXXRD && CXXRD->getNumBases()); 9806 9807 if (RD->isUnion()) { 9808 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9809 Result = APValue(Field); 9810 if (!Field) 9811 return true; 9812 9813 // If the initializer list for a union does not contain any elements, the 9814 // first element of the union is value-initialized. 9815 // FIXME: The element should be initialized from an initializer list. 9816 // Is this difference ever observable for initializer lists which 9817 // we don't build? 9818 ImplicitValueInitExpr VIE(Field->getType()); 9819 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9820 9821 LValue Subobject = This; 9822 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9823 return false; 9824 9825 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9826 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9827 isa<CXXDefaultInitExpr>(InitExpr)); 9828 9829 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9830 if (Field->isBitField()) 9831 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9832 Field); 9833 return true; 9834 } 9835 9836 return false; 9837 } 9838 9839 if (!Result.hasValue()) 9840 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9841 std::distance(RD->field_begin(), RD->field_end())); 9842 unsigned ElementNo = 0; 9843 bool Success = true; 9844 9845 // Initialize base classes. 9846 if (CXXRD && CXXRD->getNumBases()) { 9847 for (const auto &Base : CXXRD->bases()) { 9848 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9849 const Expr *Init = E->getInit(ElementNo); 9850 9851 LValue Subobject = This; 9852 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9853 return false; 9854 9855 APValue &FieldVal = Result.getStructBase(ElementNo); 9856 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9857 if (!Info.noteFailure()) 9858 return false; 9859 Success = false; 9860 } 9861 ++ElementNo; 9862 } 9863 9864 EvalObj.finishedConstructingBases(); 9865 } 9866 9867 // Initialize members. 9868 for (const auto *Field : RD->fields()) { 9869 // Anonymous bit-fields are not considered members of the class for 9870 // purposes of aggregate initialization. 9871 if (Field->isUnnamedBitfield()) 9872 continue; 9873 9874 LValue Subobject = This; 9875 9876 bool HaveInit = ElementNo < E->getNumInits(); 9877 9878 // FIXME: Diagnostics here should point to the end of the initializer 9879 // list, not the start. 9880 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9881 Subobject, Field, &Layout)) 9882 return false; 9883 9884 // Perform an implicit value-initialization for members beyond the end of 9885 // the initializer list. 9886 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9887 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9888 9889 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9890 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9891 isa<CXXDefaultInitExpr>(Init)); 9892 9893 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9894 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9895 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9896 FieldVal, Field))) { 9897 if (!Info.noteFailure()) 9898 return false; 9899 Success = false; 9900 } 9901 } 9902 9903 EvalObj.finishedConstructingFields(); 9904 9905 return Success; 9906 } 9907 9908 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9909 QualType T) { 9910 // Note that E's type is not necessarily the type of our class here; we might 9911 // be initializing an array element instead. 9912 const CXXConstructorDecl *FD = E->getConstructor(); 9913 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9914 9915 bool ZeroInit = E->requiresZeroInitialization(); 9916 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9917 // If we've already performed zero-initialization, we're already done. 9918 if (Result.hasValue()) 9919 return true; 9920 9921 if (ZeroInit) 9922 return ZeroInitialization(E, T); 9923 9924 return getDefaultInitValue(T, Result); 9925 } 9926 9927 const FunctionDecl *Definition = nullptr; 9928 auto Body = FD->getBody(Definition); 9929 9930 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9931 return false; 9932 9933 // Avoid materializing a temporary for an elidable copy/move constructor. 9934 if (E->isElidable() && !ZeroInit) 9935 if (const MaterializeTemporaryExpr *ME 9936 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9937 return Visit(ME->getSubExpr()); 9938 9939 if (ZeroInit && !ZeroInitialization(E, T)) 9940 return false; 9941 9942 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9943 return HandleConstructorCall(E, This, Args, 9944 cast<CXXConstructorDecl>(Definition), Info, 9945 Result); 9946 } 9947 9948 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9949 const CXXInheritedCtorInitExpr *E) { 9950 if (!Info.CurrentCall) { 9951 assert(Info.checkingPotentialConstantExpression()); 9952 return false; 9953 } 9954 9955 const CXXConstructorDecl *FD = E->getConstructor(); 9956 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9957 return false; 9958 9959 const FunctionDecl *Definition = nullptr; 9960 auto Body = FD->getBody(Definition); 9961 9962 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9963 return false; 9964 9965 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9966 cast<CXXConstructorDecl>(Definition), Info, 9967 Result); 9968 } 9969 9970 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9971 const CXXStdInitializerListExpr *E) { 9972 const ConstantArrayType *ArrayType = 9973 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9974 9975 LValue Array; 9976 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9977 return false; 9978 9979 // Get a pointer to the first element of the array. 9980 Array.addArray(Info, E, ArrayType); 9981 9982 auto InvalidType = [&] { 9983 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9984 << E->getType(); 9985 return false; 9986 }; 9987 9988 // FIXME: Perform the checks on the field types in SemaInit. 9989 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9990 RecordDecl::field_iterator Field = Record->field_begin(); 9991 if (Field == Record->field_end()) 9992 return InvalidType(); 9993 9994 // Start pointer. 9995 if (!Field->getType()->isPointerType() || 9996 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9997 ArrayType->getElementType())) 9998 return InvalidType(); 9999 10000 // FIXME: What if the initializer_list type has base classes, etc? 10001 Result = APValue(APValue::UninitStruct(), 0, 2); 10002 Array.moveInto(Result.getStructField(0)); 10003 10004 if (++Field == Record->field_end()) 10005 return InvalidType(); 10006 10007 if (Field->getType()->isPointerType() && 10008 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 10009 ArrayType->getElementType())) { 10010 // End pointer. 10011 if (!HandleLValueArrayAdjustment(Info, E, Array, 10012 ArrayType->getElementType(), 10013 ArrayType->getSize().getZExtValue())) 10014 return false; 10015 Array.moveInto(Result.getStructField(1)); 10016 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 10017 // Length. 10018 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 10019 else 10020 return InvalidType(); 10021 10022 if (++Field != Record->field_end()) 10023 return InvalidType(); 10024 10025 return true; 10026 } 10027 10028 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10029 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10030 if (ClosureClass->isInvalidDecl()) 10031 return false; 10032 10033 const size_t NumFields = 10034 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10035 10036 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10037 E->capture_init_end()) && 10038 "The number of lambda capture initializers should equal the number of " 10039 "fields within the closure type"); 10040 10041 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10042 // Iterate through all the lambda's closure object's fields and initialize 10043 // them. 10044 auto *CaptureInitIt = E->capture_init_begin(); 10045 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10046 bool Success = true; 10047 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10048 for (const auto *Field : ClosureClass->fields()) { 10049 assert(CaptureInitIt != E->capture_init_end()); 10050 // Get the initializer for this field 10051 Expr *const CurFieldInit = *CaptureInitIt++; 10052 10053 // If there is no initializer, either this is a VLA or an error has 10054 // occurred. 10055 if (!CurFieldInit) 10056 return Error(E); 10057 10058 LValue Subobject = This; 10059 10060 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10061 return false; 10062 10063 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10064 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10065 if (!Info.keepEvaluatingAfterFailure()) 10066 return false; 10067 Success = false; 10068 } 10069 ++CaptureIt; 10070 } 10071 return Success; 10072 } 10073 10074 static bool EvaluateRecord(const Expr *E, const LValue &This, 10075 APValue &Result, EvalInfo &Info) { 10076 assert(!E->isValueDependent()); 10077 assert(E->isRValue() && E->getType()->isRecordType() && 10078 "can't evaluate expression as a record rvalue"); 10079 return RecordExprEvaluator(Info, This, Result).Visit(E); 10080 } 10081 10082 //===----------------------------------------------------------------------===// 10083 // Temporary Evaluation 10084 // 10085 // Temporaries are represented in the AST as rvalues, but generally behave like 10086 // lvalues. The full-object of which the temporary is a subobject is implicitly 10087 // materialized so that a reference can bind to it. 10088 //===----------------------------------------------------------------------===// 10089 namespace { 10090 class TemporaryExprEvaluator 10091 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10092 public: 10093 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10094 LValueExprEvaluatorBaseTy(Info, Result, false) {} 10095 10096 /// Visit an expression which constructs the value of this temporary. 10097 bool VisitConstructExpr(const Expr *E) { 10098 APValue &Value = Info.CurrentCall->createTemporary( 10099 E, E->getType(), ScopeKind::FullExpression, Result); 10100 return EvaluateInPlace(Value, Info, Result, E); 10101 } 10102 10103 bool VisitCastExpr(const CastExpr *E) { 10104 switch (E->getCastKind()) { 10105 default: 10106 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10107 10108 case CK_ConstructorConversion: 10109 return VisitConstructExpr(E->getSubExpr()); 10110 } 10111 } 10112 bool VisitInitListExpr(const InitListExpr *E) { 10113 return VisitConstructExpr(E); 10114 } 10115 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10116 return VisitConstructExpr(E); 10117 } 10118 bool VisitCallExpr(const CallExpr *E) { 10119 return VisitConstructExpr(E); 10120 } 10121 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10122 return VisitConstructExpr(E); 10123 } 10124 bool VisitLambdaExpr(const LambdaExpr *E) { 10125 return VisitConstructExpr(E); 10126 } 10127 }; 10128 } // end anonymous namespace 10129 10130 /// Evaluate an expression of record type as a temporary. 10131 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10132 assert(!E->isValueDependent()); 10133 assert(E->isRValue() && E->getType()->isRecordType()); 10134 return TemporaryExprEvaluator(Info, Result).Visit(E); 10135 } 10136 10137 //===----------------------------------------------------------------------===// 10138 // Vector Evaluation 10139 //===----------------------------------------------------------------------===// 10140 10141 namespace { 10142 class VectorExprEvaluator 10143 : public ExprEvaluatorBase<VectorExprEvaluator> { 10144 APValue &Result; 10145 public: 10146 10147 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10148 : ExprEvaluatorBaseTy(info), Result(Result) {} 10149 10150 bool Success(ArrayRef<APValue> V, const Expr *E) { 10151 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10152 // FIXME: remove this APValue copy. 10153 Result = APValue(V.data(), V.size()); 10154 return true; 10155 } 10156 bool Success(const APValue &V, const Expr *E) { 10157 assert(V.isVector()); 10158 Result = V; 10159 return true; 10160 } 10161 bool ZeroInitialization(const Expr *E); 10162 10163 bool VisitUnaryReal(const UnaryOperator *E) 10164 { return Visit(E->getSubExpr()); } 10165 bool VisitCastExpr(const CastExpr* E); 10166 bool VisitInitListExpr(const InitListExpr *E); 10167 bool VisitUnaryImag(const UnaryOperator *E); 10168 bool VisitBinaryOperator(const BinaryOperator *E); 10169 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10170 // conditional select), shufflevector, ExtVectorElementExpr 10171 }; 10172 } // end anonymous namespace 10173 10174 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10175 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10176 return VectorExprEvaluator(Info, Result).Visit(E); 10177 } 10178 10179 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10180 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10181 unsigned NElts = VTy->getNumElements(); 10182 10183 const Expr *SE = E->getSubExpr(); 10184 QualType SETy = SE->getType(); 10185 10186 switch (E->getCastKind()) { 10187 case CK_VectorSplat: { 10188 APValue Val = APValue(); 10189 if (SETy->isIntegerType()) { 10190 APSInt IntResult; 10191 if (!EvaluateInteger(SE, IntResult, Info)) 10192 return false; 10193 Val = APValue(std::move(IntResult)); 10194 } else if (SETy->isRealFloatingType()) { 10195 APFloat FloatResult(0.0); 10196 if (!EvaluateFloat(SE, FloatResult, Info)) 10197 return false; 10198 Val = APValue(std::move(FloatResult)); 10199 } else { 10200 return Error(E); 10201 } 10202 10203 // Splat and create vector APValue. 10204 SmallVector<APValue, 4> Elts(NElts, Val); 10205 return Success(Elts, E); 10206 } 10207 case CK_BitCast: { 10208 // Evaluate the operand into an APInt we can extract from. 10209 llvm::APInt SValInt; 10210 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10211 return false; 10212 // Extract the elements 10213 QualType EltTy = VTy->getElementType(); 10214 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10215 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10216 SmallVector<APValue, 4> Elts; 10217 if (EltTy->isRealFloatingType()) { 10218 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10219 unsigned FloatEltSize = EltSize; 10220 if (&Sem == &APFloat::x87DoubleExtended()) 10221 FloatEltSize = 80; 10222 for (unsigned i = 0; i < NElts; i++) { 10223 llvm::APInt Elt; 10224 if (BigEndian) 10225 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10226 else 10227 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10228 Elts.push_back(APValue(APFloat(Sem, Elt))); 10229 } 10230 } else if (EltTy->isIntegerType()) { 10231 for (unsigned i = 0; i < NElts; i++) { 10232 llvm::APInt Elt; 10233 if (BigEndian) 10234 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10235 else 10236 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10237 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10238 } 10239 } else { 10240 return Error(E); 10241 } 10242 return Success(Elts, E); 10243 } 10244 default: 10245 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10246 } 10247 } 10248 10249 bool 10250 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10251 const VectorType *VT = E->getType()->castAs<VectorType>(); 10252 unsigned NumInits = E->getNumInits(); 10253 unsigned NumElements = VT->getNumElements(); 10254 10255 QualType EltTy = VT->getElementType(); 10256 SmallVector<APValue, 4> Elements; 10257 10258 // The number of initializers can be less than the number of 10259 // vector elements. For OpenCL, this can be due to nested vector 10260 // initialization. For GCC compatibility, missing trailing elements 10261 // should be initialized with zeroes. 10262 unsigned CountInits = 0, CountElts = 0; 10263 while (CountElts < NumElements) { 10264 // Handle nested vector initialization. 10265 if (CountInits < NumInits 10266 && E->getInit(CountInits)->getType()->isVectorType()) { 10267 APValue v; 10268 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10269 return Error(E); 10270 unsigned vlen = v.getVectorLength(); 10271 for (unsigned j = 0; j < vlen; j++) 10272 Elements.push_back(v.getVectorElt(j)); 10273 CountElts += vlen; 10274 } else if (EltTy->isIntegerType()) { 10275 llvm::APSInt sInt(32); 10276 if (CountInits < NumInits) { 10277 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10278 return false; 10279 } else // trailing integer zero. 10280 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10281 Elements.push_back(APValue(sInt)); 10282 CountElts++; 10283 } else { 10284 llvm::APFloat f(0.0); 10285 if (CountInits < NumInits) { 10286 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10287 return false; 10288 } else // trailing float zero. 10289 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10290 Elements.push_back(APValue(f)); 10291 CountElts++; 10292 } 10293 CountInits++; 10294 } 10295 return Success(Elements, E); 10296 } 10297 10298 bool 10299 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10300 const auto *VT = E->getType()->castAs<VectorType>(); 10301 QualType EltTy = VT->getElementType(); 10302 APValue ZeroElement; 10303 if (EltTy->isIntegerType()) 10304 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10305 else 10306 ZeroElement = 10307 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10308 10309 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10310 return Success(Elements, E); 10311 } 10312 10313 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10314 VisitIgnoredValue(E->getSubExpr()); 10315 return ZeroInitialization(E); 10316 } 10317 10318 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10319 BinaryOperatorKind Op = E->getOpcode(); 10320 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10321 "Operation not supported on vector types"); 10322 10323 if (Op == BO_Comma) 10324 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10325 10326 Expr *LHS = E->getLHS(); 10327 Expr *RHS = E->getRHS(); 10328 10329 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10330 "Must both be vector types"); 10331 // Checking JUST the types are the same would be fine, except shifts don't 10332 // need to have their types be the same (since you always shift by an int). 10333 assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10334 E->getType()->castAs<VectorType>()->getNumElements() && 10335 RHS->getType()->castAs<VectorType>()->getNumElements() == 10336 E->getType()->castAs<VectorType>()->getNumElements() && 10337 "All operands must be the same size."); 10338 10339 APValue LHSValue; 10340 APValue RHSValue; 10341 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10342 if (!LHSOK && !Info.noteFailure()) 10343 return false; 10344 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10345 return false; 10346 10347 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10348 return false; 10349 10350 return Success(LHSValue, E); 10351 } 10352 10353 //===----------------------------------------------------------------------===// 10354 // Array Evaluation 10355 //===----------------------------------------------------------------------===// 10356 10357 namespace { 10358 class ArrayExprEvaluator 10359 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10360 const LValue &This; 10361 APValue &Result; 10362 public: 10363 10364 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10365 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10366 10367 bool Success(const APValue &V, const Expr *E) { 10368 assert(V.isArray() && "expected array"); 10369 Result = V; 10370 return true; 10371 } 10372 10373 bool ZeroInitialization(const Expr *E) { 10374 const ConstantArrayType *CAT = 10375 Info.Ctx.getAsConstantArrayType(E->getType()); 10376 if (!CAT) { 10377 if (E->getType()->isIncompleteArrayType()) { 10378 // We can be asked to zero-initialize a flexible array member; this 10379 // is represented as an ImplicitValueInitExpr of incomplete array 10380 // type. In this case, the array has zero elements. 10381 Result = APValue(APValue::UninitArray(), 0, 0); 10382 return true; 10383 } 10384 // FIXME: We could handle VLAs here. 10385 return Error(E); 10386 } 10387 10388 Result = APValue(APValue::UninitArray(), 0, 10389 CAT->getSize().getZExtValue()); 10390 if (!Result.hasArrayFiller()) 10391 return true; 10392 10393 // Zero-initialize all elements. 10394 LValue Subobject = This; 10395 Subobject.addArray(Info, E, CAT); 10396 ImplicitValueInitExpr VIE(CAT->getElementType()); 10397 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10398 } 10399 10400 bool VisitCallExpr(const CallExpr *E) { 10401 return handleCallExpr(E, Result, &This); 10402 } 10403 bool VisitInitListExpr(const InitListExpr *E, 10404 QualType AllocType = QualType()); 10405 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10406 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10407 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10408 const LValue &Subobject, 10409 APValue *Value, QualType Type); 10410 bool VisitStringLiteral(const StringLiteral *E, 10411 QualType AllocType = QualType()) { 10412 expandStringLiteral(Info, E, Result, AllocType); 10413 return true; 10414 } 10415 }; 10416 } // end anonymous namespace 10417 10418 static bool EvaluateArray(const Expr *E, const LValue &This, 10419 APValue &Result, EvalInfo &Info) { 10420 assert(!E->isValueDependent()); 10421 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10422 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10423 } 10424 10425 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10426 APValue &Result, const InitListExpr *ILE, 10427 QualType AllocType) { 10428 assert(!ILE->isValueDependent()); 10429 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10430 "not an array rvalue"); 10431 return ArrayExprEvaluator(Info, This, Result) 10432 .VisitInitListExpr(ILE, AllocType); 10433 } 10434 10435 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10436 APValue &Result, 10437 const CXXConstructExpr *CCE, 10438 QualType AllocType) { 10439 assert(!CCE->isValueDependent()); 10440 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10441 "not an array rvalue"); 10442 return ArrayExprEvaluator(Info, This, Result) 10443 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10444 } 10445 10446 // Return true iff the given array filler may depend on the element index. 10447 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10448 // For now, just allow non-class value-initialization and initialization 10449 // lists comprised of them. 10450 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10451 return false; 10452 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10453 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10454 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10455 return true; 10456 } 10457 return false; 10458 } 10459 return true; 10460 } 10461 10462 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10463 QualType AllocType) { 10464 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10465 AllocType.isNull() ? E->getType() : AllocType); 10466 if (!CAT) 10467 return Error(E); 10468 10469 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10470 // an appropriately-typed string literal enclosed in braces. 10471 if (E->isStringLiteralInit()) { 10472 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10473 // FIXME: Support ObjCEncodeExpr here once we support it in 10474 // ArrayExprEvaluator generally. 10475 if (!SL) 10476 return Error(E); 10477 return VisitStringLiteral(SL, AllocType); 10478 } 10479 10480 bool Success = true; 10481 10482 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10483 "zero-initialized array shouldn't have any initialized elts"); 10484 APValue Filler; 10485 if (Result.isArray() && Result.hasArrayFiller()) 10486 Filler = Result.getArrayFiller(); 10487 10488 unsigned NumEltsToInit = E->getNumInits(); 10489 unsigned NumElts = CAT->getSize().getZExtValue(); 10490 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10491 10492 // If the initializer might depend on the array index, run it for each 10493 // array element. 10494 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10495 NumEltsToInit = NumElts; 10496 10497 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10498 << NumEltsToInit << ".\n"); 10499 10500 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10501 10502 // If the array was previously zero-initialized, preserve the 10503 // zero-initialized values. 10504 if (Filler.hasValue()) { 10505 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10506 Result.getArrayInitializedElt(I) = Filler; 10507 if (Result.hasArrayFiller()) 10508 Result.getArrayFiller() = Filler; 10509 } 10510 10511 LValue Subobject = This; 10512 Subobject.addArray(Info, E, CAT); 10513 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10514 const Expr *Init = 10515 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10516 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10517 Info, Subobject, Init) || 10518 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10519 CAT->getElementType(), 1)) { 10520 if (!Info.noteFailure()) 10521 return false; 10522 Success = false; 10523 } 10524 } 10525 10526 if (!Result.hasArrayFiller()) 10527 return Success; 10528 10529 // If we get here, we have a trivial filler, which we can just evaluate 10530 // once and splat over the rest of the array elements. 10531 assert(FillerExpr && "no array filler for incomplete init list"); 10532 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10533 FillerExpr) && Success; 10534 } 10535 10536 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10537 LValue CommonLV; 10538 if (E->getCommonExpr() && 10539 !Evaluate(Info.CurrentCall->createTemporary( 10540 E->getCommonExpr(), 10541 getStorageType(Info.Ctx, E->getCommonExpr()), 10542 ScopeKind::FullExpression, CommonLV), 10543 Info, E->getCommonExpr()->getSourceExpr())) 10544 return false; 10545 10546 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10547 10548 uint64_t Elements = CAT->getSize().getZExtValue(); 10549 Result = APValue(APValue::UninitArray(), Elements, Elements); 10550 10551 LValue Subobject = This; 10552 Subobject.addArray(Info, E, CAT); 10553 10554 bool Success = true; 10555 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10556 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10557 Info, Subobject, E->getSubExpr()) || 10558 !HandleLValueArrayAdjustment(Info, E, Subobject, 10559 CAT->getElementType(), 1)) { 10560 if (!Info.noteFailure()) 10561 return false; 10562 Success = false; 10563 } 10564 } 10565 10566 return Success; 10567 } 10568 10569 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10570 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10571 } 10572 10573 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10574 const LValue &Subobject, 10575 APValue *Value, 10576 QualType Type) { 10577 bool HadZeroInit = Value->hasValue(); 10578 10579 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10580 unsigned N = CAT->getSize().getZExtValue(); 10581 10582 // Preserve the array filler if we had prior zero-initialization. 10583 APValue Filler = 10584 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10585 : APValue(); 10586 10587 *Value = APValue(APValue::UninitArray(), N, N); 10588 10589 if (HadZeroInit) 10590 for (unsigned I = 0; I != N; ++I) 10591 Value->getArrayInitializedElt(I) = Filler; 10592 10593 // Initialize the elements. 10594 LValue ArrayElt = Subobject; 10595 ArrayElt.addArray(Info, E, CAT); 10596 for (unsigned I = 0; I != N; ++I) 10597 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10598 CAT->getElementType()) || 10599 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10600 CAT->getElementType(), 1)) 10601 return false; 10602 10603 return true; 10604 } 10605 10606 if (!Type->isRecordType()) 10607 return Error(E); 10608 10609 return RecordExprEvaluator(Info, Subobject, *Value) 10610 .VisitCXXConstructExpr(E, Type); 10611 } 10612 10613 //===----------------------------------------------------------------------===// 10614 // Integer Evaluation 10615 // 10616 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10617 // types and back in constant folding. Integer values are thus represented 10618 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10619 //===----------------------------------------------------------------------===// 10620 10621 namespace { 10622 class IntExprEvaluator 10623 : public ExprEvaluatorBase<IntExprEvaluator> { 10624 APValue &Result; 10625 public: 10626 IntExprEvaluator(EvalInfo &info, APValue &result) 10627 : ExprEvaluatorBaseTy(info), Result(result) {} 10628 10629 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10630 assert(E->getType()->isIntegralOrEnumerationType() && 10631 "Invalid evaluation result."); 10632 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10633 "Invalid evaluation result."); 10634 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10635 "Invalid evaluation result."); 10636 Result = APValue(SI); 10637 return true; 10638 } 10639 bool Success(const llvm::APSInt &SI, const Expr *E) { 10640 return Success(SI, E, Result); 10641 } 10642 10643 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10644 assert(E->getType()->isIntegralOrEnumerationType() && 10645 "Invalid evaluation result."); 10646 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10647 "Invalid evaluation result."); 10648 Result = APValue(APSInt(I)); 10649 Result.getInt().setIsUnsigned( 10650 E->getType()->isUnsignedIntegerOrEnumerationType()); 10651 return true; 10652 } 10653 bool Success(const llvm::APInt &I, const Expr *E) { 10654 return Success(I, E, Result); 10655 } 10656 10657 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10658 assert(E->getType()->isIntegralOrEnumerationType() && 10659 "Invalid evaluation result."); 10660 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10661 return true; 10662 } 10663 bool Success(uint64_t Value, const Expr *E) { 10664 return Success(Value, E, Result); 10665 } 10666 10667 bool Success(CharUnits Size, const Expr *E) { 10668 return Success(Size.getQuantity(), E); 10669 } 10670 10671 bool Success(const APValue &V, const Expr *E) { 10672 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10673 Result = V; 10674 return true; 10675 } 10676 return Success(V.getInt(), E); 10677 } 10678 10679 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10680 10681 //===--------------------------------------------------------------------===// 10682 // Visitor Methods 10683 //===--------------------------------------------------------------------===// 10684 10685 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10686 return Success(E->getValue(), E); 10687 } 10688 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10689 return Success(E->getValue(), E); 10690 } 10691 10692 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10693 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10694 if (CheckReferencedDecl(E, E->getDecl())) 10695 return true; 10696 10697 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10698 } 10699 bool VisitMemberExpr(const MemberExpr *E) { 10700 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10701 VisitIgnoredBaseExpression(E->getBase()); 10702 return true; 10703 } 10704 10705 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10706 } 10707 10708 bool VisitCallExpr(const CallExpr *E); 10709 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10710 bool VisitBinaryOperator(const BinaryOperator *E); 10711 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10712 bool VisitUnaryOperator(const UnaryOperator *E); 10713 10714 bool VisitCastExpr(const CastExpr* E); 10715 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10716 10717 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10718 return Success(E->getValue(), E); 10719 } 10720 10721 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10722 return Success(E->getValue(), E); 10723 } 10724 10725 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10726 if (Info.ArrayInitIndex == uint64_t(-1)) { 10727 // We were asked to evaluate this subexpression independent of the 10728 // enclosing ArrayInitLoopExpr. We can't do that. 10729 Info.FFDiag(E); 10730 return false; 10731 } 10732 return Success(Info.ArrayInitIndex, E); 10733 } 10734 10735 // Note, GNU defines __null as an integer, not a pointer. 10736 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10737 return ZeroInitialization(E); 10738 } 10739 10740 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10741 return Success(E->getValue(), E); 10742 } 10743 10744 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10745 return Success(E->getValue(), E); 10746 } 10747 10748 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10749 return Success(E->getValue(), E); 10750 } 10751 10752 bool VisitUnaryReal(const UnaryOperator *E); 10753 bool VisitUnaryImag(const UnaryOperator *E); 10754 10755 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10756 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10757 bool VisitSourceLocExpr(const SourceLocExpr *E); 10758 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10759 bool VisitRequiresExpr(const RequiresExpr *E); 10760 // FIXME: Missing: array subscript of vector, member of vector 10761 }; 10762 10763 class FixedPointExprEvaluator 10764 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10765 APValue &Result; 10766 10767 public: 10768 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10769 : ExprEvaluatorBaseTy(info), Result(result) {} 10770 10771 bool Success(const llvm::APInt &I, const Expr *E) { 10772 return Success( 10773 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10774 } 10775 10776 bool Success(uint64_t Value, const Expr *E) { 10777 return Success( 10778 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10779 } 10780 10781 bool Success(const APValue &V, const Expr *E) { 10782 return Success(V.getFixedPoint(), E); 10783 } 10784 10785 bool Success(const APFixedPoint &V, const Expr *E) { 10786 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10787 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10788 "Invalid evaluation result."); 10789 Result = APValue(V); 10790 return true; 10791 } 10792 10793 //===--------------------------------------------------------------------===// 10794 // Visitor Methods 10795 //===--------------------------------------------------------------------===// 10796 10797 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10798 return Success(E->getValue(), E); 10799 } 10800 10801 bool VisitCastExpr(const CastExpr *E); 10802 bool VisitUnaryOperator(const UnaryOperator *E); 10803 bool VisitBinaryOperator(const BinaryOperator *E); 10804 }; 10805 } // end anonymous namespace 10806 10807 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10808 /// produce either the integer value or a pointer. 10809 /// 10810 /// GCC has a heinous extension which folds casts between pointer types and 10811 /// pointer-sized integral types. We support this by allowing the evaluation of 10812 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10813 /// Some simple arithmetic on such values is supported (they are treated much 10814 /// like char*). 10815 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10816 EvalInfo &Info) { 10817 assert(!E->isValueDependent()); 10818 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10819 return IntExprEvaluator(Info, Result).Visit(E); 10820 } 10821 10822 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10823 assert(!E->isValueDependent()); 10824 APValue Val; 10825 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10826 return false; 10827 if (!Val.isInt()) { 10828 // FIXME: It would be better to produce the diagnostic for casting 10829 // a pointer to an integer. 10830 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10831 return false; 10832 } 10833 Result = Val.getInt(); 10834 return true; 10835 } 10836 10837 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10838 APValue Evaluated = E->EvaluateInContext( 10839 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10840 return Success(Evaluated, E); 10841 } 10842 10843 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10844 EvalInfo &Info) { 10845 assert(!E->isValueDependent()); 10846 if (E->getType()->isFixedPointType()) { 10847 APValue Val; 10848 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10849 return false; 10850 if (!Val.isFixedPoint()) 10851 return false; 10852 10853 Result = Val.getFixedPoint(); 10854 return true; 10855 } 10856 return false; 10857 } 10858 10859 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10860 EvalInfo &Info) { 10861 assert(!E->isValueDependent()); 10862 if (E->getType()->isIntegerType()) { 10863 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10864 APSInt Val; 10865 if (!EvaluateInteger(E, Val, Info)) 10866 return false; 10867 Result = APFixedPoint(Val, FXSema); 10868 return true; 10869 } else if (E->getType()->isFixedPointType()) { 10870 return EvaluateFixedPoint(E, Result, Info); 10871 } 10872 return false; 10873 } 10874 10875 /// Check whether the given declaration can be directly converted to an integral 10876 /// rvalue. If not, no diagnostic is produced; there are other things we can 10877 /// try. 10878 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10879 // Enums are integer constant exprs. 10880 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10881 // Check for signedness/width mismatches between E type and ECD value. 10882 bool SameSign = (ECD->getInitVal().isSigned() 10883 == E->getType()->isSignedIntegerOrEnumerationType()); 10884 bool SameWidth = (ECD->getInitVal().getBitWidth() 10885 == Info.Ctx.getIntWidth(E->getType())); 10886 if (SameSign && SameWidth) 10887 return Success(ECD->getInitVal(), E); 10888 else { 10889 // Get rid of mismatch (otherwise Success assertions will fail) 10890 // by computing a new value matching the type of E. 10891 llvm::APSInt Val = ECD->getInitVal(); 10892 if (!SameSign) 10893 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10894 if (!SameWidth) 10895 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10896 return Success(Val, E); 10897 } 10898 } 10899 return false; 10900 } 10901 10902 /// Values returned by __builtin_classify_type, chosen to match the values 10903 /// produced by GCC's builtin. 10904 enum class GCCTypeClass { 10905 None = -1, 10906 Void = 0, 10907 Integer = 1, 10908 // GCC reserves 2 for character types, but instead classifies them as 10909 // integers. 10910 Enum = 3, 10911 Bool = 4, 10912 Pointer = 5, 10913 // GCC reserves 6 for references, but appears to never use it (because 10914 // expressions never have reference type, presumably). 10915 PointerToDataMember = 7, 10916 RealFloat = 8, 10917 Complex = 9, 10918 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10919 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10920 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10921 // uses 12 for that purpose, same as for a class or struct. Maybe it 10922 // internally implements a pointer to member as a struct? Who knows. 10923 PointerToMemberFunction = 12, // Not a bug, see above. 10924 ClassOrStruct = 12, 10925 Union = 13, 10926 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10927 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10928 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10929 // literals. 10930 }; 10931 10932 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10933 /// as GCC. 10934 static GCCTypeClass 10935 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10936 assert(!T->isDependentType() && "unexpected dependent type"); 10937 10938 QualType CanTy = T.getCanonicalType(); 10939 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10940 10941 switch (CanTy->getTypeClass()) { 10942 #define TYPE(ID, BASE) 10943 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10944 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10945 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10946 #include "clang/AST/TypeNodes.inc" 10947 case Type::Auto: 10948 case Type::DeducedTemplateSpecialization: 10949 llvm_unreachable("unexpected non-canonical or dependent type"); 10950 10951 case Type::Builtin: 10952 switch (BT->getKind()) { 10953 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10954 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10955 case BuiltinType::ID: return GCCTypeClass::Integer; 10956 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10957 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10958 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10959 case BuiltinType::ID: break; 10960 #include "clang/AST/BuiltinTypes.def" 10961 case BuiltinType::Void: 10962 return GCCTypeClass::Void; 10963 10964 case BuiltinType::Bool: 10965 return GCCTypeClass::Bool; 10966 10967 case BuiltinType::Char_U: 10968 case BuiltinType::UChar: 10969 case BuiltinType::WChar_U: 10970 case BuiltinType::Char8: 10971 case BuiltinType::Char16: 10972 case BuiltinType::Char32: 10973 case BuiltinType::UShort: 10974 case BuiltinType::UInt: 10975 case BuiltinType::ULong: 10976 case BuiltinType::ULongLong: 10977 case BuiltinType::UInt128: 10978 return GCCTypeClass::Integer; 10979 10980 case BuiltinType::UShortAccum: 10981 case BuiltinType::UAccum: 10982 case BuiltinType::ULongAccum: 10983 case BuiltinType::UShortFract: 10984 case BuiltinType::UFract: 10985 case BuiltinType::ULongFract: 10986 case BuiltinType::SatUShortAccum: 10987 case BuiltinType::SatUAccum: 10988 case BuiltinType::SatULongAccum: 10989 case BuiltinType::SatUShortFract: 10990 case BuiltinType::SatUFract: 10991 case BuiltinType::SatULongFract: 10992 return GCCTypeClass::None; 10993 10994 case BuiltinType::NullPtr: 10995 10996 case BuiltinType::ObjCId: 10997 case BuiltinType::ObjCClass: 10998 case BuiltinType::ObjCSel: 10999 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 11000 case BuiltinType::Id: 11001 #include "clang/Basic/OpenCLImageTypes.def" 11002 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 11003 case BuiltinType::Id: 11004 #include "clang/Basic/OpenCLExtensionTypes.def" 11005 case BuiltinType::OCLSampler: 11006 case BuiltinType::OCLEvent: 11007 case BuiltinType::OCLClkEvent: 11008 case BuiltinType::OCLQueue: 11009 case BuiltinType::OCLReserveID: 11010 #define SVE_TYPE(Name, Id, SingletonId) \ 11011 case BuiltinType::Id: 11012 #include "clang/Basic/AArch64SVEACLETypes.def" 11013 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 11014 case BuiltinType::Id: 11015 #include "clang/Basic/PPCTypes.def" 11016 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 11017 #include "clang/Basic/RISCVVTypes.def" 11018 return GCCTypeClass::None; 11019 11020 case BuiltinType::Dependent: 11021 llvm_unreachable("unexpected dependent type"); 11022 }; 11023 llvm_unreachable("unexpected placeholder type"); 11024 11025 case Type::Enum: 11026 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11027 11028 case Type::Pointer: 11029 case Type::ConstantArray: 11030 case Type::VariableArray: 11031 case Type::IncompleteArray: 11032 case Type::FunctionNoProto: 11033 case Type::FunctionProto: 11034 return GCCTypeClass::Pointer; 11035 11036 case Type::MemberPointer: 11037 return CanTy->isMemberDataPointerType() 11038 ? GCCTypeClass::PointerToDataMember 11039 : GCCTypeClass::PointerToMemberFunction; 11040 11041 case Type::Complex: 11042 return GCCTypeClass::Complex; 11043 11044 case Type::Record: 11045 return CanTy->isUnionType() ? GCCTypeClass::Union 11046 : GCCTypeClass::ClassOrStruct; 11047 11048 case Type::Atomic: 11049 // GCC classifies _Atomic T the same as T. 11050 return EvaluateBuiltinClassifyType( 11051 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11052 11053 case Type::BlockPointer: 11054 case Type::Vector: 11055 case Type::ExtVector: 11056 case Type::ConstantMatrix: 11057 case Type::ObjCObject: 11058 case Type::ObjCInterface: 11059 case Type::ObjCObjectPointer: 11060 case Type::Pipe: 11061 case Type::ExtInt: 11062 // GCC classifies vectors as None. We follow its lead and classify all 11063 // other types that don't fit into the regular classification the same way. 11064 return GCCTypeClass::None; 11065 11066 case Type::LValueReference: 11067 case Type::RValueReference: 11068 llvm_unreachable("invalid type for expression"); 11069 } 11070 11071 llvm_unreachable("unexpected type class"); 11072 } 11073 11074 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11075 /// as GCC. 11076 static GCCTypeClass 11077 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11078 // If no argument was supplied, default to None. This isn't 11079 // ideal, however it is what gcc does. 11080 if (E->getNumArgs() == 0) 11081 return GCCTypeClass::None; 11082 11083 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11084 // being an ICE, but still folds it to a constant using the type of the first 11085 // argument. 11086 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11087 } 11088 11089 /// EvaluateBuiltinConstantPForLValue - Determine the result of 11090 /// __builtin_constant_p when applied to the given pointer. 11091 /// 11092 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11093 /// or it points to the first character of a string literal. 11094 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11095 APValue::LValueBase Base = LV.getLValueBase(); 11096 if (Base.isNull()) { 11097 // A null base is acceptable. 11098 return true; 11099 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11100 if (!isa<StringLiteral>(E)) 11101 return false; 11102 return LV.getLValueOffset().isZero(); 11103 } else if (Base.is<TypeInfoLValue>()) { 11104 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11105 // evaluate to true. 11106 return true; 11107 } else { 11108 // Any other base is not constant enough for GCC. 11109 return false; 11110 } 11111 } 11112 11113 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11114 /// GCC as we can manage. 11115 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11116 // This evaluation is not permitted to have side-effects, so evaluate it in 11117 // a speculative evaluation context. 11118 SpeculativeEvaluationRAII SpeculativeEval(Info); 11119 11120 // Constant-folding is always enabled for the operand of __builtin_constant_p 11121 // (even when the enclosing evaluation context otherwise requires a strict 11122 // language-specific constant expression). 11123 FoldConstant Fold(Info, true); 11124 11125 QualType ArgType = Arg->getType(); 11126 11127 // __builtin_constant_p always has one operand. The rules which gcc follows 11128 // are not precisely documented, but are as follows: 11129 // 11130 // - If the operand is of integral, floating, complex or enumeration type, 11131 // and can be folded to a known value of that type, it returns 1. 11132 // - If the operand can be folded to a pointer to the first character 11133 // of a string literal (or such a pointer cast to an integral type) 11134 // or to a null pointer or an integer cast to a pointer, it returns 1. 11135 // 11136 // Otherwise, it returns 0. 11137 // 11138 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11139 // its support for this did not work prior to GCC 9 and is not yet well 11140 // understood. 11141 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11142 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11143 ArgType->isNullPtrType()) { 11144 APValue V; 11145 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11146 Fold.keepDiagnostics(); 11147 return false; 11148 } 11149 11150 // For a pointer (possibly cast to integer), there are special rules. 11151 if (V.getKind() == APValue::LValue) 11152 return EvaluateBuiltinConstantPForLValue(V); 11153 11154 // Otherwise, any constant value is good enough. 11155 return V.hasValue(); 11156 } 11157 11158 // Anything else isn't considered to be sufficiently constant. 11159 return false; 11160 } 11161 11162 /// Retrieves the "underlying object type" of the given expression, 11163 /// as used by __builtin_object_size. 11164 static QualType getObjectType(APValue::LValueBase B) { 11165 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11166 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11167 return VD->getType(); 11168 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11169 if (isa<CompoundLiteralExpr>(E)) 11170 return E->getType(); 11171 } else if (B.is<TypeInfoLValue>()) { 11172 return B.getTypeInfoType(); 11173 } else if (B.is<DynamicAllocLValue>()) { 11174 return B.getDynamicAllocType(); 11175 } 11176 11177 return QualType(); 11178 } 11179 11180 /// A more selective version of E->IgnoreParenCasts for 11181 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11182 /// to change the type of E. 11183 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11184 /// 11185 /// Always returns an RValue with a pointer representation. 11186 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11187 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11188 11189 auto *NoParens = E->IgnoreParens(); 11190 auto *Cast = dyn_cast<CastExpr>(NoParens); 11191 if (Cast == nullptr) 11192 return NoParens; 11193 11194 // We only conservatively allow a few kinds of casts, because this code is 11195 // inherently a simple solution that seeks to support the common case. 11196 auto CastKind = Cast->getCastKind(); 11197 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11198 CastKind != CK_AddressSpaceConversion) 11199 return NoParens; 11200 11201 auto *SubExpr = Cast->getSubExpr(); 11202 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11203 return NoParens; 11204 return ignorePointerCastsAndParens(SubExpr); 11205 } 11206 11207 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11208 /// record layout. e.g. 11209 /// struct { struct { int a, b; } fst, snd; } obj; 11210 /// obj.fst // no 11211 /// obj.snd // yes 11212 /// obj.fst.a // no 11213 /// obj.fst.b // no 11214 /// obj.snd.a // no 11215 /// obj.snd.b // yes 11216 /// 11217 /// Please note: this function is specialized for how __builtin_object_size 11218 /// views "objects". 11219 /// 11220 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11221 /// correct result, it will always return true. 11222 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11223 assert(!LVal.Designator.Invalid); 11224 11225 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11226 const RecordDecl *Parent = FD->getParent(); 11227 Invalid = Parent->isInvalidDecl(); 11228 if (Invalid || Parent->isUnion()) 11229 return true; 11230 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11231 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11232 }; 11233 11234 auto &Base = LVal.getLValueBase(); 11235 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11236 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11237 bool Invalid; 11238 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11239 return Invalid; 11240 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11241 for (auto *FD : IFD->chain()) { 11242 bool Invalid; 11243 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11244 return Invalid; 11245 } 11246 } 11247 } 11248 11249 unsigned I = 0; 11250 QualType BaseType = getType(Base); 11251 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11252 // If we don't know the array bound, conservatively assume we're looking at 11253 // the final array element. 11254 ++I; 11255 if (BaseType->isIncompleteArrayType()) 11256 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11257 else 11258 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11259 } 11260 11261 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11262 const auto &Entry = LVal.Designator.Entries[I]; 11263 if (BaseType->isArrayType()) { 11264 // Because __builtin_object_size treats arrays as objects, we can ignore 11265 // the index iff this is the last array in the Designator. 11266 if (I + 1 == E) 11267 return true; 11268 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11269 uint64_t Index = Entry.getAsArrayIndex(); 11270 if (Index + 1 != CAT->getSize()) 11271 return false; 11272 BaseType = CAT->getElementType(); 11273 } else if (BaseType->isAnyComplexType()) { 11274 const auto *CT = BaseType->castAs<ComplexType>(); 11275 uint64_t Index = Entry.getAsArrayIndex(); 11276 if (Index != 1) 11277 return false; 11278 BaseType = CT->getElementType(); 11279 } else if (auto *FD = getAsField(Entry)) { 11280 bool Invalid; 11281 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11282 return Invalid; 11283 BaseType = FD->getType(); 11284 } else { 11285 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11286 return false; 11287 } 11288 } 11289 return true; 11290 } 11291 11292 /// Tests to see if the LValue has a user-specified designator (that isn't 11293 /// necessarily valid). Note that this always returns 'true' if the LValue has 11294 /// an unsized array as its first designator entry, because there's currently no 11295 /// way to tell if the user typed *foo or foo[0]. 11296 static bool refersToCompleteObject(const LValue &LVal) { 11297 if (LVal.Designator.Invalid) 11298 return false; 11299 11300 if (!LVal.Designator.Entries.empty()) 11301 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11302 11303 if (!LVal.InvalidBase) 11304 return true; 11305 11306 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11307 // the LValueBase. 11308 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11309 return !E || !isa<MemberExpr>(E); 11310 } 11311 11312 /// Attempts to detect a user writing into a piece of memory that's impossible 11313 /// to figure out the size of by just using types. 11314 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11315 const SubobjectDesignator &Designator = LVal.Designator; 11316 // Notes: 11317 // - Users can only write off of the end when we have an invalid base. Invalid 11318 // bases imply we don't know where the memory came from. 11319 // - We used to be a bit more aggressive here; we'd only be conservative if 11320 // the array at the end was flexible, or if it had 0 or 1 elements. This 11321 // broke some common standard library extensions (PR30346), but was 11322 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11323 // with some sort of list. OTOH, it seems that GCC is always 11324 // conservative with the last element in structs (if it's an array), so our 11325 // current behavior is more compatible than an explicit list approach would 11326 // be. 11327 return LVal.InvalidBase && 11328 Designator.Entries.size() == Designator.MostDerivedPathLength && 11329 Designator.MostDerivedIsArrayElement && 11330 isDesignatorAtObjectEnd(Ctx, LVal); 11331 } 11332 11333 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11334 /// Fails if the conversion would cause loss of precision. 11335 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11336 CharUnits &Result) { 11337 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11338 if (Int.ugt(CharUnitsMax)) 11339 return false; 11340 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11341 return true; 11342 } 11343 11344 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11345 /// determine how many bytes exist from the beginning of the object to either 11346 /// the end of the current subobject, or the end of the object itself, depending 11347 /// on what the LValue looks like + the value of Type. 11348 /// 11349 /// If this returns false, the value of Result is undefined. 11350 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11351 unsigned Type, const LValue &LVal, 11352 CharUnits &EndOffset) { 11353 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11354 11355 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11356 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11357 return false; 11358 return HandleSizeof(Info, ExprLoc, Ty, Result); 11359 }; 11360 11361 // We want to evaluate the size of the entire object. This is a valid fallback 11362 // for when Type=1 and the designator is invalid, because we're asked for an 11363 // upper-bound. 11364 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11365 // Type=3 wants a lower bound, so we can't fall back to this. 11366 if (Type == 3 && !DetermineForCompleteObject) 11367 return false; 11368 11369 llvm::APInt APEndOffset; 11370 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11371 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11372 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11373 11374 if (LVal.InvalidBase) 11375 return false; 11376 11377 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11378 return CheckedHandleSizeof(BaseTy, EndOffset); 11379 } 11380 11381 // We want to evaluate the size of a subobject. 11382 const SubobjectDesignator &Designator = LVal.Designator; 11383 11384 // The following is a moderately common idiom in C: 11385 // 11386 // struct Foo { int a; char c[1]; }; 11387 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11388 // strcpy(&F->c[0], Bar); 11389 // 11390 // In order to not break too much legacy code, we need to support it. 11391 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11392 // If we can resolve this to an alloc_size call, we can hand that back, 11393 // because we know for certain how many bytes there are to write to. 11394 llvm::APInt APEndOffset; 11395 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11396 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11397 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11398 11399 // If we cannot determine the size of the initial allocation, then we can't 11400 // given an accurate upper-bound. However, we are still able to give 11401 // conservative lower-bounds for Type=3. 11402 if (Type == 1) 11403 return false; 11404 } 11405 11406 CharUnits BytesPerElem; 11407 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11408 return false; 11409 11410 // According to the GCC documentation, we want the size of the subobject 11411 // denoted by the pointer. But that's not quite right -- what we actually 11412 // want is the size of the immediately-enclosing array, if there is one. 11413 int64_t ElemsRemaining; 11414 if (Designator.MostDerivedIsArrayElement && 11415 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11416 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11417 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11418 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11419 } else { 11420 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11421 } 11422 11423 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11424 return true; 11425 } 11426 11427 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11428 /// returns true and stores the result in @p Size. 11429 /// 11430 /// If @p WasError is non-null, this will report whether the failure to evaluate 11431 /// is to be treated as an Error in IntExprEvaluator. 11432 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11433 EvalInfo &Info, uint64_t &Size) { 11434 // Determine the denoted object. 11435 LValue LVal; 11436 { 11437 // The operand of __builtin_object_size is never evaluated for side-effects. 11438 // If there are any, but we can determine the pointed-to object anyway, then 11439 // ignore the side-effects. 11440 SpeculativeEvaluationRAII SpeculativeEval(Info); 11441 IgnoreSideEffectsRAII Fold(Info); 11442 11443 if (E->isGLValue()) { 11444 // It's possible for us to be given GLValues if we're called via 11445 // Expr::tryEvaluateObjectSize. 11446 APValue RVal; 11447 if (!EvaluateAsRValue(Info, E, RVal)) 11448 return false; 11449 LVal.setFrom(Info.Ctx, RVal); 11450 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11451 /*InvalidBaseOK=*/true)) 11452 return false; 11453 } 11454 11455 // If we point to before the start of the object, there are no accessible 11456 // bytes. 11457 if (LVal.getLValueOffset().isNegative()) { 11458 Size = 0; 11459 return true; 11460 } 11461 11462 CharUnits EndOffset; 11463 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11464 return false; 11465 11466 // If we've fallen outside of the end offset, just pretend there's nothing to 11467 // write to/read from. 11468 if (EndOffset <= LVal.getLValueOffset()) 11469 Size = 0; 11470 else 11471 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11472 return true; 11473 } 11474 11475 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11476 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11477 return VisitBuiltinCallExpr(E, BuiltinOp); 11478 11479 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11480 } 11481 11482 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11483 APValue &Val, APSInt &Alignment) { 11484 QualType SrcTy = E->getArg(0)->getType(); 11485 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11486 return false; 11487 // Even though we are evaluating integer expressions we could get a pointer 11488 // argument for the __builtin_is_aligned() case. 11489 if (SrcTy->isPointerType()) { 11490 LValue Ptr; 11491 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11492 return false; 11493 Ptr.moveInto(Val); 11494 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11495 Info.FFDiag(E->getArg(0)); 11496 return false; 11497 } else { 11498 APSInt SrcInt; 11499 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11500 return false; 11501 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11502 "Bit widths must be the same"); 11503 Val = APValue(SrcInt); 11504 } 11505 assert(Val.hasValue()); 11506 return true; 11507 } 11508 11509 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11510 unsigned BuiltinOp) { 11511 switch (BuiltinOp) { 11512 default: 11513 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11514 11515 case Builtin::BI__builtin_dynamic_object_size: 11516 case Builtin::BI__builtin_object_size: { 11517 // The type was checked when we built the expression. 11518 unsigned Type = 11519 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11520 assert(Type <= 3 && "unexpected type"); 11521 11522 uint64_t Size; 11523 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11524 return Success(Size, E); 11525 11526 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11527 return Success((Type & 2) ? 0 : -1, E); 11528 11529 // Expression had no side effects, but we couldn't statically determine the 11530 // size of the referenced object. 11531 switch (Info.EvalMode) { 11532 case EvalInfo::EM_ConstantExpression: 11533 case EvalInfo::EM_ConstantFold: 11534 case EvalInfo::EM_IgnoreSideEffects: 11535 // Leave it to IR generation. 11536 return Error(E); 11537 case EvalInfo::EM_ConstantExpressionUnevaluated: 11538 // Reduce it to a constant now. 11539 return Success((Type & 2) ? 0 : -1, E); 11540 } 11541 11542 llvm_unreachable("unexpected EvalMode"); 11543 } 11544 11545 case Builtin::BI__builtin_os_log_format_buffer_size: { 11546 analyze_os_log::OSLogBufferLayout Layout; 11547 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11548 return Success(Layout.size().getQuantity(), E); 11549 } 11550 11551 case Builtin::BI__builtin_is_aligned: { 11552 APValue Src; 11553 APSInt Alignment; 11554 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11555 return false; 11556 if (Src.isLValue()) { 11557 // If we evaluated a pointer, check the minimum known alignment. 11558 LValue Ptr; 11559 Ptr.setFrom(Info.Ctx, Src); 11560 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11561 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11562 // We can return true if the known alignment at the computed offset is 11563 // greater than the requested alignment. 11564 assert(PtrAlign.isPowerOfTwo()); 11565 assert(Alignment.isPowerOf2()); 11566 if (PtrAlign.getQuantity() >= Alignment) 11567 return Success(1, E); 11568 // If the alignment is not known to be sufficient, some cases could still 11569 // be aligned at run time. However, if the requested alignment is less or 11570 // equal to the base alignment and the offset is not aligned, we know that 11571 // the run-time value can never be aligned. 11572 if (BaseAlignment.getQuantity() >= Alignment && 11573 PtrAlign.getQuantity() < Alignment) 11574 return Success(0, E); 11575 // Otherwise we can't infer whether the value is sufficiently aligned. 11576 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11577 // in cases where we can't fully evaluate the pointer. 11578 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11579 << Alignment; 11580 return false; 11581 } 11582 assert(Src.isInt()); 11583 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11584 } 11585 case Builtin::BI__builtin_align_up: { 11586 APValue Src; 11587 APSInt Alignment; 11588 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11589 return false; 11590 if (!Src.isInt()) 11591 return Error(E); 11592 APSInt AlignedVal = 11593 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11594 Src.getInt().isUnsigned()); 11595 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11596 return Success(AlignedVal, E); 11597 } 11598 case Builtin::BI__builtin_align_down: { 11599 APValue Src; 11600 APSInt Alignment; 11601 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11602 return false; 11603 if (!Src.isInt()) 11604 return Error(E); 11605 APSInt AlignedVal = 11606 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11607 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11608 return Success(AlignedVal, E); 11609 } 11610 11611 case Builtin::BI__builtin_bitreverse8: 11612 case Builtin::BI__builtin_bitreverse16: 11613 case Builtin::BI__builtin_bitreverse32: 11614 case Builtin::BI__builtin_bitreverse64: { 11615 APSInt Val; 11616 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11617 return false; 11618 11619 return Success(Val.reverseBits(), E); 11620 } 11621 11622 case Builtin::BI__builtin_bswap16: 11623 case Builtin::BI__builtin_bswap32: 11624 case Builtin::BI__builtin_bswap64: { 11625 APSInt Val; 11626 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11627 return false; 11628 11629 return Success(Val.byteSwap(), E); 11630 } 11631 11632 case Builtin::BI__builtin_classify_type: 11633 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11634 11635 case Builtin::BI__builtin_clrsb: 11636 case Builtin::BI__builtin_clrsbl: 11637 case Builtin::BI__builtin_clrsbll: { 11638 APSInt Val; 11639 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11640 return false; 11641 11642 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11643 } 11644 11645 case Builtin::BI__builtin_clz: 11646 case Builtin::BI__builtin_clzl: 11647 case Builtin::BI__builtin_clzll: 11648 case Builtin::BI__builtin_clzs: { 11649 APSInt Val; 11650 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11651 return false; 11652 if (!Val) 11653 return Error(E); 11654 11655 return Success(Val.countLeadingZeros(), E); 11656 } 11657 11658 case Builtin::BI__builtin_constant_p: { 11659 const Expr *Arg = E->getArg(0); 11660 if (EvaluateBuiltinConstantP(Info, Arg)) 11661 return Success(true, E); 11662 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11663 // Outside a constant context, eagerly evaluate to false in the presence 11664 // of side-effects in order to avoid -Wunsequenced false-positives in 11665 // a branch on __builtin_constant_p(expr). 11666 return Success(false, E); 11667 } 11668 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11669 return false; 11670 } 11671 11672 case Builtin::BI__builtin_is_constant_evaluated: { 11673 const auto *Callee = Info.CurrentCall->getCallee(); 11674 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11675 (Info.CallStackDepth == 1 || 11676 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11677 Callee->getIdentifier() && 11678 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11679 // FIXME: Find a better way to avoid duplicated diagnostics. 11680 if (Info.EvalStatus.Diag) 11681 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11682 : Info.CurrentCall->CallLoc, 11683 diag::warn_is_constant_evaluated_always_true_constexpr) 11684 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11685 : "std::is_constant_evaluated"); 11686 } 11687 11688 return Success(Info.InConstantContext, E); 11689 } 11690 11691 case Builtin::BI__builtin_ctz: 11692 case Builtin::BI__builtin_ctzl: 11693 case Builtin::BI__builtin_ctzll: 11694 case Builtin::BI__builtin_ctzs: { 11695 APSInt Val; 11696 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11697 return false; 11698 if (!Val) 11699 return Error(E); 11700 11701 return Success(Val.countTrailingZeros(), E); 11702 } 11703 11704 case Builtin::BI__builtin_eh_return_data_regno: { 11705 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11706 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11707 return Success(Operand, E); 11708 } 11709 11710 case Builtin::BI__builtin_expect: 11711 case Builtin::BI__builtin_expect_with_probability: 11712 return Visit(E->getArg(0)); 11713 11714 case Builtin::BI__builtin_ffs: 11715 case Builtin::BI__builtin_ffsl: 11716 case Builtin::BI__builtin_ffsll: { 11717 APSInt Val; 11718 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11719 return false; 11720 11721 unsigned N = Val.countTrailingZeros(); 11722 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11723 } 11724 11725 case Builtin::BI__builtin_fpclassify: { 11726 APFloat Val(0.0); 11727 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11728 return false; 11729 unsigned Arg; 11730 switch (Val.getCategory()) { 11731 case APFloat::fcNaN: Arg = 0; break; 11732 case APFloat::fcInfinity: Arg = 1; break; 11733 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11734 case APFloat::fcZero: Arg = 4; break; 11735 } 11736 return Visit(E->getArg(Arg)); 11737 } 11738 11739 case Builtin::BI__builtin_isinf_sign: { 11740 APFloat Val(0.0); 11741 return EvaluateFloat(E->getArg(0), Val, Info) && 11742 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11743 } 11744 11745 case Builtin::BI__builtin_isinf: { 11746 APFloat Val(0.0); 11747 return EvaluateFloat(E->getArg(0), Val, Info) && 11748 Success(Val.isInfinity() ? 1 : 0, E); 11749 } 11750 11751 case Builtin::BI__builtin_isfinite: { 11752 APFloat Val(0.0); 11753 return EvaluateFloat(E->getArg(0), Val, Info) && 11754 Success(Val.isFinite() ? 1 : 0, E); 11755 } 11756 11757 case Builtin::BI__builtin_isnan: { 11758 APFloat Val(0.0); 11759 return EvaluateFloat(E->getArg(0), Val, Info) && 11760 Success(Val.isNaN() ? 1 : 0, E); 11761 } 11762 11763 case Builtin::BI__builtin_isnormal: { 11764 APFloat Val(0.0); 11765 return EvaluateFloat(E->getArg(0), Val, Info) && 11766 Success(Val.isNormal() ? 1 : 0, E); 11767 } 11768 11769 case Builtin::BI__builtin_parity: 11770 case Builtin::BI__builtin_parityl: 11771 case Builtin::BI__builtin_parityll: { 11772 APSInt Val; 11773 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11774 return false; 11775 11776 return Success(Val.countPopulation() % 2, E); 11777 } 11778 11779 case Builtin::BI__builtin_popcount: 11780 case Builtin::BI__builtin_popcountl: 11781 case Builtin::BI__builtin_popcountll: { 11782 APSInt Val; 11783 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11784 return false; 11785 11786 return Success(Val.countPopulation(), E); 11787 } 11788 11789 case Builtin::BI__builtin_rotateleft8: 11790 case Builtin::BI__builtin_rotateleft16: 11791 case Builtin::BI__builtin_rotateleft32: 11792 case Builtin::BI__builtin_rotateleft64: 11793 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11794 case Builtin::BI_rotl16: 11795 case Builtin::BI_rotl: 11796 case Builtin::BI_lrotl: 11797 case Builtin::BI_rotl64: { 11798 APSInt Val, Amt; 11799 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11800 !EvaluateInteger(E->getArg(1), Amt, Info)) 11801 return false; 11802 11803 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11804 } 11805 11806 case Builtin::BI__builtin_rotateright8: 11807 case Builtin::BI__builtin_rotateright16: 11808 case Builtin::BI__builtin_rotateright32: 11809 case Builtin::BI__builtin_rotateright64: 11810 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11811 case Builtin::BI_rotr16: 11812 case Builtin::BI_rotr: 11813 case Builtin::BI_lrotr: 11814 case Builtin::BI_rotr64: { 11815 APSInt Val, Amt; 11816 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11817 !EvaluateInteger(E->getArg(1), Amt, Info)) 11818 return false; 11819 11820 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11821 } 11822 11823 case Builtin::BIstrlen: 11824 case Builtin::BIwcslen: 11825 // A call to strlen is not a constant expression. 11826 if (Info.getLangOpts().CPlusPlus11) 11827 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11828 << /*isConstexpr*/0 << /*isConstructor*/0 11829 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11830 else 11831 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11832 LLVM_FALLTHROUGH; 11833 case Builtin::BI__builtin_strlen: 11834 case Builtin::BI__builtin_wcslen: { 11835 // As an extension, we support __builtin_strlen() as a constant expression, 11836 // and support folding strlen() to a constant. 11837 LValue String; 11838 if (!EvaluatePointer(E->getArg(0), String, Info)) 11839 return false; 11840 11841 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11842 11843 // Fast path: if it's a string literal, search the string value. 11844 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11845 String.getLValueBase().dyn_cast<const Expr *>())) { 11846 // The string literal may have embedded null characters. Find the first 11847 // one and truncate there. 11848 StringRef Str = S->getBytes(); 11849 int64_t Off = String.Offset.getQuantity(); 11850 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11851 S->getCharByteWidth() == 1 && 11852 // FIXME: Add fast-path for wchar_t too. 11853 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11854 Str = Str.substr(Off); 11855 11856 StringRef::size_type Pos = Str.find(0); 11857 if (Pos != StringRef::npos) 11858 Str = Str.substr(0, Pos); 11859 11860 return Success(Str.size(), E); 11861 } 11862 11863 // Fall through to slow path to issue appropriate diagnostic. 11864 } 11865 11866 // Slow path: scan the bytes of the string looking for the terminating 0. 11867 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11868 APValue Char; 11869 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11870 !Char.isInt()) 11871 return false; 11872 if (!Char.getInt()) 11873 return Success(Strlen, E); 11874 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11875 return false; 11876 } 11877 } 11878 11879 case Builtin::BIstrcmp: 11880 case Builtin::BIwcscmp: 11881 case Builtin::BIstrncmp: 11882 case Builtin::BIwcsncmp: 11883 case Builtin::BImemcmp: 11884 case Builtin::BIbcmp: 11885 case Builtin::BIwmemcmp: 11886 // A call to strlen is not a constant expression. 11887 if (Info.getLangOpts().CPlusPlus11) 11888 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11889 << /*isConstexpr*/0 << /*isConstructor*/0 11890 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11891 else 11892 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11893 LLVM_FALLTHROUGH; 11894 case Builtin::BI__builtin_strcmp: 11895 case Builtin::BI__builtin_wcscmp: 11896 case Builtin::BI__builtin_strncmp: 11897 case Builtin::BI__builtin_wcsncmp: 11898 case Builtin::BI__builtin_memcmp: 11899 case Builtin::BI__builtin_bcmp: 11900 case Builtin::BI__builtin_wmemcmp: { 11901 LValue String1, String2; 11902 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11903 !EvaluatePointer(E->getArg(1), String2, Info)) 11904 return false; 11905 11906 uint64_t MaxLength = uint64_t(-1); 11907 if (BuiltinOp != Builtin::BIstrcmp && 11908 BuiltinOp != Builtin::BIwcscmp && 11909 BuiltinOp != Builtin::BI__builtin_strcmp && 11910 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11911 APSInt N; 11912 if (!EvaluateInteger(E->getArg(2), N, Info)) 11913 return false; 11914 MaxLength = N.getExtValue(); 11915 } 11916 11917 // Empty substrings compare equal by definition. 11918 if (MaxLength == 0u) 11919 return Success(0, E); 11920 11921 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11922 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11923 String1.Designator.Invalid || String2.Designator.Invalid) 11924 return false; 11925 11926 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11927 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11928 11929 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11930 BuiltinOp == Builtin::BIbcmp || 11931 BuiltinOp == Builtin::BI__builtin_memcmp || 11932 BuiltinOp == Builtin::BI__builtin_bcmp; 11933 11934 assert(IsRawByte || 11935 (Info.Ctx.hasSameUnqualifiedType( 11936 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11937 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11938 11939 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11940 // 'char8_t', but no other types. 11941 if (IsRawByte && 11942 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11943 // FIXME: Consider using our bit_cast implementation to support this. 11944 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11945 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11946 << CharTy1 << CharTy2; 11947 return false; 11948 } 11949 11950 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11951 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11952 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11953 Char1.isInt() && Char2.isInt(); 11954 }; 11955 const auto &AdvanceElems = [&] { 11956 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11957 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11958 }; 11959 11960 bool StopAtNull = 11961 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11962 BuiltinOp != Builtin::BIwmemcmp && 11963 BuiltinOp != Builtin::BI__builtin_memcmp && 11964 BuiltinOp != Builtin::BI__builtin_bcmp && 11965 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11966 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11967 BuiltinOp == Builtin::BIwcsncmp || 11968 BuiltinOp == Builtin::BIwmemcmp || 11969 BuiltinOp == Builtin::BI__builtin_wcscmp || 11970 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11971 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11972 11973 for (; MaxLength; --MaxLength) { 11974 APValue Char1, Char2; 11975 if (!ReadCurElems(Char1, Char2)) 11976 return false; 11977 if (Char1.getInt().ne(Char2.getInt())) { 11978 if (IsWide) // wmemcmp compares with wchar_t signedness. 11979 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11980 // memcmp always compares unsigned chars. 11981 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11982 } 11983 if (StopAtNull && !Char1.getInt()) 11984 return Success(0, E); 11985 assert(!(StopAtNull && !Char2.getInt())); 11986 if (!AdvanceElems()) 11987 return false; 11988 } 11989 // We hit the strncmp / memcmp limit. 11990 return Success(0, E); 11991 } 11992 11993 case Builtin::BI__atomic_always_lock_free: 11994 case Builtin::BI__atomic_is_lock_free: 11995 case Builtin::BI__c11_atomic_is_lock_free: { 11996 APSInt SizeVal; 11997 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11998 return false; 11999 12000 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 12001 // of two less than or equal to the maximum inline atomic width, we know it 12002 // is lock-free. If the size isn't a power of two, or greater than the 12003 // maximum alignment where we promote atomics, we know it is not lock-free 12004 // (at least not in the sense of atomic_is_lock_free). Otherwise, 12005 // the answer can only be determined at runtime; for example, 16-byte 12006 // atomics have lock-free implementations on some, but not all, 12007 // x86-64 processors. 12008 12009 // Check power-of-two. 12010 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 12011 if (Size.isPowerOfTwo()) { 12012 // Check against inlining width. 12013 unsigned InlineWidthBits = 12014 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 12015 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 12016 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 12017 Size == CharUnits::One() || 12018 E->getArg(1)->isNullPointerConstant(Info.Ctx, 12019 Expr::NPC_NeverValueDependent)) 12020 // OK, we will inline appropriately-aligned operations of this size, 12021 // and _Atomic(T) is appropriately-aligned. 12022 return Success(1, E); 12023 12024 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12025 castAs<PointerType>()->getPointeeType(); 12026 if (!PointeeType->isIncompleteType() && 12027 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12028 // OK, we will inline operations on this object. 12029 return Success(1, E); 12030 } 12031 } 12032 } 12033 12034 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12035 Success(0, E) : Error(E); 12036 } 12037 case Builtin::BI__builtin_add_overflow: 12038 case Builtin::BI__builtin_sub_overflow: 12039 case Builtin::BI__builtin_mul_overflow: 12040 case Builtin::BI__builtin_sadd_overflow: 12041 case Builtin::BI__builtin_uadd_overflow: 12042 case Builtin::BI__builtin_uaddl_overflow: 12043 case Builtin::BI__builtin_uaddll_overflow: 12044 case Builtin::BI__builtin_usub_overflow: 12045 case Builtin::BI__builtin_usubl_overflow: 12046 case Builtin::BI__builtin_usubll_overflow: 12047 case Builtin::BI__builtin_umul_overflow: 12048 case Builtin::BI__builtin_umull_overflow: 12049 case Builtin::BI__builtin_umulll_overflow: 12050 case Builtin::BI__builtin_saddl_overflow: 12051 case Builtin::BI__builtin_saddll_overflow: 12052 case Builtin::BI__builtin_ssub_overflow: 12053 case Builtin::BI__builtin_ssubl_overflow: 12054 case Builtin::BI__builtin_ssubll_overflow: 12055 case Builtin::BI__builtin_smul_overflow: 12056 case Builtin::BI__builtin_smull_overflow: 12057 case Builtin::BI__builtin_smulll_overflow: { 12058 LValue ResultLValue; 12059 APSInt LHS, RHS; 12060 12061 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12062 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12063 !EvaluateInteger(E->getArg(1), RHS, Info) || 12064 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12065 return false; 12066 12067 APSInt Result; 12068 bool DidOverflow = false; 12069 12070 // If the types don't have to match, enlarge all 3 to the largest of them. 12071 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12072 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12073 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12074 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12075 ResultType->isSignedIntegerOrEnumerationType(); 12076 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12077 ResultType->isSignedIntegerOrEnumerationType(); 12078 uint64_t LHSSize = LHS.getBitWidth(); 12079 uint64_t RHSSize = RHS.getBitWidth(); 12080 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12081 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12082 12083 // Add an additional bit if the signedness isn't uniformly agreed to. We 12084 // could do this ONLY if there is a signed and an unsigned that both have 12085 // MaxBits, but the code to check that is pretty nasty. The issue will be 12086 // caught in the shrink-to-result later anyway. 12087 if (IsSigned && !AllSigned) 12088 ++MaxBits; 12089 12090 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12091 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12092 Result = APSInt(MaxBits, !IsSigned); 12093 } 12094 12095 // Find largest int. 12096 switch (BuiltinOp) { 12097 default: 12098 llvm_unreachable("Invalid value for BuiltinOp"); 12099 case Builtin::BI__builtin_add_overflow: 12100 case Builtin::BI__builtin_sadd_overflow: 12101 case Builtin::BI__builtin_saddl_overflow: 12102 case Builtin::BI__builtin_saddll_overflow: 12103 case Builtin::BI__builtin_uadd_overflow: 12104 case Builtin::BI__builtin_uaddl_overflow: 12105 case Builtin::BI__builtin_uaddll_overflow: 12106 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12107 : LHS.uadd_ov(RHS, DidOverflow); 12108 break; 12109 case Builtin::BI__builtin_sub_overflow: 12110 case Builtin::BI__builtin_ssub_overflow: 12111 case Builtin::BI__builtin_ssubl_overflow: 12112 case Builtin::BI__builtin_ssubll_overflow: 12113 case Builtin::BI__builtin_usub_overflow: 12114 case Builtin::BI__builtin_usubl_overflow: 12115 case Builtin::BI__builtin_usubll_overflow: 12116 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12117 : LHS.usub_ov(RHS, DidOverflow); 12118 break; 12119 case Builtin::BI__builtin_mul_overflow: 12120 case Builtin::BI__builtin_smul_overflow: 12121 case Builtin::BI__builtin_smull_overflow: 12122 case Builtin::BI__builtin_smulll_overflow: 12123 case Builtin::BI__builtin_umul_overflow: 12124 case Builtin::BI__builtin_umull_overflow: 12125 case Builtin::BI__builtin_umulll_overflow: 12126 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12127 : LHS.umul_ov(RHS, DidOverflow); 12128 break; 12129 } 12130 12131 // In the case where multiple sizes are allowed, truncate and see if 12132 // the values are the same. 12133 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12134 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12135 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12136 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12137 // since it will give us the behavior of a TruncOrSelf in the case where 12138 // its parameter <= its size. We previously set Result to be at least the 12139 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12140 // will work exactly like TruncOrSelf. 12141 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12142 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12143 12144 if (!APSInt::isSameValue(Temp, Result)) 12145 DidOverflow = true; 12146 Result = Temp; 12147 } 12148 12149 APValue APV{Result}; 12150 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12151 return false; 12152 return Success(DidOverflow, E); 12153 } 12154 } 12155 } 12156 12157 /// Determine whether this is a pointer past the end of the complete 12158 /// object referred to by the lvalue. 12159 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12160 const LValue &LV) { 12161 // A null pointer can be viewed as being "past the end" but we don't 12162 // choose to look at it that way here. 12163 if (!LV.getLValueBase()) 12164 return false; 12165 12166 // If the designator is valid and refers to a subobject, we're not pointing 12167 // past the end. 12168 if (!LV.getLValueDesignator().Invalid && 12169 !LV.getLValueDesignator().isOnePastTheEnd()) 12170 return false; 12171 12172 // A pointer to an incomplete type might be past-the-end if the type's size is 12173 // zero. We cannot tell because the type is incomplete. 12174 QualType Ty = getType(LV.getLValueBase()); 12175 if (Ty->isIncompleteType()) 12176 return true; 12177 12178 // We're a past-the-end pointer if we point to the byte after the object, 12179 // no matter what our type or path is. 12180 auto Size = Ctx.getTypeSizeInChars(Ty); 12181 return LV.getLValueOffset() == Size; 12182 } 12183 12184 namespace { 12185 12186 /// Data recursive integer evaluator of certain binary operators. 12187 /// 12188 /// We use a data recursive algorithm for binary operators so that we are able 12189 /// to handle extreme cases of chained binary operators without causing stack 12190 /// overflow. 12191 class DataRecursiveIntBinOpEvaluator { 12192 struct EvalResult { 12193 APValue Val; 12194 bool Failed; 12195 12196 EvalResult() : Failed(false) { } 12197 12198 void swap(EvalResult &RHS) { 12199 Val.swap(RHS.Val); 12200 Failed = RHS.Failed; 12201 RHS.Failed = false; 12202 } 12203 }; 12204 12205 struct Job { 12206 const Expr *E; 12207 EvalResult LHSResult; // meaningful only for binary operator expression. 12208 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12209 12210 Job() = default; 12211 Job(Job &&) = default; 12212 12213 void startSpeculativeEval(EvalInfo &Info) { 12214 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12215 } 12216 12217 private: 12218 SpeculativeEvaluationRAII SpecEvalRAII; 12219 }; 12220 12221 SmallVector<Job, 16> Queue; 12222 12223 IntExprEvaluator &IntEval; 12224 EvalInfo &Info; 12225 APValue &FinalResult; 12226 12227 public: 12228 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12229 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12230 12231 /// True if \param E is a binary operator that we are going to handle 12232 /// data recursively. 12233 /// We handle binary operators that are comma, logical, or that have operands 12234 /// with integral or enumeration type. 12235 static bool shouldEnqueue(const BinaryOperator *E) { 12236 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12237 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12238 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12239 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12240 } 12241 12242 bool Traverse(const BinaryOperator *E) { 12243 enqueue(E); 12244 EvalResult PrevResult; 12245 while (!Queue.empty()) 12246 process(PrevResult); 12247 12248 if (PrevResult.Failed) return false; 12249 12250 FinalResult.swap(PrevResult.Val); 12251 return true; 12252 } 12253 12254 private: 12255 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12256 return IntEval.Success(Value, E, Result); 12257 } 12258 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12259 return IntEval.Success(Value, E, Result); 12260 } 12261 bool Error(const Expr *E) { 12262 return IntEval.Error(E); 12263 } 12264 bool Error(const Expr *E, diag::kind D) { 12265 return IntEval.Error(E, D); 12266 } 12267 12268 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12269 return Info.CCEDiag(E, D); 12270 } 12271 12272 // Returns true if visiting the RHS is necessary, false otherwise. 12273 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12274 bool &SuppressRHSDiags); 12275 12276 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12277 const BinaryOperator *E, APValue &Result); 12278 12279 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12280 Result.Failed = !Evaluate(Result.Val, Info, E); 12281 if (Result.Failed) 12282 Result.Val = APValue(); 12283 } 12284 12285 void process(EvalResult &Result); 12286 12287 void enqueue(const Expr *E) { 12288 E = E->IgnoreParens(); 12289 Queue.resize(Queue.size()+1); 12290 Queue.back().E = E; 12291 Queue.back().Kind = Job::AnyExprKind; 12292 } 12293 }; 12294 12295 } 12296 12297 bool DataRecursiveIntBinOpEvaluator:: 12298 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12299 bool &SuppressRHSDiags) { 12300 if (E->getOpcode() == BO_Comma) { 12301 // Ignore LHS but note if we could not evaluate it. 12302 if (LHSResult.Failed) 12303 return Info.noteSideEffect(); 12304 return true; 12305 } 12306 12307 if (E->isLogicalOp()) { 12308 bool LHSAsBool; 12309 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12310 // We were able to evaluate the LHS, see if we can get away with not 12311 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12312 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12313 Success(LHSAsBool, E, LHSResult.Val); 12314 return false; // Ignore RHS 12315 } 12316 } else { 12317 LHSResult.Failed = true; 12318 12319 // Since we weren't able to evaluate the left hand side, it 12320 // might have had side effects. 12321 if (!Info.noteSideEffect()) 12322 return false; 12323 12324 // We can't evaluate the LHS; however, sometimes the result 12325 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12326 // Don't ignore RHS and suppress diagnostics from this arm. 12327 SuppressRHSDiags = true; 12328 } 12329 12330 return true; 12331 } 12332 12333 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12334 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12335 12336 if (LHSResult.Failed && !Info.noteFailure()) 12337 return false; // Ignore RHS; 12338 12339 return true; 12340 } 12341 12342 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12343 bool IsSub) { 12344 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12345 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12346 // offsets. 12347 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12348 CharUnits &Offset = LVal.getLValueOffset(); 12349 uint64_t Offset64 = Offset.getQuantity(); 12350 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12351 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12352 : Offset64 + Index64); 12353 } 12354 12355 bool DataRecursiveIntBinOpEvaluator:: 12356 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12357 const BinaryOperator *E, APValue &Result) { 12358 if (E->getOpcode() == BO_Comma) { 12359 if (RHSResult.Failed) 12360 return false; 12361 Result = RHSResult.Val; 12362 return true; 12363 } 12364 12365 if (E->isLogicalOp()) { 12366 bool lhsResult, rhsResult; 12367 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12368 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12369 12370 if (LHSIsOK) { 12371 if (RHSIsOK) { 12372 if (E->getOpcode() == BO_LOr) 12373 return Success(lhsResult || rhsResult, E, Result); 12374 else 12375 return Success(lhsResult && rhsResult, E, Result); 12376 } 12377 } else { 12378 if (RHSIsOK) { 12379 // We can't evaluate the LHS; however, sometimes the result 12380 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12381 if (rhsResult == (E->getOpcode() == BO_LOr)) 12382 return Success(rhsResult, E, Result); 12383 } 12384 } 12385 12386 return false; 12387 } 12388 12389 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12390 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12391 12392 if (LHSResult.Failed || RHSResult.Failed) 12393 return false; 12394 12395 const APValue &LHSVal = LHSResult.Val; 12396 const APValue &RHSVal = RHSResult.Val; 12397 12398 // Handle cases like (unsigned long)&a + 4. 12399 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12400 Result = LHSVal; 12401 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12402 return true; 12403 } 12404 12405 // Handle cases like 4 + (unsigned long)&a 12406 if (E->getOpcode() == BO_Add && 12407 RHSVal.isLValue() && LHSVal.isInt()) { 12408 Result = RHSVal; 12409 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12410 return true; 12411 } 12412 12413 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12414 // Handle (intptr_t)&&A - (intptr_t)&&B. 12415 if (!LHSVal.getLValueOffset().isZero() || 12416 !RHSVal.getLValueOffset().isZero()) 12417 return false; 12418 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12419 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12420 if (!LHSExpr || !RHSExpr) 12421 return false; 12422 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12423 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12424 if (!LHSAddrExpr || !RHSAddrExpr) 12425 return false; 12426 // Make sure both labels come from the same function. 12427 if (LHSAddrExpr->getLabel()->getDeclContext() != 12428 RHSAddrExpr->getLabel()->getDeclContext()) 12429 return false; 12430 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12431 return true; 12432 } 12433 12434 // All the remaining cases expect both operands to be an integer 12435 if (!LHSVal.isInt() || !RHSVal.isInt()) 12436 return Error(E); 12437 12438 // Set up the width and signedness manually, in case it can't be deduced 12439 // from the operation we're performing. 12440 // FIXME: Don't do this in the cases where we can deduce it. 12441 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12442 E->getType()->isUnsignedIntegerOrEnumerationType()); 12443 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12444 RHSVal.getInt(), Value)) 12445 return false; 12446 return Success(Value, E, Result); 12447 } 12448 12449 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12450 Job &job = Queue.back(); 12451 12452 switch (job.Kind) { 12453 case Job::AnyExprKind: { 12454 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12455 if (shouldEnqueue(Bop)) { 12456 job.Kind = Job::BinOpKind; 12457 enqueue(Bop->getLHS()); 12458 return; 12459 } 12460 } 12461 12462 EvaluateExpr(job.E, Result); 12463 Queue.pop_back(); 12464 return; 12465 } 12466 12467 case Job::BinOpKind: { 12468 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12469 bool SuppressRHSDiags = false; 12470 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12471 Queue.pop_back(); 12472 return; 12473 } 12474 if (SuppressRHSDiags) 12475 job.startSpeculativeEval(Info); 12476 job.LHSResult.swap(Result); 12477 job.Kind = Job::BinOpVisitedLHSKind; 12478 enqueue(Bop->getRHS()); 12479 return; 12480 } 12481 12482 case Job::BinOpVisitedLHSKind: { 12483 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12484 EvalResult RHS; 12485 RHS.swap(Result); 12486 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12487 Queue.pop_back(); 12488 return; 12489 } 12490 } 12491 12492 llvm_unreachable("Invalid Job::Kind!"); 12493 } 12494 12495 namespace { 12496 enum class CmpResult { 12497 Unequal, 12498 Less, 12499 Equal, 12500 Greater, 12501 Unordered, 12502 }; 12503 } 12504 12505 template <class SuccessCB, class AfterCB> 12506 static bool 12507 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12508 SuccessCB &&Success, AfterCB &&DoAfter) { 12509 assert(!E->isValueDependent()); 12510 assert(E->isComparisonOp() && "expected comparison operator"); 12511 assert((E->getOpcode() == BO_Cmp || 12512 E->getType()->isIntegralOrEnumerationType()) && 12513 "unsupported binary expression evaluation"); 12514 auto Error = [&](const Expr *E) { 12515 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12516 return false; 12517 }; 12518 12519 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12520 bool IsEquality = E->isEqualityOp(); 12521 12522 QualType LHSTy = E->getLHS()->getType(); 12523 QualType RHSTy = E->getRHS()->getType(); 12524 12525 if (LHSTy->isIntegralOrEnumerationType() && 12526 RHSTy->isIntegralOrEnumerationType()) { 12527 APSInt LHS, RHS; 12528 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12529 if (!LHSOK && !Info.noteFailure()) 12530 return false; 12531 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12532 return false; 12533 if (LHS < RHS) 12534 return Success(CmpResult::Less, E); 12535 if (LHS > RHS) 12536 return Success(CmpResult::Greater, E); 12537 return Success(CmpResult::Equal, E); 12538 } 12539 12540 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12541 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12542 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12543 12544 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12545 if (!LHSOK && !Info.noteFailure()) 12546 return false; 12547 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12548 return false; 12549 if (LHSFX < RHSFX) 12550 return Success(CmpResult::Less, E); 12551 if (LHSFX > RHSFX) 12552 return Success(CmpResult::Greater, E); 12553 return Success(CmpResult::Equal, E); 12554 } 12555 12556 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12557 ComplexValue LHS, RHS; 12558 bool LHSOK; 12559 if (E->isAssignmentOp()) { 12560 LValue LV; 12561 EvaluateLValue(E->getLHS(), LV, Info); 12562 LHSOK = false; 12563 } else if (LHSTy->isRealFloatingType()) { 12564 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12565 if (LHSOK) { 12566 LHS.makeComplexFloat(); 12567 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12568 } 12569 } else { 12570 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12571 } 12572 if (!LHSOK && !Info.noteFailure()) 12573 return false; 12574 12575 if (E->getRHS()->getType()->isRealFloatingType()) { 12576 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12577 return false; 12578 RHS.makeComplexFloat(); 12579 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12580 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12581 return false; 12582 12583 if (LHS.isComplexFloat()) { 12584 APFloat::cmpResult CR_r = 12585 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12586 APFloat::cmpResult CR_i = 12587 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12588 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12589 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12590 } else { 12591 assert(IsEquality && "invalid complex comparison"); 12592 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12593 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12594 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12595 } 12596 } 12597 12598 if (LHSTy->isRealFloatingType() && 12599 RHSTy->isRealFloatingType()) { 12600 APFloat RHS(0.0), LHS(0.0); 12601 12602 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12603 if (!LHSOK && !Info.noteFailure()) 12604 return false; 12605 12606 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12607 return false; 12608 12609 assert(E->isComparisonOp() && "Invalid binary operator!"); 12610 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12611 if (!Info.InConstantContext && 12612 APFloatCmpResult == APFloat::cmpUnordered && 12613 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12614 // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12615 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12616 return false; 12617 } 12618 auto GetCmpRes = [&]() { 12619 switch (APFloatCmpResult) { 12620 case APFloat::cmpEqual: 12621 return CmpResult::Equal; 12622 case APFloat::cmpLessThan: 12623 return CmpResult::Less; 12624 case APFloat::cmpGreaterThan: 12625 return CmpResult::Greater; 12626 case APFloat::cmpUnordered: 12627 return CmpResult::Unordered; 12628 } 12629 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12630 }; 12631 return Success(GetCmpRes(), E); 12632 } 12633 12634 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12635 LValue LHSValue, RHSValue; 12636 12637 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12638 if (!LHSOK && !Info.noteFailure()) 12639 return false; 12640 12641 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12642 return false; 12643 12644 // Reject differing bases from the normal codepath; we special-case 12645 // comparisons to null. 12646 if (!HasSameBase(LHSValue, RHSValue)) { 12647 // Inequalities and subtractions between unrelated pointers have 12648 // unspecified or undefined behavior. 12649 if (!IsEquality) { 12650 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12651 return false; 12652 } 12653 // A constant address may compare equal to the address of a symbol. 12654 // The one exception is that address of an object cannot compare equal 12655 // to a null pointer constant. 12656 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12657 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12658 return Error(E); 12659 // It's implementation-defined whether distinct literals will have 12660 // distinct addresses. In clang, the result of such a comparison is 12661 // unspecified, so it is not a constant expression. However, we do know 12662 // that the address of a literal will be non-null. 12663 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12664 LHSValue.Base && RHSValue.Base) 12665 return Error(E); 12666 // We can't tell whether weak symbols will end up pointing to the same 12667 // object. 12668 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12669 return Error(E); 12670 // We can't compare the address of the start of one object with the 12671 // past-the-end address of another object, per C++ DR1652. 12672 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12673 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12674 (RHSValue.Base && RHSValue.Offset.isZero() && 12675 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12676 return Error(E); 12677 // We can't tell whether an object is at the same address as another 12678 // zero sized object. 12679 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12680 (LHSValue.Base && isZeroSized(RHSValue))) 12681 return Error(E); 12682 return Success(CmpResult::Unequal, E); 12683 } 12684 12685 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12686 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12687 12688 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12689 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12690 12691 // C++11 [expr.rel]p3: 12692 // Pointers to void (after pointer conversions) can be compared, with a 12693 // result defined as follows: If both pointers represent the same 12694 // address or are both the null pointer value, the result is true if the 12695 // operator is <= or >= and false otherwise; otherwise the result is 12696 // unspecified. 12697 // We interpret this as applying to pointers to *cv* void. 12698 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12699 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12700 12701 // C++11 [expr.rel]p2: 12702 // - If two pointers point to non-static data members of the same object, 12703 // or to subobjects or array elements fo such members, recursively, the 12704 // pointer to the later declared member compares greater provided the 12705 // two members have the same access control and provided their class is 12706 // not a union. 12707 // [...] 12708 // - Otherwise pointer comparisons are unspecified. 12709 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12710 bool WasArrayIndex; 12711 unsigned Mismatch = FindDesignatorMismatch( 12712 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12713 // At the point where the designators diverge, the comparison has a 12714 // specified value if: 12715 // - we are comparing array indices 12716 // - we are comparing fields of a union, or fields with the same access 12717 // Otherwise, the result is unspecified and thus the comparison is not a 12718 // constant expression. 12719 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12720 Mismatch < RHSDesignator.Entries.size()) { 12721 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12722 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12723 if (!LF && !RF) 12724 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12725 else if (!LF) 12726 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12727 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12728 << RF->getParent() << RF; 12729 else if (!RF) 12730 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12731 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12732 << LF->getParent() << LF; 12733 else if (!LF->getParent()->isUnion() && 12734 LF->getAccess() != RF->getAccess()) 12735 Info.CCEDiag(E, 12736 diag::note_constexpr_pointer_comparison_differing_access) 12737 << LF << LF->getAccess() << RF << RF->getAccess() 12738 << LF->getParent(); 12739 } 12740 } 12741 12742 // The comparison here must be unsigned, and performed with the same 12743 // width as the pointer. 12744 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12745 uint64_t CompareLHS = LHSOffset.getQuantity(); 12746 uint64_t CompareRHS = RHSOffset.getQuantity(); 12747 assert(PtrSize <= 64 && "Unexpected pointer width"); 12748 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12749 CompareLHS &= Mask; 12750 CompareRHS &= Mask; 12751 12752 // If there is a base and this is a relational operator, we can only 12753 // compare pointers within the object in question; otherwise, the result 12754 // depends on where the object is located in memory. 12755 if (!LHSValue.Base.isNull() && IsRelational) { 12756 QualType BaseTy = getType(LHSValue.Base); 12757 if (BaseTy->isIncompleteType()) 12758 return Error(E); 12759 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12760 uint64_t OffsetLimit = Size.getQuantity(); 12761 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12762 return Error(E); 12763 } 12764 12765 if (CompareLHS < CompareRHS) 12766 return Success(CmpResult::Less, E); 12767 if (CompareLHS > CompareRHS) 12768 return Success(CmpResult::Greater, E); 12769 return Success(CmpResult::Equal, E); 12770 } 12771 12772 if (LHSTy->isMemberPointerType()) { 12773 assert(IsEquality && "unexpected member pointer operation"); 12774 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12775 12776 MemberPtr LHSValue, RHSValue; 12777 12778 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12779 if (!LHSOK && !Info.noteFailure()) 12780 return false; 12781 12782 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12783 return false; 12784 12785 // C++11 [expr.eq]p2: 12786 // If both operands are null, they compare equal. Otherwise if only one is 12787 // null, they compare unequal. 12788 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12789 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12790 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12791 } 12792 12793 // Otherwise if either is a pointer to a virtual member function, the 12794 // result is unspecified. 12795 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12796 if (MD->isVirtual()) 12797 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12798 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12799 if (MD->isVirtual()) 12800 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12801 12802 // Otherwise they compare equal if and only if they would refer to the 12803 // same member of the same most derived object or the same subobject if 12804 // they were dereferenced with a hypothetical object of the associated 12805 // class type. 12806 bool Equal = LHSValue == RHSValue; 12807 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12808 } 12809 12810 if (LHSTy->isNullPtrType()) { 12811 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12812 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12813 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12814 // are compared, the result is true of the operator is <=, >= or ==, and 12815 // false otherwise. 12816 return Success(CmpResult::Equal, E); 12817 } 12818 12819 return DoAfter(); 12820 } 12821 12822 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12823 if (!CheckLiteralType(Info, E)) 12824 return false; 12825 12826 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12827 ComparisonCategoryResult CCR; 12828 switch (CR) { 12829 case CmpResult::Unequal: 12830 llvm_unreachable("should never produce Unequal for three-way comparison"); 12831 case CmpResult::Less: 12832 CCR = ComparisonCategoryResult::Less; 12833 break; 12834 case CmpResult::Equal: 12835 CCR = ComparisonCategoryResult::Equal; 12836 break; 12837 case CmpResult::Greater: 12838 CCR = ComparisonCategoryResult::Greater; 12839 break; 12840 case CmpResult::Unordered: 12841 CCR = ComparisonCategoryResult::Unordered; 12842 break; 12843 } 12844 // Evaluation succeeded. Lookup the information for the comparison category 12845 // type and fetch the VarDecl for the result. 12846 const ComparisonCategoryInfo &CmpInfo = 12847 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12848 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12849 // Check and evaluate the result as a constant expression. 12850 LValue LV; 12851 LV.set(VD); 12852 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12853 return false; 12854 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12855 ConstantExprKind::Normal); 12856 }; 12857 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12858 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12859 }); 12860 } 12861 12862 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12863 // We don't support assignment in C. C++ assignments don't get here because 12864 // assignment is an lvalue in C++. 12865 if (E->isAssignmentOp()) { 12866 Error(E); 12867 if (!Info.noteFailure()) 12868 return false; 12869 } 12870 12871 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12872 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12873 12874 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12875 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12876 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12877 12878 if (E->isComparisonOp()) { 12879 // Evaluate builtin binary comparisons by evaluating them as three-way 12880 // comparisons and then translating the result. 12881 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12882 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12883 "should only produce Unequal for equality comparisons"); 12884 bool IsEqual = CR == CmpResult::Equal, 12885 IsLess = CR == CmpResult::Less, 12886 IsGreater = CR == CmpResult::Greater; 12887 auto Op = E->getOpcode(); 12888 switch (Op) { 12889 default: 12890 llvm_unreachable("unsupported binary operator"); 12891 case BO_EQ: 12892 case BO_NE: 12893 return Success(IsEqual == (Op == BO_EQ), E); 12894 case BO_LT: 12895 return Success(IsLess, E); 12896 case BO_GT: 12897 return Success(IsGreater, E); 12898 case BO_LE: 12899 return Success(IsEqual || IsLess, E); 12900 case BO_GE: 12901 return Success(IsEqual || IsGreater, E); 12902 } 12903 }; 12904 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12905 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12906 }); 12907 } 12908 12909 QualType LHSTy = E->getLHS()->getType(); 12910 QualType RHSTy = E->getRHS()->getType(); 12911 12912 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12913 E->getOpcode() == BO_Sub) { 12914 LValue LHSValue, RHSValue; 12915 12916 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12917 if (!LHSOK && !Info.noteFailure()) 12918 return false; 12919 12920 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12921 return false; 12922 12923 // Reject differing bases from the normal codepath; we special-case 12924 // comparisons to null. 12925 if (!HasSameBase(LHSValue, RHSValue)) { 12926 // Handle &&A - &&B. 12927 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12928 return Error(E); 12929 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12930 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12931 if (!LHSExpr || !RHSExpr) 12932 return Error(E); 12933 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12934 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12935 if (!LHSAddrExpr || !RHSAddrExpr) 12936 return Error(E); 12937 // Make sure both labels come from the same function. 12938 if (LHSAddrExpr->getLabel()->getDeclContext() != 12939 RHSAddrExpr->getLabel()->getDeclContext()) 12940 return Error(E); 12941 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12942 } 12943 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12944 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12945 12946 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12947 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12948 12949 // C++11 [expr.add]p6: 12950 // Unless both pointers point to elements of the same array object, or 12951 // one past the last element of the array object, the behavior is 12952 // undefined. 12953 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12954 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12955 RHSDesignator)) 12956 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12957 12958 QualType Type = E->getLHS()->getType(); 12959 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12960 12961 CharUnits ElementSize; 12962 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12963 return false; 12964 12965 // As an extension, a type may have zero size (empty struct or union in 12966 // C, array of zero length). Pointer subtraction in such cases has 12967 // undefined behavior, so is not constant. 12968 if (ElementSize.isZero()) { 12969 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12970 << ElementType; 12971 return false; 12972 } 12973 12974 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12975 // and produce incorrect results when it overflows. Such behavior 12976 // appears to be non-conforming, but is common, so perhaps we should 12977 // assume the standard intended for such cases to be undefined behavior 12978 // and check for them. 12979 12980 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12981 // overflow in the final conversion to ptrdiff_t. 12982 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12983 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12984 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12985 false); 12986 APSInt TrueResult = (LHS - RHS) / ElemSize; 12987 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12988 12989 if (Result.extend(65) != TrueResult && 12990 !HandleOverflow(Info, E, TrueResult, E->getType())) 12991 return false; 12992 return Success(Result, E); 12993 } 12994 12995 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12996 } 12997 12998 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12999 /// a result as the expression's type. 13000 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 13001 const UnaryExprOrTypeTraitExpr *E) { 13002 switch(E->getKind()) { 13003 case UETT_PreferredAlignOf: 13004 case UETT_AlignOf: { 13005 if (E->isArgumentType()) 13006 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 13007 E); 13008 else 13009 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 13010 E); 13011 } 13012 13013 case UETT_VecStep: { 13014 QualType Ty = E->getTypeOfArgument(); 13015 13016 if (Ty->isVectorType()) { 13017 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 13018 13019 // The vec_step built-in functions that take a 3-component 13020 // vector return 4. (OpenCL 1.1 spec 6.11.12) 13021 if (n == 3) 13022 n = 4; 13023 13024 return Success(n, E); 13025 } else 13026 return Success(1, E); 13027 } 13028 13029 case UETT_SizeOf: { 13030 QualType SrcTy = E->getTypeOfArgument(); 13031 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13032 // the result is the size of the referenced type." 13033 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13034 SrcTy = Ref->getPointeeType(); 13035 13036 CharUnits Sizeof; 13037 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13038 return false; 13039 return Success(Sizeof, E); 13040 } 13041 case UETT_OpenMPRequiredSimdAlign: 13042 assert(E->isArgumentType()); 13043 return Success( 13044 Info.Ctx.toCharUnitsFromBits( 13045 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13046 .getQuantity(), 13047 E); 13048 } 13049 13050 llvm_unreachable("unknown expr/type trait"); 13051 } 13052 13053 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13054 CharUnits Result; 13055 unsigned n = OOE->getNumComponents(); 13056 if (n == 0) 13057 return Error(OOE); 13058 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13059 for (unsigned i = 0; i != n; ++i) { 13060 OffsetOfNode ON = OOE->getComponent(i); 13061 switch (ON.getKind()) { 13062 case OffsetOfNode::Array: { 13063 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13064 APSInt IdxResult; 13065 if (!EvaluateInteger(Idx, IdxResult, Info)) 13066 return false; 13067 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13068 if (!AT) 13069 return Error(OOE); 13070 CurrentType = AT->getElementType(); 13071 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13072 Result += IdxResult.getSExtValue() * ElementSize; 13073 break; 13074 } 13075 13076 case OffsetOfNode::Field: { 13077 FieldDecl *MemberDecl = ON.getField(); 13078 const RecordType *RT = CurrentType->getAs<RecordType>(); 13079 if (!RT) 13080 return Error(OOE); 13081 RecordDecl *RD = RT->getDecl(); 13082 if (RD->isInvalidDecl()) return false; 13083 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13084 unsigned i = MemberDecl->getFieldIndex(); 13085 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13086 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13087 CurrentType = MemberDecl->getType().getNonReferenceType(); 13088 break; 13089 } 13090 13091 case OffsetOfNode::Identifier: 13092 llvm_unreachable("dependent __builtin_offsetof"); 13093 13094 case OffsetOfNode::Base: { 13095 CXXBaseSpecifier *BaseSpec = ON.getBase(); 13096 if (BaseSpec->isVirtual()) 13097 return Error(OOE); 13098 13099 // Find the layout of the class whose base we are looking into. 13100 const RecordType *RT = CurrentType->getAs<RecordType>(); 13101 if (!RT) 13102 return Error(OOE); 13103 RecordDecl *RD = RT->getDecl(); 13104 if (RD->isInvalidDecl()) return false; 13105 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13106 13107 // Find the base class itself. 13108 CurrentType = BaseSpec->getType(); 13109 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13110 if (!BaseRT) 13111 return Error(OOE); 13112 13113 // Add the offset to the base. 13114 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13115 break; 13116 } 13117 } 13118 } 13119 return Success(Result, OOE); 13120 } 13121 13122 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13123 switch (E->getOpcode()) { 13124 default: 13125 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13126 // See C99 6.6p3. 13127 return Error(E); 13128 case UO_Extension: 13129 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13130 // If so, we could clear the diagnostic ID. 13131 return Visit(E->getSubExpr()); 13132 case UO_Plus: 13133 // The result is just the value. 13134 return Visit(E->getSubExpr()); 13135 case UO_Minus: { 13136 if (!Visit(E->getSubExpr())) 13137 return false; 13138 if (!Result.isInt()) return Error(E); 13139 const APSInt &Value = Result.getInt(); 13140 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13141 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13142 E->getType())) 13143 return false; 13144 return Success(-Value, E); 13145 } 13146 case UO_Not: { 13147 if (!Visit(E->getSubExpr())) 13148 return false; 13149 if (!Result.isInt()) return Error(E); 13150 return Success(~Result.getInt(), E); 13151 } 13152 case UO_LNot: { 13153 bool bres; 13154 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13155 return false; 13156 return Success(!bres, E); 13157 } 13158 } 13159 } 13160 13161 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13162 /// result type is integer. 13163 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13164 const Expr *SubExpr = E->getSubExpr(); 13165 QualType DestType = E->getType(); 13166 QualType SrcType = SubExpr->getType(); 13167 13168 switch (E->getCastKind()) { 13169 case CK_BaseToDerived: 13170 case CK_DerivedToBase: 13171 case CK_UncheckedDerivedToBase: 13172 case CK_Dynamic: 13173 case CK_ToUnion: 13174 case CK_ArrayToPointerDecay: 13175 case CK_FunctionToPointerDecay: 13176 case CK_NullToPointer: 13177 case CK_NullToMemberPointer: 13178 case CK_BaseToDerivedMemberPointer: 13179 case CK_DerivedToBaseMemberPointer: 13180 case CK_ReinterpretMemberPointer: 13181 case CK_ConstructorConversion: 13182 case CK_IntegralToPointer: 13183 case CK_ToVoid: 13184 case CK_VectorSplat: 13185 case CK_IntegralToFloating: 13186 case CK_FloatingCast: 13187 case CK_CPointerToObjCPointerCast: 13188 case CK_BlockPointerToObjCPointerCast: 13189 case CK_AnyPointerToBlockPointerCast: 13190 case CK_ObjCObjectLValueCast: 13191 case CK_FloatingRealToComplex: 13192 case CK_FloatingComplexToReal: 13193 case CK_FloatingComplexCast: 13194 case CK_FloatingComplexToIntegralComplex: 13195 case CK_IntegralRealToComplex: 13196 case CK_IntegralComplexCast: 13197 case CK_IntegralComplexToFloatingComplex: 13198 case CK_BuiltinFnToFnPtr: 13199 case CK_ZeroToOCLOpaqueType: 13200 case CK_NonAtomicToAtomic: 13201 case CK_AddressSpaceConversion: 13202 case CK_IntToOCLSampler: 13203 case CK_FloatingToFixedPoint: 13204 case CK_FixedPointToFloating: 13205 case CK_FixedPointCast: 13206 case CK_IntegralToFixedPoint: 13207 case CK_MatrixCast: 13208 llvm_unreachable("invalid cast kind for integral value"); 13209 13210 case CK_BitCast: 13211 case CK_Dependent: 13212 case CK_LValueBitCast: 13213 case CK_ARCProduceObject: 13214 case CK_ARCConsumeObject: 13215 case CK_ARCReclaimReturnedObject: 13216 case CK_ARCExtendBlockObject: 13217 case CK_CopyAndAutoreleaseBlockObject: 13218 return Error(E); 13219 13220 case CK_UserDefinedConversion: 13221 case CK_LValueToRValue: 13222 case CK_AtomicToNonAtomic: 13223 case CK_NoOp: 13224 case CK_LValueToRValueBitCast: 13225 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13226 13227 case CK_MemberPointerToBoolean: 13228 case CK_PointerToBoolean: 13229 case CK_IntegralToBoolean: 13230 case CK_FloatingToBoolean: 13231 case CK_BooleanToSignedIntegral: 13232 case CK_FloatingComplexToBoolean: 13233 case CK_IntegralComplexToBoolean: { 13234 bool BoolResult; 13235 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13236 return false; 13237 uint64_t IntResult = BoolResult; 13238 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13239 IntResult = (uint64_t)-1; 13240 return Success(IntResult, E); 13241 } 13242 13243 case CK_FixedPointToIntegral: { 13244 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13245 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13246 return false; 13247 bool Overflowed; 13248 llvm::APSInt Result = Src.convertToInt( 13249 Info.Ctx.getIntWidth(DestType), 13250 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13251 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13252 return false; 13253 return Success(Result, E); 13254 } 13255 13256 case CK_FixedPointToBoolean: { 13257 // Unsigned padding does not affect this. 13258 APValue Val; 13259 if (!Evaluate(Val, Info, SubExpr)) 13260 return false; 13261 return Success(Val.getFixedPoint().getBoolValue(), E); 13262 } 13263 13264 case CK_IntegralCast: { 13265 if (!Visit(SubExpr)) 13266 return false; 13267 13268 if (!Result.isInt()) { 13269 // Allow casts of address-of-label differences if they are no-ops 13270 // or narrowing. (The narrowing case isn't actually guaranteed to 13271 // be constant-evaluatable except in some narrow cases which are hard 13272 // to detect here. We let it through on the assumption the user knows 13273 // what they are doing.) 13274 if (Result.isAddrLabelDiff()) 13275 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13276 // Only allow casts of lvalues if they are lossless. 13277 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13278 } 13279 13280 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13281 Result.getInt()), E); 13282 } 13283 13284 case CK_PointerToIntegral: { 13285 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13286 13287 LValue LV; 13288 if (!EvaluatePointer(SubExpr, LV, Info)) 13289 return false; 13290 13291 if (LV.getLValueBase()) { 13292 // Only allow based lvalue casts if they are lossless. 13293 // FIXME: Allow a larger integer size than the pointer size, and allow 13294 // narrowing back down to pointer width in subsequent integral casts. 13295 // FIXME: Check integer type's active bits, not its type size. 13296 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13297 return Error(E); 13298 13299 LV.Designator.setInvalid(); 13300 LV.moveInto(Result); 13301 return true; 13302 } 13303 13304 APSInt AsInt; 13305 APValue V; 13306 LV.moveInto(V); 13307 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13308 llvm_unreachable("Can't cast this!"); 13309 13310 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13311 } 13312 13313 case CK_IntegralComplexToReal: { 13314 ComplexValue C; 13315 if (!EvaluateComplex(SubExpr, C, Info)) 13316 return false; 13317 return Success(C.getComplexIntReal(), E); 13318 } 13319 13320 case CK_FloatingToIntegral: { 13321 APFloat F(0.0); 13322 if (!EvaluateFloat(SubExpr, F, Info)) 13323 return false; 13324 13325 APSInt Value; 13326 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13327 return false; 13328 return Success(Value, E); 13329 } 13330 } 13331 13332 llvm_unreachable("unknown cast resulting in integral value"); 13333 } 13334 13335 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13336 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13337 ComplexValue LV; 13338 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13339 return false; 13340 if (!LV.isComplexInt()) 13341 return Error(E); 13342 return Success(LV.getComplexIntReal(), E); 13343 } 13344 13345 return Visit(E->getSubExpr()); 13346 } 13347 13348 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13349 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13350 ComplexValue LV; 13351 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13352 return false; 13353 if (!LV.isComplexInt()) 13354 return Error(E); 13355 return Success(LV.getComplexIntImag(), E); 13356 } 13357 13358 VisitIgnoredValue(E->getSubExpr()); 13359 return Success(0, E); 13360 } 13361 13362 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13363 return Success(E->getPackLength(), E); 13364 } 13365 13366 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13367 return Success(E->getValue(), E); 13368 } 13369 13370 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13371 const ConceptSpecializationExpr *E) { 13372 return Success(E->isSatisfied(), E); 13373 } 13374 13375 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13376 return Success(E->isSatisfied(), E); 13377 } 13378 13379 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13380 switch (E->getOpcode()) { 13381 default: 13382 // Invalid unary operators 13383 return Error(E); 13384 case UO_Plus: 13385 // The result is just the value. 13386 return Visit(E->getSubExpr()); 13387 case UO_Minus: { 13388 if (!Visit(E->getSubExpr())) return false; 13389 if (!Result.isFixedPoint()) 13390 return Error(E); 13391 bool Overflowed; 13392 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13393 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13394 return false; 13395 return Success(Negated, E); 13396 } 13397 case UO_LNot: { 13398 bool bres; 13399 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13400 return false; 13401 return Success(!bres, E); 13402 } 13403 } 13404 } 13405 13406 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13407 const Expr *SubExpr = E->getSubExpr(); 13408 QualType DestType = E->getType(); 13409 assert(DestType->isFixedPointType() && 13410 "Expected destination type to be a fixed point type"); 13411 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13412 13413 switch (E->getCastKind()) { 13414 case CK_FixedPointCast: { 13415 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13416 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13417 return false; 13418 bool Overflowed; 13419 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13420 if (Overflowed) { 13421 if (Info.checkingForUndefinedBehavior()) 13422 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13423 diag::warn_fixedpoint_constant_overflow) 13424 << Result.toString() << E->getType(); 13425 if (!HandleOverflow(Info, E, Result, E->getType())) 13426 return false; 13427 } 13428 return Success(Result, E); 13429 } 13430 case CK_IntegralToFixedPoint: { 13431 APSInt Src; 13432 if (!EvaluateInteger(SubExpr, Src, Info)) 13433 return false; 13434 13435 bool Overflowed; 13436 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13437 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13438 13439 if (Overflowed) { 13440 if (Info.checkingForUndefinedBehavior()) 13441 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13442 diag::warn_fixedpoint_constant_overflow) 13443 << IntResult.toString() << E->getType(); 13444 if (!HandleOverflow(Info, E, IntResult, E->getType())) 13445 return false; 13446 } 13447 13448 return Success(IntResult, E); 13449 } 13450 case CK_FloatingToFixedPoint: { 13451 APFloat Src(0.0); 13452 if (!EvaluateFloat(SubExpr, Src, Info)) 13453 return false; 13454 13455 bool Overflowed; 13456 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13457 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13458 13459 if (Overflowed) { 13460 if (Info.checkingForUndefinedBehavior()) 13461 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13462 diag::warn_fixedpoint_constant_overflow) 13463 << Result.toString() << E->getType(); 13464 if (!HandleOverflow(Info, E, Result, E->getType())) 13465 return false; 13466 } 13467 13468 return Success(Result, E); 13469 } 13470 case CK_NoOp: 13471 case CK_LValueToRValue: 13472 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13473 default: 13474 return Error(E); 13475 } 13476 } 13477 13478 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13479 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13480 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13481 13482 const Expr *LHS = E->getLHS(); 13483 const Expr *RHS = E->getRHS(); 13484 FixedPointSemantics ResultFXSema = 13485 Info.Ctx.getFixedPointSemantics(E->getType()); 13486 13487 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13488 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13489 return false; 13490 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13491 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13492 return false; 13493 13494 bool OpOverflow = false, ConversionOverflow = false; 13495 APFixedPoint Result(LHSFX.getSemantics()); 13496 switch (E->getOpcode()) { 13497 case BO_Add: { 13498 Result = LHSFX.add(RHSFX, &OpOverflow) 13499 .convert(ResultFXSema, &ConversionOverflow); 13500 break; 13501 } 13502 case BO_Sub: { 13503 Result = LHSFX.sub(RHSFX, &OpOverflow) 13504 .convert(ResultFXSema, &ConversionOverflow); 13505 break; 13506 } 13507 case BO_Mul: { 13508 Result = LHSFX.mul(RHSFX, &OpOverflow) 13509 .convert(ResultFXSema, &ConversionOverflow); 13510 break; 13511 } 13512 case BO_Div: { 13513 if (RHSFX.getValue() == 0) { 13514 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13515 return false; 13516 } 13517 Result = LHSFX.div(RHSFX, &OpOverflow) 13518 .convert(ResultFXSema, &ConversionOverflow); 13519 break; 13520 } 13521 case BO_Shl: 13522 case BO_Shr: { 13523 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13524 llvm::APSInt RHSVal = RHSFX.getValue(); 13525 13526 unsigned ShiftBW = 13527 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13528 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13529 // Embedded-C 4.1.6.2.2: 13530 // The right operand must be nonnegative and less than the total number 13531 // of (nonpadding) bits of the fixed-point operand ... 13532 if (RHSVal.isNegative()) 13533 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13534 else if (Amt != RHSVal) 13535 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13536 << RHSVal << E->getType() << ShiftBW; 13537 13538 if (E->getOpcode() == BO_Shl) 13539 Result = LHSFX.shl(Amt, &OpOverflow); 13540 else 13541 Result = LHSFX.shr(Amt, &OpOverflow); 13542 break; 13543 } 13544 default: 13545 return false; 13546 } 13547 if (OpOverflow || ConversionOverflow) { 13548 if (Info.checkingForUndefinedBehavior()) 13549 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13550 diag::warn_fixedpoint_constant_overflow) 13551 << Result.toString() << E->getType(); 13552 if (!HandleOverflow(Info, E, Result, E->getType())) 13553 return false; 13554 } 13555 return Success(Result, E); 13556 } 13557 13558 //===----------------------------------------------------------------------===// 13559 // Float Evaluation 13560 //===----------------------------------------------------------------------===// 13561 13562 namespace { 13563 class FloatExprEvaluator 13564 : public ExprEvaluatorBase<FloatExprEvaluator> { 13565 APFloat &Result; 13566 public: 13567 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13568 : ExprEvaluatorBaseTy(info), Result(result) {} 13569 13570 bool Success(const APValue &V, const Expr *e) { 13571 Result = V.getFloat(); 13572 return true; 13573 } 13574 13575 bool ZeroInitialization(const Expr *E) { 13576 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13577 return true; 13578 } 13579 13580 bool VisitCallExpr(const CallExpr *E); 13581 13582 bool VisitUnaryOperator(const UnaryOperator *E); 13583 bool VisitBinaryOperator(const BinaryOperator *E); 13584 bool VisitFloatingLiteral(const FloatingLiteral *E); 13585 bool VisitCastExpr(const CastExpr *E); 13586 13587 bool VisitUnaryReal(const UnaryOperator *E); 13588 bool VisitUnaryImag(const UnaryOperator *E); 13589 13590 // FIXME: Missing: array subscript of vector, member of vector 13591 }; 13592 } // end anonymous namespace 13593 13594 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13595 assert(!E->isValueDependent()); 13596 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13597 return FloatExprEvaluator(Info, Result).Visit(E); 13598 } 13599 13600 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13601 QualType ResultTy, 13602 const Expr *Arg, 13603 bool SNaN, 13604 llvm::APFloat &Result) { 13605 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13606 if (!S) return false; 13607 13608 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13609 13610 llvm::APInt fill; 13611 13612 // Treat empty strings as if they were zero. 13613 if (S->getString().empty()) 13614 fill = llvm::APInt(32, 0); 13615 else if (S->getString().getAsInteger(0, fill)) 13616 return false; 13617 13618 if (Context.getTargetInfo().isNan2008()) { 13619 if (SNaN) 13620 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13621 else 13622 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13623 } else { 13624 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13625 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13626 // a different encoding to what became a standard in 2008, and for pre- 13627 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13628 // sNaN. This is now known as "legacy NaN" encoding. 13629 if (SNaN) 13630 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13631 else 13632 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13633 } 13634 13635 return true; 13636 } 13637 13638 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13639 switch (E->getBuiltinCallee()) { 13640 default: 13641 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13642 13643 case Builtin::BI__builtin_huge_val: 13644 case Builtin::BI__builtin_huge_valf: 13645 case Builtin::BI__builtin_huge_vall: 13646 case Builtin::BI__builtin_huge_valf128: 13647 case Builtin::BI__builtin_inf: 13648 case Builtin::BI__builtin_inff: 13649 case Builtin::BI__builtin_infl: 13650 case Builtin::BI__builtin_inff128: { 13651 const llvm::fltSemantics &Sem = 13652 Info.Ctx.getFloatTypeSemantics(E->getType()); 13653 Result = llvm::APFloat::getInf(Sem); 13654 return true; 13655 } 13656 13657 case Builtin::BI__builtin_nans: 13658 case Builtin::BI__builtin_nansf: 13659 case Builtin::BI__builtin_nansl: 13660 case Builtin::BI__builtin_nansf128: 13661 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13662 true, Result)) 13663 return Error(E); 13664 return true; 13665 13666 case Builtin::BI__builtin_nan: 13667 case Builtin::BI__builtin_nanf: 13668 case Builtin::BI__builtin_nanl: 13669 case Builtin::BI__builtin_nanf128: 13670 // If this is __builtin_nan() turn this into a nan, otherwise we 13671 // can't constant fold it. 13672 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13673 false, Result)) 13674 return Error(E); 13675 return true; 13676 13677 case Builtin::BI__builtin_fabs: 13678 case Builtin::BI__builtin_fabsf: 13679 case Builtin::BI__builtin_fabsl: 13680 case Builtin::BI__builtin_fabsf128: 13681 // The C standard says "fabs raises no floating-point exceptions, 13682 // even if x is a signaling NaN. The returned value is independent of 13683 // the current rounding direction mode." Therefore constant folding can 13684 // proceed without regard to the floating point settings. 13685 // Reference, WG14 N2478 F.10.4.3 13686 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13687 return false; 13688 13689 if (Result.isNegative()) 13690 Result.changeSign(); 13691 return true; 13692 13693 // FIXME: Builtin::BI__builtin_powi 13694 // FIXME: Builtin::BI__builtin_powif 13695 // FIXME: Builtin::BI__builtin_powil 13696 13697 case Builtin::BI__builtin_copysign: 13698 case Builtin::BI__builtin_copysignf: 13699 case Builtin::BI__builtin_copysignl: 13700 case Builtin::BI__builtin_copysignf128: { 13701 APFloat RHS(0.); 13702 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13703 !EvaluateFloat(E->getArg(1), RHS, Info)) 13704 return false; 13705 Result.copySign(RHS); 13706 return true; 13707 } 13708 } 13709 } 13710 13711 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13712 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13713 ComplexValue CV; 13714 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13715 return false; 13716 Result = CV.FloatReal; 13717 return true; 13718 } 13719 13720 return Visit(E->getSubExpr()); 13721 } 13722 13723 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13724 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13725 ComplexValue CV; 13726 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13727 return false; 13728 Result = CV.FloatImag; 13729 return true; 13730 } 13731 13732 VisitIgnoredValue(E->getSubExpr()); 13733 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13734 Result = llvm::APFloat::getZero(Sem); 13735 return true; 13736 } 13737 13738 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13739 switch (E->getOpcode()) { 13740 default: return Error(E); 13741 case UO_Plus: 13742 return EvaluateFloat(E->getSubExpr(), Result, Info); 13743 case UO_Minus: 13744 // In C standard, WG14 N2478 F.3 p4 13745 // "the unary - raises no floating point exceptions, 13746 // even if the operand is signalling." 13747 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13748 return false; 13749 Result.changeSign(); 13750 return true; 13751 } 13752 } 13753 13754 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13755 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13756 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13757 13758 APFloat RHS(0.0); 13759 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13760 if (!LHSOK && !Info.noteFailure()) 13761 return false; 13762 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13763 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13764 } 13765 13766 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13767 Result = E->getValue(); 13768 return true; 13769 } 13770 13771 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13772 const Expr* SubExpr = E->getSubExpr(); 13773 13774 switch (E->getCastKind()) { 13775 default: 13776 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13777 13778 case CK_IntegralToFloating: { 13779 APSInt IntResult; 13780 const FPOptions FPO = E->getFPFeaturesInEffect( 13781 Info.Ctx.getLangOpts()); 13782 return EvaluateInteger(SubExpr, IntResult, Info) && 13783 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13784 IntResult, E->getType(), Result); 13785 } 13786 13787 case CK_FixedPointToFloating: { 13788 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13789 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13790 return false; 13791 Result = 13792 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13793 return true; 13794 } 13795 13796 case CK_FloatingCast: { 13797 if (!Visit(SubExpr)) 13798 return false; 13799 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13800 Result); 13801 } 13802 13803 case CK_FloatingComplexToReal: { 13804 ComplexValue V; 13805 if (!EvaluateComplex(SubExpr, V, Info)) 13806 return false; 13807 Result = V.getComplexFloatReal(); 13808 return true; 13809 } 13810 } 13811 } 13812 13813 //===----------------------------------------------------------------------===// 13814 // Complex Evaluation (for float and integer) 13815 //===----------------------------------------------------------------------===// 13816 13817 namespace { 13818 class ComplexExprEvaluator 13819 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13820 ComplexValue &Result; 13821 13822 public: 13823 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13824 : ExprEvaluatorBaseTy(info), Result(Result) {} 13825 13826 bool Success(const APValue &V, const Expr *e) { 13827 Result.setFrom(V); 13828 return true; 13829 } 13830 13831 bool ZeroInitialization(const Expr *E); 13832 13833 //===--------------------------------------------------------------------===// 13834 // Visitor Methods 13835 //===--------------------------------------------------------------------===// 13836 13837 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13838 bool VisitCastExpr(const CastExpr *E); 13839 bool VisitBinaryOperator(const BinaryOperator *E); 13840 bool VisitUnaryOperator(const UnaryOperator *E); 13841 bool VisitInitListExpr(const InitListExpr *E); 13842 bool VisitCallExpr(const CallExpr *E); 13843 }; 13844 } // end anonymous namespace 13845 13846 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13847 EvalInfo &Info) { 13848 assert(!E->isValueDependent()); 13849 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13850 return ComplexExprEvaluator(Info, Result).Visit(E); 13851 } 13852 13853 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13854 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13855 if (ElemTy->isRealFloatingType()) { 13856 Result.makeComplexFloat(); 13857 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13858 Result.FloatReal = Zero; 13859 Result.FloatImag = Zero; 13860 } else { 13861 Result.makeComplexInt(); 13862 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13863 Result.IntReal = Zero; 13864 Result.IntImag = Zero; 13865 } 13866 return true; 13867 } 13868 13869 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13870 const Expr* SubExpr = E->getSubExpr(); 13871 13872 if (SubExpr->getType()->isRealFloatingType()) { 13873 Result.makeComplexFloat(); 13874 APFloat &Imag = Result.FloatImag; 13875 if (!EvaluateFloat(SubExpr, Imag, Info)) 13876 return false; 13877 13878 Result.FloatReal = APFloat(Imag.getSemantics()); 13879 return true; 13880 } else { 13881 assert(SubExpr->getType()->isIntegerType() && 13882 "Unexpected imaginary literal."); 13883 13884 Result.makeComplexInt(); 13885 APSInt &Imag = Result.IntImag; 13886 if (!EvaluateInteger(SubExpr, Imag, Info)) 13887 return false; 13888 13889 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13890 return true; 13891 } 13892 } 13893 13894 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13895 13896 switch (E->getCastKind()) { 13897 case CK_BitCast: 13898 case CK_BaseToDerived: 13899 case CK_DerivedToBase: 13900 case CK_UncheckedDerivedToBase: 13901 case CK_Dynamic: 13902 case CK_ToUnion: 13903 case CK_ArrayToPointerDecay: 13904 case CK_FunctionToPointerDecay: 13905 case CK_NullToPointer: 13906 case CK_NullToMemberPointer: 13907 case CK_BaseToDerivedMemberPointer: 13908 case CK_DerivedToBaseMemberPointer: 13909 case CK_MemberPointerToBoolean: 13910 case CK_ReinterpretMemberPointer: 13911 case CK_ConstructorConversion: 13912 case CK_IntegralToPointer: 13913 case CK_PointerToIntegral: 13914 case CK_PointerToBoolean: 13915 case CK_ToVoid: 13916 case CK_VectorSplat: 13917 case CK_IntegralCast: 13918 case CK_BooleanToSignedIntegral: 13919 case CK_IntegralToBoolean: 13920 case CK_IntegralToFloating: 13921 case CK_FloatingToIntegral: 13922 case CK_FloatingToBoolean: 13923 case CK_FloatingCast: 13924 case CK_CPointerToObjCPointerCast: 13925 case CK_BlockPointerToObjCPointerCast: 13926 case CK_AnyPointerToBlockPointerCast: 13927 case CK_ObjCObjectLValueCast: 13928 case CK_FloatingComplexToReal: 13929 case CK_FloatingComplexToBoolean: 13930 case CK_IntegralComplexToReal: 13931 case CK_IntegralComplexToBoolean: 13932 case CK_ARCProduceObject: 13933 case CK_ARCConsumeObject: 13934 case CK_ARCReclaimReturnedObject: 13935 case CK_ARCExtendBlockObject: 13936 case CK_CopyAndAutoreleaseBlockObject: 13937 case CK_BuiltinFnToFnPtr: 13938 case CK_ZeroToOCLOpaqueType: 13939 case CK_NonAtomicToAtomic: 13940 case CK_AddressSpaceConversion: 13941 case CK_IntToOCLSampler: 13942 case CK_FloatingToFixedPoint: 13943 case CK_FixedPointToFloating: 13944 case CK_FixedPointCast: 13945 case CK_FixedPointToBoolean: 13946 case CK_FixedPointToIntegral: 13947 case CK_IntegralToFixedPoint: 13948 case CK_MatrixCast: 13949 llvm_unreachable("invalid cast kind for complex value"); 13950 13951 case CK_LValueToRValue: 13952 case CK_AtomicToNonAtomic: 13953 case CK_NoOp: 13954 case CK_LValueToRValueBitCast: 13955 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13956 13957 case CK_Dependent: 13958 case CK_LValueBitCast: 13959 case CK_UserDefinedConversion: 13960 return Error(E); 13961 13962 case CK_FloatingRealToComplex: { 13963 APFloat &Real = Result.FloatReal; 13964 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13965 return false; 13966 13967 Result.makeComplexFloat(); 13968 Result.FloatImag = APFloat(Real.getSemantics()); 13969 return true; 13970 } 13971 13972 case CK_FloatingComplexCast: { 13973 if (!Visit(E->getSubExpr())) 13974 return false; 13975 13976 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13977 QualType From 13978 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13979 13980 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13981 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13982 } 13983 13984 case CK_FloatingComplexToIntegralComplex: { 13985 if (!Visit(E->getSubExpr())) 13986 return false; 13987 13988 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13989 QualType From 13990 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13991 Result.makeComplexInt(); 13992 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13993 To, Result.IntReal) && 13994 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13995 To, Result.IntImag); 13996 } 13997 13998 case CK_IntegralRealToComplex: { 13999 APSInt &Real = Result.IntReal; 14000 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 14001 return false; 14002 14003 Result.makeComplexInt(); 14004 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 14005 return true; 14006 } 14007 14008 case CK_IntegralComplexCast: { 14009 if (!Visit(E->getSubExpr())) 14010 return false; 14011 14012 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14013 QualType From 14014 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14015 14016 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 14017 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 14018 return true; 14019 } 14020 14021 case CK_IntegralComplexToFloatingComplex: { 14022 if (!Visit(E->getSubExpr())) 14023 return false; 14024 14025 const FPOptions FPO = E->getFPFeaturesInEffect( 14026 Info.Ctx.getLangOpts()); 14027 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14028 QualType From 14029 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14030 Result.makeComplexFloat(); 14031 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14032 To, Result.FloatReal) && 14033 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14034 To, Result.FloatImag); 14035 } 14036 } 14037 14038 llvm_unreachable("unknown cast resulting in complex value"); 14039 } 14040 14041 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14042 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14043 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14044 14045 // Track whether the LHS or RHS is real at the type system level. When this is 14046 // the case we can simplify our evaluation strategy. 14047 bool LHSReal = false, RHSReal = false; 14048 14049 bool LHSOK; 14050 if (E->getLHS()->getType()->isRealFloatingType()) { 14051 LHSReal = true; 14052 APFloat &Real = Result.FloatReal; 14053 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14054 if (LHSOK) { 14055 Result.makeComplexFloat(); 14056 Result.FloatImag = APFloat(Real.getSemantics()); 14057 } 14058 } else { 14059 LHSOK = Visit(E->getLHS()); 14060 } 14061 if (!LHSOK && !Info.noteFailure()) 14062 return false; 14063 14064 ComplexValue RHS; 14065 if (E->getRHS()->getType()->isRealFloatingType()) { 14066 RHSReal = true; 14067 APFloat &Real = RHS.FloatReal; 14068 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14069 return false; 14070 RHS.makeComplexFloat(); 14071 RHS.FloatImag = APFloat(Real.getSemantics()); 14072 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14073 return false; 14074 14075 assert(!(LHSReal && RHSReal) && 14076 "Cannot have both operands of a complex operation be real."); 14077 switch (E->getOpcode()) { 14078 default: return Error(E); 14079 case BO_Add: 14080 if (Result.isComplexFloat()) { 14081 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14082 APFloat::rmNearestTiesToEven); 14083 if (LHSReal) 14084 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14085 else if (!RHSReal) 14086 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14087 APFloat::rmNearestTiesToEven); 14088 } else { 14089 Result.getComplexIntReal() += RHS.getComplexIntReal(); 14090 Result.getComplexIntImag() += RHS.getComplexIntImag(); 14091 } 14092 break; 14093 case BO_Sub: 14094 if (Result.isComplexFloat()) { 14095 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14096 APFloat::rmNearestTiesToEven); 14097 if (LHSReal) { 14098 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14099 Result.getComplexFloatImag().changeSign(); 14100 } else if (!RHSReal) { 14101 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14102 APFloat::rmNearestTiesToEven); 14103 } 14104 } else { 14105 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14106 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14107 } 14108 break; 14109 case BO_Mul: 14110 if (Result.isComplexFloat()) { 14111 // This is an implementation of complex multiplication according to the 14112 // constraints laid out in C11 Annex G. The implementation uses the 14113 // following naming scheme: 14114 // (a + ib) * (c + id) 14115 ComplexValue LHS = Result; 14116 APFloat &A = LHS.getComplexFloatReal(); 14117 APFloat &B = LHS.getComplexFloatImag(); 14118 APFloat &C = RHS.getComplexFloatReal(); 14119 APFloat &D = RHS.getComplexFloatImag(); 14120 APFloat &ResR = Result.getComplexFloatReal(); 14121 APFloat &ResI = Result.getComplexFloatImag(); 14122 if (LHSReal) { 14123 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14124 ResR = A * C; 14125 ResI = A * D; 14126 } else if (RHSReal) { 14127 ResR = C * A; 14128 ResI = C * B; 14129 } else { 14130 // In the fully general case, we need to handle NaNs and infinities 14131 // robustly. 14132 APFloat AC = A * C; 14133 APFloat BD = B * D; 14134 APFloat AD = A * D; 14135 APFloat BC = B * C; 14136 ResR = AC - BD; 14137 ResI = AD + BC; 14138 if (ResR.isNaN() && ResI.isNaN()) { 14139 bool Recalc = false; 14140 if (A.isInfinity() || B.isInfinity()) { 14141 A = APFloat::copySign( 14142 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14143 B = APFloat::copySign( 14144 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14145 if (C.isNaN()) 14146 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14147 if (D.isNaN()) 14148 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14149 Recalc = true; 14150 } 14151 if (C.isInfinity() || D.isInfinity()) { 14152 C = APFloat::copySign( 14153 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14154 D = APFloat::copySign( 14155 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14156 if (A.isNaN()) 14157 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14158 if (B.isNaN()) 14159 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14160 Recalc = true; 14161 } 14162 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14163 AD.isInfinity() || BC.isInfinity())) { 14164 if (A.isNaN()) 14165 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14166 if (B.isNaN()) 14167 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14168 if (C.isNaN()) 14169 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14170 if (D.isNaN()) 14171 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14172 Recalc = true; 14173 } 14174 if (Recalc) { 14175 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14176 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14177 } 14178 } 14179 } 14180 } else { 14181 ComplexValue LHS = Result; 14182 Result.getComplexIntReal() = 14183 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14184 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14185 Result.getComplexIntImag() = 14186 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14187 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14188 } 14189 break; 14190 case BO_Div: 14191 if (Result.isComplexFloat()) { 14192 // This is an implementation of complex division according to the 14193 // constraints laid out in C11 Annex G. The implementation uses the 14194 // following naming scheme: 14195 // (a + ib) / (c + id) 14196 ComplexValue LHS = Result; 14197 APFloat &A = LHS.getComplexFloatReal(); 14198 APFloat &B = LHS.getComplexFloatImag(); 14199 APFloat &C = RHS.getComplexFloatReal(); 14200 APFloat &D = RHS.getComplexFloatImag(); 14201 APFloat &ResR = Result.getComplexFloatReal(); 14202 APFloat &ResI = Result.getComplexFloatImag(); 14203 if (RHSReal) { 14204 ResR = A / C; 14205 ResI = B / C; 14206 } else { 14207 if (LHSReal) { 14208 // No real optimizations we can do here, stub out with zero. 14209 B = APFloat::getZero(A.getSemantics()); 14210 } 14211 int DenomLogB = 0; 14212 APFloat MaxCD = maxnum(abs(C), abs(D)); 14213 if (MaxCD.isFinite()) { 14214 DenomLogB = ilogb(MaxCD); 14215 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14216 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14217 } 14218 APFloat Denom = C * C + D * D; 14219 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14220 APFloat::rmNearestTiesToEven); 14221 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14222 APFloat::rmNearestTiesToEven); 14223 if (ResR.isNaN() && ResI.isNaN()) { 14224 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14225 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14226 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14227 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14228 D.isFinite()) { 14229 A = APFloat::copySign( 14230 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14231 B = APFloat::copySign( 14232 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14233 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14234 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14235 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14236 C = APFloat::copySign( 14237 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14238 D = APFloat::copySign( 14239 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14240 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14241 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14242 } 14243 } 14244 } 14245 } else { 14246 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14247 return Error(E, diag::note_expr_divide_by_zero); 14248 14249 ComplexValue LHS = Result; 14250 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14251 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14252 Result.getComplexIntReal() = 14253 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14254 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14255 Result.getComplexIntImag() = 14256 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14257 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14258 } 14259 break; 14260 } 14261 14262 return true; 14263 } 14264 14265 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14266 // Get the operand value into 'Result'. 14267 if (!Visit(E->getSubExpr())) 14268 return false; 14269 14270 switch (E->getOpcode()) { 14271 default: 14272 return Error(E); 14273 case UO_Extension: 14274 return true; 14275 case UO_Plus: 14276 // The result is always just the subexpr. 14277 return true; 14278 case UO_Minus: 14279 if (Result.isComplexFloat()) { 14280 Result.getComplexFloatReal().changeSign(); 14281 Result.getComplexFloatImag().changeSign(); 14282 } 14283 else { 14284 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14285 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14286 } 14287 return true; 14288 case UO_Not: 14289 if (Result.isComplexFloat()) 14290 Result.getComplexFloatImag().changeSign(); 14291 else 14292 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14293 return true; 14294 } 14295 } 14296 14297 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14298 if (E->getNumInits() == 2) { 14299 if (E->getType()->isComplexType()) { 14300 Result.makeComplexFloat(); 14301 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14302 return false; 14303 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14304 return false; 14305 } else { 14306 Result.makeComplexInt(); 14307 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14308 return false; 14309 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14310 return false; 14311 } 14312 return true; 14313 } 14314 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14315 } 14316 14317 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14318 switch (E->getBuiltinCallee()) { 14319 case Builtin::BI__builtin_complex: 14320 Result.makeComplexFloat(); 14321 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14322 return false; 14323 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14324 return false; 14325 return true; 14326 14327 default: 14328 break; 14329 } 14330 14331 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14332 } 14333 14334 //===----------------------------------------------------------------------===// 14335 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14336 // implicit conversion. 14337 //===----------------------------------------------------------------------===// 14338 14339 namespace { 14340 class AtomicExprEvaluator : 14341 public ExprEvaluatorBase<AtomicExprEvaluator> { 14342 const LValue *This; 14343 APValue &Result; 14344 public: 14345 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14346 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14347 14348 bool Success(const APValue &V, const Expr *E) { 14349 Result = V; 14350 return true; 14351 } 14352 14353 bool ZeroInitialization(const Expr *E) { 14354 ImplicitValueInitExpr VIE( 14355 E->getType()->castAs<AtomicType>()->getValueType()); 14356 // For atomic-qualified class (and array) types in C++, initialize the 14357 // _Atomic-wrapped subobject directly, in-place. 14358 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14359 : Evaluate(Result, Info, &VIE); 14360 } 14361 14362 bool VisitCastExpr(const CastExpr *E) { 14363 switch (E->getCastKind()) { 14364 default: 14365 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14366 case CK_NonAtomicToAtomic: 14367 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14368 : Evaluate(Result, Info, E->getSubExpr()); 14369 } 14370 } 14371 }; 14372 } // end anonymous namespace 14373 14374 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14375 EvalInfo &Info) { 14376 assert(!E->isValueDependent()); 14377 assert(E->isRValue() && E->getType()->isAtomicType()); 14378 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14379 } 14380 14381 //===----------------------------------------------------------------------===// 14382 // Void expression evaluation, primarily for a cast to void on the LHS of a 14383 // comma operator 14384 //===----------------------------------------------------------------------===// 14385 14386 namespace { 14387 class VoidExprEvaluator 14388 : public ExprEvaluatorBase<VoidExprEvaluator> { 14389 public: 14390 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14391 14392 bool Success(const APValue &V, const Expr *e) { return true; } 14393 14394 bool ZeroInitialization(const Expr *E) { return true; } 14395 14396 bool VisitCastExpr(const CastExpr *E) { 14397 switch (E->getCastKind()) { 14398 default: 14399 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14400 case CK_ToVoid: 14401 VisitIgnoredValue(E->getSubExpr()); 14402 return true; 14403 } 14404 } 14405 14406 bool VisitCallExpr(const CallExpr *E) { 14407 switch (E->getBuiltinCallee()) { 14408 case Builtin::BI__assume: 14409 case Builtin::BI__builtin_assume: 14410 // The argument is not evaluated! 14411 return true; 14412 14413 case Builtin::BI__builtin_operator_delete: 14414 return HandleOperatorDeleteCall(Info, E); 14415 14416 default: 14417 break; 14418 } 14419 14420 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14421 } 14422 14423 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14424 }; 14425 } // end anonymous namespace 14426 14427 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14428 // We cannot speculatively evaluate a delete expression. 14429 if (Info.SpeculativeEvaluationDepth) 14430 return false; 14431 14432 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14433 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14434 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14435 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14436 return false; 14437 } 14438 14439 const Expr *Arg = E->getArgument(); 14440 14441 LValue Pointer; 14442 if (!EvaluatePointer(Arg, Pointer, Info)) 14443 return false; 14444 if (Pointer.Designator.Invalid) 14445 return false; 14446 14447 // Deleting a null pointer has no effect. 14448 if (Pointer.isNullPointer()) { 14449 // This is the only case where we need to produce an extension warning: 14450 // the only other way we can succeed is if we find a dynamic allocation, 14451 // and we will have warned when we allocated it in that case. 14452 if (!Info.getLangOpts().CPlusPlus20) 14453 Info.CCEDiag(E, diag::note_constexpr_new); 14454 return true; 14455 } 14456 14457 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14458 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14459 if (!Alloc) 14460 return false; 14461 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14462 14463 // For the non-array case, the designator must be empty if the static type 14464 // does not have a virtual destructor. 14465 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14466 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14467 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14468 << Arg->getType()->getPointeeType() << AllocType; 14469 return false; 14470 } 14471 14472 // For a class type with a virtual destructor, the selected operator delete 14473 // is the one looked up when building the destructor. 14474 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14475 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14476 if (VirtualDelete && 14477 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14478 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14479 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14480 return false; 14481 } 14482 } 14483 14484 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14485 (*Alloc)->Value, AllocType)) 14486 return false; 14487 14488 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14489 // The element was already erased. This means the destructor call also 14490 // deleted the object. 14491 // FIXME: This probably results in undefined behavior before we get this 14492 // far, and should be diagnosed elsewhere first. 14493 Info.FFDiag(E, diag::note_constexpr_double_delete); 14494 return false; 14495 } 14496 14497 return true; 14498 } 14499 14500 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14501 assert(!E->isValueDependent()); 14502 assert(E->isRValue() && E->getType()->isVoidType()); 14503 return VoidExprEvaluator(Info).Visit(E); 14504 } 14505 14506 //===----------------------------------------------------------------------===// 14507 // Top level Expr::EvaluateAsRValue method. 14508 //===----------------------------------------------------------------------===// 14509 14510 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14511 assert(!E->isValueDependent()); 14512 // In C, function designators are not lvalues, but we evaluate them as if they 14513 // are. 14514 QualType T = E->getType(); 14515 if (E->isGLValue() || T->isFunctionType()) { 14516 LValue LV; 14517 if (!EvaluateLValue(E, LV, Info)) 14518 return false; 14519 LV.moveInto(Result); 14520 } else if (T->isVectorType()) { 14521 if (!EvaluateVector(E, Result, Info)) 14522 return false; 14523 } else if (T->isIntegralOrEnumerationType()) { 14524 if (!IntExprEvaluator(Info, Result).Visit(E)) 14525 return false; 14526 } else if (T->hasPointerRepresentation()) { 14527 LValue LV; 14528 if (!EvaluatePointer(E, LV, Info)) 14529 return false; 14530 LV.moveInto(Result); 14531 } else if (T->isRealFloatingType()) { 14532 llvm::APFloat F(0.0); 14533 if (!EvaluateFloat(E, F, Info)) 14534 return false; 14535 Result = APValue(F); 14536 } else if (T->isAnyComplexType()) { 14537 ComplexValue C; 14538 if (!EvaluateComplex(E, C, Info)) 14539 return false; 14540 C.moveInto(Result); 14541 } else if (T->isFixedPointType()) { 14542 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14543 } else if (T->isMemberPointerType()) { 14544 MemberPtr P; 14545 if (!EvaluateMemberPointer(E, P, Info)) 14546 return false; 14547 P.moveInto(Result); 14548 return true; 14549 } else if (T->isArrayType()) { 14550 LValue LV; 14551 APValue &Value = 14552 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14553 if (!EvaluateArray(E, LV, Value, Info)) 14554 return false; 14555 Result = Value; 14556 } else if (T->isRecordType()) { 14557 LValue LV; 14558 APValue &Value = 14559 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14560 if (!EvaluateRecord(E, LV, Value, Info)) 14561 return false; 14562 Result = Value; 14563 } else if (T->isVoidType()) { 14564 if (!Info.getLangOpts().CPlusPlus11) 14565 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14566 << E->getType(); 14567 if (!EvaluateVoid(E, Info)) 14568 return false; 14569 } else if (T->isAtomicType()) { 14570 QualType Unqual = T.getAtomicUnqualifiedType(); 14571 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14572 LValue LV; 14573 APValue &Value = Info.CurrentCall->createTemporary( 14574 E, Unqual, ScopeKind::FullExpression, LV); 14575 if (!EvaluateAtomic(E, &LV, Value, Info)) 14576 return false; 14577 } else { 14578 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14579 return false; 14580 } 14581 } else if (Info.getLangOpts().CPlusPlus11) { 14582 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14583 return false; 14584 } else { 14585 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14586 return false; 14587 } 14588 14589 return true; 14590 } 14591 14592 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14593 /// cases, the in-place evaluation is essential, since later initializers for 14594 /// an object can indirectly refer to subobjects which were initialized earlier. 14595 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14596 const Expr *E, bool AllowNonLiteralTypes) { 14597 assert(!E->isValueDependent()); 14598 14599 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14600 return false; 14601 14602 if (E->isRValue()) { 14603 // Evaluate arrays and record types in-place, so that later initializers can 14604 // refer to earlier-initialized members of the object. 14605 QualType T = E->getType(); 14606 if (T->isArrayType()) 14607 return EvaluateArray(E, This, Result, Info); 14608 else if (T->isRecordType()) 14609 return EvaluateRecord(E, This, Result, Info); 14610 else if (T->isAtomicType()) { 14611 QualType Unqual = T.getAtomicUnqualifiedType(); 14612 if (Unqual->isArrayType() || Unqual->isRecordType()) 14613 return EvaluateAtomic(E, &This, Result, Info); 14614 } 14615 } 14616 14617 // For any other type, in-place evaluation is unimportant. 14618 return Evaluate(Result, Info, E); 14619 } 14620 14621 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14622 /// lvalue-to-rvalue cast if it is an lvalue. 14623 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14624 assert(!E->isValueDependent()); 14625 if (Info.EnableNewConstInterp) { 14626 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14627 return false; 14628 } else { 14629 if (E->getType().isNull()) 14630 return false; 14631 14632 if (!CheckLiteralType(Info, E)) 14633 return false; 14634 14635 if (!::Evaluate(Result, Info, E)) 14636 return false; 14637 14638 if (E->isGLValue()) { 14639 LValue LV; 14640 LV.setFrom(Info.Ctx, Result); 14641 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14642 return false; 14643 } 14644 } 14645 14646 // Check this core constant expression is a constant expression. 14647 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14648 ConstantExprKind::Normal) && 14649 CheckMemoryLeaks(Info); 14650 } 14651 14652 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14653 const ASTContext &Ctx, bool &IsConst) { 14654 // Fast-path evaluations of integer literals, since we sometimes see files 14655 // containing vast quantities of these. 14656 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14657 Result.Val = APValue(APSInt(L->getValue(), 14658 L->getType()->isUnsignedIntegerType())); 14659 IsConst = true; 14660 return true; 14661 } 14662 14663 // This case should be rare, but we need to check it before we check on 14664 // the type below. 14665 if (Exp->getType().isNull()) { 14666 IsConst = false; 14667 return true; 14668 } 14669 14670 // FIXME: Evaluating values of large array and record types can cause 14671 // performance problems. Only do so in C++11 for now. 14672 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14673 Exp->getType()->isRecordType()) && 14674 !Ctx.getLangOpts().CPlusPlus11) { 14675 IsConst = false; 14676 return true; 14677 } 14678 return false; 14679 } 14680 14681 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14682 Expr::SideEffectsKind SEK) { 14683 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14684 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14685 } 14686 14687 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14688 const ASTContext &Ctx, EvalInfo &Info) { 14689 assert(!E->isValueDependent()); 14690 bool IsConst; 14691 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14692 return IsConst; 14693 14694 return EvaluateAsRValue(Info, E, Result.Val); 14695 } 14696 14697 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14698 const ASTContext &Ctx, 14699 Expr::SideEffectsKind AllowSideEffects, 14700 EvalInfo &Info) { 14701 assert(!E->isValueDependent()); 14702 if (!E->getType()->isIntegralOrEnumerationType()) 14703 return false; 14704 14705 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14706 !ExprResult.Val.isInt() || 14707 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14708 return false; 14709 14710 return true; 14711 } 14712 14713 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14714 const ASTContext &Ctx, 14715 Expr::SideEffectsKind AllowSideEffects, 14716 EvalInfo &Info) { 14717 assert(!E->isValueDependent()); 14718 if (!E->getType()->isFixedPointType()) 14719 return false; 14720 14721 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14722 return false; 14723 14724 if (!ExprResult.Val.isFixedPoint() || 14725 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14726 return false; 14727 14728 return true; 14729 } 14730 14731 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14732 /// any crazy technique (that has nothing to do with language standards) that 14733 /// we want to. If this function returns true, it returns the folded constant 14734 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14735 /// will be applied to the result. 14736 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14737 bool InConstantContext) const { 14738 assert(!isValueDependent() && 14739 "Expression evaluator can't be called on a dependent expression."); 14740 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14741 Info.InConstantContext = InConstantContext; 14742 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14743 } 14744 14745 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14746 bool InConstantContext) const { 14747 assert(!isValueDependent() && 14748 "Expression evaluator can't be called on a dependent expression."); 14749 EvalResult Scratch; 14750 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14751 HandleConversionToBool(Scratch.Val, Result); 14752 } 14753 14754 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14755 SideEffectsKind AllowSideEffects, 14756 bool InConstantContext) const { 14757 assert(!isValueDependent() && 14758 "Expression evaluator can't be called on a dependent expression."); 14759 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14760 Info.InConstantContext = InConstantContext; 14761 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14762 } 14763 14764 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14765 SideEffectsKind AllowSideEffects, 14766 bool InConstantContext) const { 14767 assert(!isValueDependent() && 14768 "Expression evaluator can't be called on a dependent expression."); 14769 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14770 Info.InConstantContext = InConstantContext; 14771 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14772 } 14773 14774 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14775 SideEffectsKind AllowSideEffects, 14776 bool InConstantContext) const { 14777 assert(!isValueDependent() && 14778 "Expression evaluator can't be called on a dependent expression."); 14779 14780 if (!getType()->isRealFloatingType()) 14781 return false; 14782 14783 EvalResult ExprResult; 14784 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14785 !ExprResult.Val.isFloat() || 14786 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14787 return false; 14788 14789 Result = ExprResult.Val.getFloat(); 14790 return true; 14791 } 14792 14793 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14794 bool InConstantContext) const { 14795 assert(!isValueDependent() && 14796 "Expression evaluator can't be called on a dependent expression."); 14797 14798 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14799 Info.InConstantContext = InConstantContext; 14800 LValue LV; 14801 CheckedTemporaries CheckedTemps; 14802 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14803 Result.HasSideEffects || 14804 !CheckLValueConstantExpression(Info, getExprLoc(), 14805 Ctx.getLValueReferenceType(getType()), LV, 14806 ConstantExprKind::Normal, CheckedTemps)) 14807 return false; 14808 14809 LV.moveInto(Result.Val); 14810 return true; 14811 } 14812 14813 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14814 APValue DestroyedValue, QualType Type, 14815 SourceLocation Loc, Expr::EvalStatus &EStatus, 14816 bool IsConstantDestruction) { 14817 EvalInfo Info(Ctx, EStatus, 14818 IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14819 : EvalInfo::EM_ConstantFold); 14820 Info.setEvaluatingDecl(Base, DestroyedValue, 14821 EvalInfo::EvaluatingDeclKind::Dtor); 14822 Info.InConstantContext = IsConstantDestruction; 14823 14824 LValue LVal; 14825 LVal.set(Base); 14826 14827 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14828 EStatus.HasSideEffects) 14829 return false; 14830 14831 if (!Info.discardCleanups()) 14832 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14833 14834 return true; 14835 } 14836 14837 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14838 ConstantExprKind Kind) const { 14839 assert(!isValueDependent() && 14840 "Expression evaluator can't be called on a dependent expression."); 14841 14842 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14843 EvalInfo Info(Ctx, Result, EM); 14844 Info.InConstantContext = true; 14845 14846 // The type of the object we're initializing is 'const T' for a class NTTP. 14847 QualType T = getType(); 14848 if (Kind == ConstantExprKind::ClassTemplateArgument) 14849 T.addConst(); 14850 14851 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14852 // represent the result of the evaluation. CheckConstantExpression ensures 14853 // this doesn't escape. 14854 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14855 APValue::LValueBase Base(&BaseMTE); 14856 14857 Info.setEvaluatingDecl(Base, Result.Val); 14858 LValue LVal; 14859 LVal.set(Base); 14860 14861 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14862 return false; 14863 14864 if (!Info.discardCleanups()) 14865 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14866 14867 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14868 Result.Val, Kind)) 14869 return false; 14870 if (!CheckMemoryLeaks(Info)) 14871 return false; 14872 14873 // If this is a class template argument, it's required to have constant 14874 // destruction too. 14875 if (Kind == ConstantExprKind::ClassTemplateArgument && 14876 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 14877 true) || 14878 Result.HasSideEffects)) { 14879 // FIXME: Prefix a note to indicate that the problem is lack of constant 14880 // destruction. 14881 return false; 14882 } 14883 14884 return true; 14885 } 14886 14887 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14888 const VarDecl *VD, 14889 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14890 bool IsConstantInitialization) const { 14891 assert(!isValueDependent() && 14892 "Expression evaluator can't be called on a dependent expression."); 14893 14894 // FIXME: Evaluating initializers for large array and record types can cause 14895 // performance problems. Only do so in C++11 for now. 14896 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14897 !Ctx.getLangOpts().CPlusPlus11) 14898 return false; 14899 14900 Expr::EvalStatus EStatus; 14901 EStatus.Diag = &Notes; 14902 14903 EvalInfo Info(Ctx, EStatus, 14904 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14905 ? EvalInfo::EM_ConstantExpression 14906 : EvalInfo::EM_ConstantFold); 14907 Info.setEvaluatingDecl(VD, Value); 14908 Info.InConstantContext = IsConstantInitialization; 14909 14910 SourceLocation DeclLoc = VD->getLocation(); 14911 QualType DeclTy = VD->getType(); 14912 14913 if (Info.EnableNewConstInterp) { 14914 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14915 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14916 return false; 14917 } else { 14918 LValue LVal; 14919 LVal.set(VD); 14920 14921 if (!EvaluateInPlace(Value, Info, LVal, this, 14922 /*AllowNonLiteralTypes=*/true) || 14923 EStatus.HasSideEffects) 14924 return false; 14925 14926 // At this point, any lifetime-extended temporaries are completely 14927 // initialized. 14928 Info.performLifetimeExtension(); 14929 14930 if (!Info.discardCleanups()) 14931 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14932 } 14933 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14934 ConstantExprKind::Normal) && 14935 CheckMemoryLeaks(Info); 14936 } 14937 14938 bool VarDecl::evaluateDestruction( 14939 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14940 Expr::EvalStatus EStatus; 14941 EStatus.Diag = &Notes; 14942 14943 // Only treat the destruction as constant destruction if we formally have 14944 // constant initialization (or are usable in a constant expression). 14945 bool IsConstantDestruction = hasConstantInitialization(); 14946 14947 // Make a copy of the value for the destructor to mutate, if we know it. 14948 // Otherwise, treat the value as default-initialized; if the destructor works 14949 // anyway, then the destruction is constant (and must be essentially empty). 14950 APValue DestroyedValue; 14951 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14952 DestroyedValue = *getEvaluatedValue(); 14953 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14954 return false; 14955 14956 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14957 getType(), getLocation(), EStatus, 14958 IsConstantDestruction) || 14959 EStatus.HasSideEffects) 14960 return false; 14961 14962 ensureEvaluatedStmt()->HasConstantDestruction = true; 14963 return true; 14964 } 14965 14966 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14967 /// constant folded, but discard the result. 14968 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14969 assert(!isValueDependent() && 14970 "Expression evaluator can't be called on a dependent expression."); 14971 14972 EvalResult Result; 14973 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14974 !hasUnacceptableSideEffect(Result, SEK); 14975 } 14976 14977 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14978 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14979 assert(!isValueDependent() && 14980 "Expression evaluator can't be called on a dependent expression."); 14981 14982 EvalResult EVResult; 14983 EVResult.Diag = Diag; 14984 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14985 Info.InConstantContext = true; 14986 14987 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14988 (void)Result; 14989 assert(Result && "Could not evaluate expression"); 14990 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14991 14992 return EVResult.Val.getInt(); 14993 } 14994 14995 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14996 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14997 assert(!isValueDependent() && 14998 "Expression evaluator can't be called on a dependent expression."); 14999 15000 EvalResult EVResult; 15001 EVResult.Diag = Diag; 15002 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15003 Info.InConstantContext = true; 15004 Info.CheckingForUndefinedBehavior = true; 15005 15006 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 15007 (void)Result; 15008 assert(Result && "Could not evaluate expression"); 15009 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 15010 15011 return EVResult.Val.getInt(); 15012 } 15013 15014 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 15015 assert(!isValueDependent() && 15016 "Expression evaluator can't be called on a dependent expression."); 15017 15018 bool IsConst; 15019 EvalResult EVResult; 15020 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15021 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15022 Info.CheckingForUndefinedBehavior = true; 15023 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15024 } 15025 } 15026 15027 bool Expr::EvalResult::isGlobalLValue() const { 15028 assert(Val.isLValue()); 15029 return IsGlobalLValue(Val.getLValueBase()); 15030 } 15031 15032 /// isIntegerConstantExpr - this recursive routine will test if an expression is 15033 /// an integer constant expression. 15034 15035 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15036 /// comma, etc 15037 15038 // CheckICE - This function does the fundamental ICE checking: the returned 15039 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15040 // and a (possibly null) SourceLocation indicating the location of the problem. 15041 // 15042 // Note that to reduce code duplication, this helper does no evaluation 15043 // itself; the caller checks whether the expression is evaluatable, and 15044 // in the rare cases where CheckICE actually cares about the evaluated 15045 // value, it calls into Evaluate. 15046 15047 namespace { 15048 15049 enum ICEKind { 15050 /// This expression is an ICE. 15051 IK_ICE, 15052 /// This expression is not an ICE, but if it isn't evaluated, it's 15053 /// a legal subexpression for an ICE. This return value is used to handle 15054 /// the comma operator in C99 mode, and non-constant subexpressions. 15055 IK_ICEIfUnevaluated, 15056 /// This expression is not an ICE, and is not a legal subexpression for one. 15057 IK_NotICE 15058 }; 15059 15060 struct ICEDiag { 15061 ICEKind Kind; 15062 SourceLocation Loc; 15063 15064 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15065 }; 15066 15067 } 15068 15069 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15070 15071 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15072 15073 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15074 Expr::EvalResult EVResult; 15075 Expr::EvalStatus Status; 15076 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15077 15078 Info.InConstantContext = true; 15079 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15080 !EVResult.Val.isInt()) 15081 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15082 15083 return NoDiag(); 15084 } 15085 15086 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15087 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15088 if (!E->getType()->isIntegralOrEnumerationType()) 15089 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15090 15091 switch (E->getStmtClass()) { 15092 #define ABSTRACT_STMT(Node) 15093 #define STMT(Node, Base) case Expr::Node##Class: 15094 #define EXPR(Node, Base) 15095 #include "clang/AST/StmtNodes.inc" 15096 case Expr::PredefinedExprClass: 15097 case Expr::FloatingLiteralClass: 15098 case Expr::ImaginaryLiteralClass: 15099 case Expr::StringLiteralClass: 15100 case Expr::ArraySubscriptExprClass: 15101 case Expr::MatrixSubscriptExprClass: 15102 case Expr::OMPArraySectionExprClass: 15103 case Expr::OMPArrayShapingExprClass: 15104 case Expr::OMPIteratorExprClass: 15105 case Expr::MemberExprClass: 15106 case Expr::CompoundAssignOperatorClass: 15107 case Expr::CompoundLiteralExprClass: 15108 case Expr::ExtVectorElementExprClass: 15109 case Expr::DesignatedInitExprClass: 15110 case Expr::ArrayInitLoopExprClass: 15111 case Expr::ArrayInitIndexExprClass: 15112 case Expr::NoInitExprClass: 15113 case Expr::DesignatedInitUpdateExprClass: 15114 case Expr::ImplicitValueInitExprClass: 15115 case Expr::ParenListExprClass: 15116 case Expr::VAArgExprClass: 15117 case Expr::AddrLabelExprClass: 15118 case Expr::StmtExprClass: 15119 case Expr::CXXMemberCallExprClass: 15120 case Expr::CUDAKernelCallExprClass: 15121 case Expr::CXXAddrspaceCastExprClass: 15122 case Expr::CXXDynamicCastExprClass: 15123 case Expr::CXXTypeidExprClass: 15124 case Expr::CXXUuidofExprClass: 15125 case Expr::MSPropertyRefExprClass: 15126 case Expr::MSPropertySubscriptExprClass: 15127 case Expr::CXXNullPtrLiteralExprClass: 15128 case Expr::UserDefinedLiteralClass: 15129 case Expr::CXXThisExprClass: 15130 case Expr::CXXThrowExprClass: 15131 case Expr::CXXNewExprClass: 15132 case Expr::CXXDeleteExprClass: 15133 case Expr::CXXPseudoDestructorExprClass: 15134 case Expr::UnresolvedLookupExprClass: 15135 case Expr::TypoExprClass: 15136 case Expr::RecoveryExprClass: 15137 case Expr::DependentScopeDeclRefExprClass: 15138 case Expr::CXXConstructExprClass: 15139 case Expr::CXXInheritedCtorInitExprClass: 15140 case Expr::CXXStdInitializerListExprClass: 15141 case Expr::CXXBindTemporaryExprClass: 15142 case Expr::ExprWithCleanupsClass: 15143 case Expr::CXXTemporaryObjectExprClass: 15144 case Expr::CXXUnresolvedConstructExprClass: 15145 case Expr::CXXDependentScopeMemberExprClass: 15146 case Expr::UnresolvedMemberExprClass: 15147 case Expr::ObjCStringLiteralClass: 15148 case Expr::ObjCBoxedExprClass: 15149 case Expr::ObjCArrayLiteralClass: 15150 case Expr::ObjCDictionaryLiteralClass: 15151 case Expr::ObjCEncodeExprClass: 15152 case Expr::ObjCMessageExprClass: 15153 case Expr::ObjCSelectorExprClass: 15154 case Expr::ObjCProtocolExprClass: 15155 case Expr::ObjCIvarRefExprClass: 15156 case Expr::ObjCPropertyRefExprClass: 15157 case Expr::ObjCSubscriptRefExprClass: 15158 case Expr::ObjCIsaExprClass: 15159 case Expr::ObjCAvailabilityCheckExprClass: 15160 case Expr::ShuffleVectorExprClass: 15161 case Expr::ConvertVectorExprClass: 15162 case Expr::BlockExprClass: 15163 case Expr::NoStmtClass: 15164 case Expr::OpaqueValueExprClass: 15165 case Expr::PackExpansionExprClass: 15166 case Expr::SubstNonTypeTemplateParmPackExprClass: 15167 case Expr::FunctionParmPackExprClass: 15168 case Expr::AsTypeExprClass: 15169 case Expr::ObjCIndirectCopyRestoreExprClass: 15170 case Expr::MaterializeTemporaryExprClass: 15171 case Expr::PseudoObjectExprClass: 15172 case Expr::AtomicExprClass: 15173 case Expr::LambdaExprClass: 15174 case Expr::CXXFoldExprClass: 15175 case Expr::CoawaitExprClass: 15176 case Expr::DependentCoawaitExprClass: 15177 case Expr::CoyieldExprClass: 15178 case Expr::SYCLUniqueStableNameExprClass: 15179 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15180 15181 case Expr::InitListExprClass: { 15182 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15183 // form "T x = { a };" is equivalent to "T x = a;". 15184 // Unless we're initializing a reference, T is a scalar as it is known to be 15185 // of integral or enumeration type. 15186 if (E->isRValue()) 15187 if (cast<InitListExpr>(E)->getNumInits() == 1) 15188 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15189 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15190 } 15191 15192 case Expr::SizeOfPackExprClass: 15193 case Expr::GNUNullExprClass: 15194 case Expr::SourceLocExprClass: 15195 return NoDiag(); 15196 15197 case Expr::SubstNonTypeTemplateParmExprClass: 15198 return 15199 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15200 15201 case Expr::ConstantExprClass: 15202 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15203 15204 case Expr::ParenExprClass: 15205 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15206 case Expr::GenericSelectionExprClass: 15207 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15208 case Expr::IntegerLiteralClass: 15209 case Expr::FixedPointLiteralClass: 15210 case Expr::CharacterLiteralClass: 15211 case Expr::ObjCBoolLiteralExprClass: 15212 case Expr::CXXBoolLiteralExprClass: 15213 case Expr::CXXScalarValueInitExprClass: 15214 case Expr::TypeTraitExprClass: 15215 case Expr::ConceptSpecializationExprClass: 15216 case Expr::RequiresExprClass: 15217 case Expr::ArrayTypeTraitExprClass: 15218 case Expr::ExpressionTraitExprClass: 15219 case Expr::CXXNoexceptExprClass: 15220 return NoDiag(); 15221 case Expr::CallExprClass: 15222 case Expr::CXXOperatorCallExprClass: { 15223 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15224 // constant expressions, but they can never be ICEs because an ICE cannot 15225 // contain an operand of (pointer to) function type. 15226 const CallExpr *CE = cast<CallExpr>(E); 15227 if (CE->getBuiltinCallee()) 15228 return CheckEvalInICE(E, Ctx); 15229 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15230 } 15231 case Expr::CXXRewrittenBinaryOperatorClass: 15232 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15233 Ctx); 15234 case Expr::DeclRefExprClass: { 15235 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15236 if (isa<EnumConstantDecl>(D)) 15237 return NoDiag(); 15238 15239 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15240 // integer variables in constant expressions: 15241 // 15242 // C++ 7.1.5.1p2 15243 // A variable of non-volatile const-qualified integral or enumeration 15244 // type initialized by an ICE can be used in ICEs. 15245 // 15246 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15247 // that mode, use of reference variables should not be allowed. 15248 const VarDecl *VD = dyn_cast<VarDecl>(D); 15249 if (VD && VD->isUsableInConstantExpressions(Ctx) && 15250 !VD->getType()->isReferenceType()) 15251 return NoDiag(); 15252 15253 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15254 } 15255 case Expr::UnaryOperatorClass: { 15256 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15257 switch (Exp->getOpcode()) { 15258 case UO_PostInc: 15259 case UO_PostDec: 15260 case UO_PreInc: 15261 case UO_PreDec: 15262 case UO_AddrOf: 15263 case UO_Deref: 15264 case UO_Coawait: 15265 // C99 6.6/3 allows increment and decrement within unevaluated 15266 // subexpressions of constant expressions, but they can never be ICEs 15267 // because an ICE cannot contain an lvalue operand. 15268 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15269 case UO_Extension: 15270 case UO_LNot: 15271 case UO_Plus: 15272 case UO_Minus: 15273 case UO_Not: 15274 case UO_Real: 15275 case UO_Imag: 15276 return CheckICE(Exp->getSubExpr(), Ctx); 15277 } 15278 llvm_unreachable("invalid unary operator class"); 15279 } 15280 case Expr::OffsetOfExprClass: { 15281 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15282 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15283 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15284 // compliance: we should warn earlier for offsetof expressions with 15285 // array subscripts that aren't ICEs, and if the array subscripts 15286 // are ICEs, the value of the offsetof must be an integer constant. 15287 return CheckEvalInICE(E, Ctx); 15288 } 15289 case Expr::UnaryExprOrTypeTraitExprClass: { 15290 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15291 if ((Exp->getKind() == UETT_SizeOf) && 15292 Exp->getTypeOfArgument()->isVariableArrayType()) 15293 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15294 return NoDiag(); 15295 } 15296 case Expr::BinaryOperatorClass: { 15297 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15298 switch (Exp->getOpcode()) { 15299 case BO_PtrMemD: 15300 case BO_PtrMemI: 15301 case BO_Assign: 15302 case BO_MulAssign: 15303 case BO_DivAssign: 15304 case BO_RemAssign: 15305 case BO_AddAssign: 15306 case BO_SubAssign: 15307 case BO_ShlAssign: 15308 case BO_ShrAssign: 15309 case BO_AndAssign: 15310 case BO_XorAssign: 15311 case BO_OrAssign: 15312 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15313 // constant expressions, but they can never be ICEs because an ICE cannot 15314 // contain an lvalue operand. 15315 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15316 15317 case BO_Mul: 15318 case BO_Div: 15319 case BO_Rem: 15320 case BO_Add: 15321 case BO_Sub: 15322 case BO_Shl: 15323 case BO_Shr: 15324 case BO_LT: 15325 case BO_GT: 15326 case BO_LE: 15327 case BO_GE: 15328 case BO_EQ: 15329 case BO_NE: 15330 case BO_And: 15331 case BO_Xor: 15332 case BO_Or: 15333 case BO_Comma: 15334 case BO_Cmp: { 15335 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15336 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15337 if (Exp->getOpcode() == BO_Div || 15338 Exp->getOpcode() == BO_Rem) { 15339 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15340 // we don't evaluate one. 15341 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15342 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15343 if (REval == 0) 15344 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15345 if (REval.isSigned() && REval.isAllOnesValue()) { 15346 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15347 if (LEval.isMinSignedValue()) 15348 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15349 } 15350 } 15351 } 15352 if (Exp->getOpcode() == BO_Comma) { 15353 if (Ctx.getLangOpts().C99) { 15354 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15355 // if it isn't evaluated. 15356 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15357 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15358 } else { 15359 // In both C89 and C++, commas in ICEs are illegal. 15360 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15361 } 15362 } 15363 return Worst(LHSResult, RHSResult); 15364 } 15365 case BO_LAnd: 15366 case BO_LOr: { 15367 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15368 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15369 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15370 // Rare case where the RHS has a comma "side-effect"; we need 15371 // to actually check the condition to see whether the side 15372 // with the comma is evaluated. 15373 if ((Exp->getOpcode() == BO_LAnd) != 15374 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15375 return RHSResult; 15376 return NoDiag(); 15377 } 15378 15379 return Worst(LHSResult, RHSResult); 15380 } 15381 } 15382 llvm_unreachable("invalid binary operator kind"); 15383 } 15384 case Expr::ImplicitCastExprClass: 15385 case Expr::CStyleCastExprClass: 15386 case Expr::CXXFunctionalCastExprClass: 15387 case Expr::CXXStaticCastExprClass: 15388 case Expr::CXXReinterpretCastExprClass: 15389 case Expr::CXXConstCastExprClass: 15390 case Expr::ObjCBridgedCastExprClass: { 15391 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15392 if (isa<ExplicitCastExpr>(E)) { 15393 if (const FloatingLiteral *FL 15394 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15395 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15396 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15397 APSInt IgnoredVal(DestWidth, !DestSigned); 15398 bool Ignored; 15399 // If the value does not fit in the destination type, the behavior is 15400 // undefined, so we are not required to treat it as a constant 15401 // expression. 15402 if (FL->getValue().convertToInteger(IgnoredVal, 15403 llvm::APFloat::rmTowardZero, 15404 &Ignored) & APFloat::opInvalidOp) 15405 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15406 return NoDiag(); 15407 } 15408 } 15409 switch (cast<CastExpr>(E)->getCastKind()) { 15410 case CK_LValueToRValue: 15411 case CK_AtomicToNonAtomic: 15412 case CK_NonAtomicToAtomic: 15413 case CK_NoOp: 15414 case CK_IntegralToBoolean: 15415 case CK_IntegralCast: 15416 return CheckICE(SubExpr, Ctx); 15417 default: 15418 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15419 } 15420 } 15421 case Expr::BinaryConditionalOperatorClass: { 15422 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15423 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15424 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15425 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15426 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15427 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15428 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15429 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15430 return FalseResult; 15431 } 15432 case Expr::ConditionalOperatorClass: { 15433 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15434 // If the condition (ignoring parens) is a __builtin_constant_p call, 15435 // then only the true side is actually considered in an integer constant 15436 // expression, and it is fully evaluated. This is an important GNU 15437 // extension. See GCC PR38377 for discussion. 15438 if (const CallExpr *CallCE 15439 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15440 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15441 return CheckEvalInICE(E, Ctx); 15442 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15443 if (CondResult.Kind == IK_NotICE) 15444 return CondResult; 15445 15446 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15447 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15448 15449 if (TrueResult.Kind == IK_NotICE) 15450 return TrueResult; 15451 if (FalseResult.Kind == IK_NotICE) 15452 return FalseResult; 15453 if (CondResult.Kind == IK_ICEIfUnevaluated) 15454 return CondResult; 15455 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15456 return NoDiag(); 15457 // Rare case where the diagnostics depend on which side is evaluated 15458 // Note that if we get here, CondResult is 0, and at least one of 15459 // TrueResult and FalseResult is non-zero. 15460 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15461 return FalseResult; 15462 return TrueResult; 15463 } 15464 case Expr::CXXDefaultArgExprClass: 15465 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15466 case Expr::CXXDefaultInitExprClass: 15467 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15468 case Expr::ChooseExprClass: { 15469 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15470 } 15471 case Expr::BuiltinBitCastExprClass: { 15472 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15473 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15474 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15475 } 15476 } 15477 15478 llvm_unreachable("Invalid StmtClass!"); 15479 } 15480 15481 /// Evaluate an expression as a C++11 integral constant expression. 15482 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15483 const Expr *E, 15484 llvm::APSInt *Value, 15485 SourceLocation *Loc) { 15486 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15487 if (Loc) *Loc = E->getExprLoc(); 15488 return false; 15489 } 15490 15491 APValue Result; 15492 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15493 return false; 15494 15495 if (!Result.isInt()) { 15496 if (Loc) *Loc = E->getExprLoc(); 15497 return false; 15498 } 15499 15500 if (Value) *Value = Result.getInt(); 15501 return true; 15502 } 15503 15504 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15505 SourceLocation *Loc) const { 15506 assert(!isValueDependent() && 15507 "Expression evaluator can't be called on a dependent expression."); 15508 15509 if (Ctx.getLangOpts().CPlusPlus11) 15510 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15511 15512 ICEDiag D = CheckICE(this, Ctx); 15513 if (D.Kind != IK_ICE) { 15514 if (Loc) *Loc = D.Loc; 15515 return false; 15516 } 15517 return true; 15518 } 15519 15520 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15521 SourceLocation *Loc, 15522 bool isEvaluated) const { 15523 assert(!isValueDependent() && 15524 "Expression evaluator can't be called on a dependent expression."); 15525 15526 APSInt Value; 15527 15528 if (Ctx.getLangOpts().CPlusPlus11) { 15529 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15530 return Value; 15531 return None; 15532 } 15533 15534 if (!isIntegerConstantExpr(Ctx, Loc)) 15535 return None; 15536 15537 // The only possible side-effects here are due to UB discovered in the 15538 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15539 // required to treat the expression as an ICE, so we produce the folded 15540 // value. 15541 EvalResult ExprResult; 15542 Expr::EvalStatus Status; 15543 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15544 Info.InConstantContext = true; 15545 15546 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15547 llvm_unreachable("ICE cannot be evaluated!"); 15548 15549 return ExprResult.Val.getInt(); 15550 } 15551 15552 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15553 assert(!isValueDependent() && 15554 "Expression evaluator can't be called on a dependent expression."); 15555 15556 return CheckICE(this, Ctx).Kind == IK_ICE; 15557 } 15558 15559 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15560 SourceLocation *Loc) const { 15561 assert(!isValueDependent() && 15562 "Expression evaluator can't be called on a dependent expression."); 15563 15564 // We support this checking in C++98 mode in order to diagnose compatibility 15565 // issues. 15566 assert(Ctx.getLangOpts().CPlusPlus); 15567 15568 // Build evaluation settings. 15569 Expr::EvalStatus Status; 15570 SmallVector<PartialDiagnosticAt, 8> Diags; 15571 Status.Diag = &Diags; 15572 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15573 15574 APValue Scratch; 15575 bool IsConstExpr = 15576 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15577 // FIXME: We don't produce a diagnostic for this, but the callers that 15578 // call us on arbitrary full-expressions should generally not care. 15579 Info.discardCleanups() && !Status.HasSideEffects; 15580 15581 if (!Diags.empty()) { 15582 IsConstExpr = false; 15583 if (Loc) *Loc = Diags[0].first; 15584 } else if (!IsConstExpr) { 15585 // FIXME: This shouldn't happen. 15586 if (Loc) *Loc = getExprLoc(); 15587 } 15588 15589 return IsConstExpr; 15590 } 15591 15592 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15593 const FunctionDecl *Callee, 15594 ArrayRef<const Expr*> Args, 15595 const Expr *This) const { 15596 assert(!isValueDependent() && 15597 "Expression evaluator can't be called on a dependent expression."); 15598 15599 Expr::EvalStatus Status; 15600 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15601 Info.InConstantContext = true; 15602 15603 LValue ThisVal; 15604 const LValue *ThisPtr = nullptr; 15605 if (This) { 15606 #ifndef NDEBUG 15607 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15608 assert(MD && "Don't provide `this` for non-methods."); 15609 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15610 #endif 15611 if (!This->isValueDependent() && 15612 EvaluateObjectArgument(Info, This, ThisVal) && 15613 !Info.EvalStatus.HasSideEffects) 15614 ThisPtr = &ThisVal; 15615 15616 // Ignore any side-effects from a failed evaluation. This is safe because 15617 // they can't interfere with any other argument evaluation. 15618 Info.EvalStatus.HasSideEffects = false; 15619 } 15620 15621 CallRef Call = Info.CurrentCall->createCall(Callee); 15622 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15623 I != E; ++I) { 15624 unsigned Idx = I - Args.begin(); 15625 if (Idx >= Callee->getNumParams()) 15626 break; 15627 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15628 if ((*I)->isValueDependent() || 15629 !EvaluateCallArg(PVD, *I, Call, Info) || 15630 Info.EvalStatus.HasSideEffects) { 15631 // If evaluation fails, throw away the argument entirely. 15632 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15633 *Slot = APValue(); 15634 } 15635 15636 // Ignore any side-effects from a failed evaluation. This is safe because 15637 // they can't interfere with any other argument evaluation. 15638 Info.EvalStatus.HasSideEffects = false; 15639 } 15640 15641 // Parameter cleanups happen in the caller and are not part of this 15642 // evaluation. 15643 Info.discardCleanups(); 15644 Info.EvalStatus.HasSideEffects = false; 15645 15646 // Build fake call to Callee. 15647 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15648 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15649 FullExpressionRAII Scope(Info); 15650 return Evaluate(Value, Info, this) && Scope.destroy() && 15651 !Info.EvalStatus.HasSideEffects; 15652 } 15653 15654 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15655 SmallVectorImpl< 15656 PartialDiagnosticAt> &Diags) { 15657 // FIXME: It would be useful to check constexpr function templates, but at the 15658 // moment the constant expression evaluator cannot cope with the non-rigorous 15659 // ASTs which we build for dependent expressions. 15660 if (FD->isDependentContext()) 15661 return true; 15662 15663 Expr::EvalStatus Status; 15664 Status.Diag = &Diags; 15665 15666 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15667 Info.InConstantContext = true; 15668 Info.CheckingPotentialConstantExpression = true; 15669 15670 // The constexpr VM attempts to compile all methods to bytecode here. 15671 if (Info.EnableNewConstInterp) { 15672 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15673 return Diags.empty(); 15674 } 15675 15676 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15677 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15678 15679 // Fabricate an arbitrary expression on the stack and pretend that it 15680 // is a temporary being used as the 'this' pointer. 15681 LValue This; 15682 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15683 This.set({&VIE, Info.CurrentCall->Index}); 15684 15685 ArrayRef<const Expr*> Args; 15686 15687 APValue Scratch; 15688 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15689 // Evaluate the call as a constant initializer, to allow the construction 15690 // of objects of non-literal types. 15691 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15692 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15693 } else { 15694 SourceLocation Loc = FD->getLocation(); 15695 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15696 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15697 } 15698 15699 return Diags.empty(); 15700 } 15701 15702 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15703 const FunctionDecl *FD, 15704 SmallVectorImpl< 15705 PartialDiagnosticAt> &Diags) { 15706 assert(!E->isValueDependent() && 15707 "Expression evaluator can't be called on a dependent expression."); 15708 15709 Expr::EvalStatus Status; 15710 Status.Diag = &Diags; 15711 15712 EvalInfo Info(FD->getASTContext(), Status, 15713 EvalInfo::EM_ConstantExpressionUnevaluated); 15714 Info.InConstantContext = true; 15715 Info.CheckingPotentialConstantExpression = true; 15716 15717 // Fabricate a call stack frame to give the arguments a plausible cover story. 15718 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15719 15720 APValue ResultScratch; 15721 Evaluate(ResultScratch, Info, E); 15722 return Diags.empty(); 15723 } 15724 15725 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15726 unsigned Type) const { 15727 if (!getType()->isPointerType()) 15728 return false; 15729 15730 Expr::EvalStatus Status; 15731 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15732 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15733 } 15734