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/FixedPoint.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/SaveAndRestore.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <cstring> 60 #include <functional> 61 62 #define DEBUG_TYPE "exprconstant" 63 64 using namespace clang; 65 using llvm::APInt; 66 using llvm::APSInt; 67 using llvm::APFloat; 68 using llvm::Optional; 69 70 namespace { 71 struct LValue; 72 class CallStackFrame; 73 class EvalInfo; 74 75 using SourceLocExprScopeGuard = 76 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 77 78 static QualType getType(APValue::LValueBase B) { 79 if (!B) return QualType(); 80 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 81 // FIXME: It's unclear where we're supposed to take the type from, and 82 // this actually matters for arrays of unknown bound. Eg: 83 // 84 // extern int arr[]; void f() { extern int arr[3]; }; 85 // constexpr int *p = &arr[1]; // valid? 86 // 87 // For now, we take the array bound from the most recent declaration. 88 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 89 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 90 QualType T = Redecl->getType(); 91 if (!T->isIncompleteArrayType()) 92 return T; 93 } 94 return D->getType(); 95 } 96 97 if (B.is<TypeInfoLValue>()) 98 return B.getTypeInfoType(); 99 100 if (B.is<DynamicAllocLValue>()) 101 return B.getDynamicAllocType(); 102 103 const Expr *Base = B.get<const Expr*>(); 104 105 // For a materialized temporary, the type of the temporary we materialized 106 // may not be the type of the expression. 107 if (const MaterializeTemporaryExpr *MTE = 108 dyn_cast<MaterializeTemporaryExpr>(Base)) { 109 SmallVector<const Expr *, 2> CommaLHSs; 110 SmallVector<SubobjectAdjustment, 2> Adjustments; 111 const Expr *Temp = MTE->getSubExpr(); 112 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 113 Adjustments); 114 // Keep any cv-qualifiers from the reference if we generated a temporary 115 // for it directly. Otherwise use the type after adjustment. 116 if (!Adjustments.empty()) 117 return Inner->getType(); 118 } 119 120 return Base->getType(); 121 } 122 123 /// Get an LValue path entry, which is known to not be an array index, as a 124 /// field declaration. 125 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 126 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 127 } 128 /// Get an LValue path entry, which is known to not be an array index, as a 129 /// base class declaration. 130 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 131 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 132 } 133 /// Determine whether this LValue path entry for a base class names a virtual 134 /// base class. 135 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 136 return E.getAsBaseOrMember().getInt(); 137 } 138 139 /// Given an expression, determine the type used to store the result of 140 /// evaluating that expression. 141 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 142 if (E->isRValue()) 143 return E->getType(); 144 return Ctx.getLValueReferenceType(E->getType()); 145 } 146 147 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 148 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 149 const FunctionDecl *Callee = CE->getDirectCallee(); 150 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 151 } 152 153 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 154 /// This will look through a single cast. 155 /// 156 /// Returns null if we couldn't unwrap a function with alloc_size. 157 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 158 if (!E->getType()->isPointerType()) 159 return nullptr; 160 161 E = E->IgnoreParens(); 162 // If we're doing a variable assignment from e.g. malloc(N), there will 163 // probably be a cast of some kind. In exotic cases, we might also see a 164 // top-level ExprWithCleanups. Ignore them either way. 165 if (const auto *FE = dyn_cast<FullExpr>(E)) 166 E = FE->getSubExpr()->IgnoreParens(); 167 168 if (const auto *Cast = dyn_cast<CastExpr>(E)) 169 E = Cast->getSubExpr()->IgnoreParens(); 170 171 if (const auto *CE = dyn_cast<CallExpr>(E)) 172 return getAllocSizeAttr(CE) ? CE : nullptr; 173 return nullptr; 174 } 175 176 /// Determines whether or not the given Base contains a call to a function 177 /// with the alloc_size attribute. 178 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 179 const auto *E = Base.dyn_cast<const Expr *>(); 180 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 181 } 182 183 /// The bound to claim that an array of unknown bound has. 184 /// The value in MostDerivedArraySize is undefined in this case. So, set it 185 /// to an arbitrary value that's likely to loudly break things if it's used. 186 static const uint64_t AssumedSizeForUnsizedArray = 187 std::numeric_limits<uint64_t>::max() / 2; 188 189 /// Determines if an LValue with the given LValueBase will have an unsized 190 /// array in its designator. 191 /// Find the path length and type of the most-derived subobject in the given 192 /// path, and find the size of the containing array, if any. 193 static unsigned 194 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 195 ArrayRef<APValue::LValuePathEntry> Path, 196 uint64_t &ArraySize, QualType &Type, bool &IsArray, 197 bool &FirstEntryIsUnsizedArray) { 198 // This only accepts LValueBases from APValues, and APValues don't support 199 // arrays that lack size info. 200 assert(!isBaseAnAllocSizeCall(Base) && 201 "Unsized arrays shouldn't appear here"); 202 unsigned MostDerivedLength = 0; 203 Type = getType(Base); 204 205 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 206 if (Type->isArrayType()) { 207 const ArrayType *AT = Ctx.getAsArrayType(Type); 208 Type = AT->getElementType(); 209 MostDerivedLength = I + 1; 210 IsArray = true; 211 212 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 213 ArraySize = CAT->getSize().getZExtValue(); 214 } else { 215 assert(I == 0 && "unexpected unsized array designator"); 216 FirstEntryIsUnsizedArray = true; 217 ArraySize = AssumedSizeForUnsizedArray; 218 } 219 } else if (Type->isAnyComplexType()) { 220 const ComplexType *CT = Type->castAs<ComplexType>(); 221 Type = CT->getElementType(); 222 ArraySize = 2; 223 MostDerivedLength = I + 1; 224 IsArray = true; 225 } else if (const FieldDecl *FD = getAsField(Path[I])) { 226 Type = FD->getType(); 227 ArraySize = 0; 228 MostDerivedLength = I + 1; 229 IsArray = false; 230 } else { 231 // Path[I] describes a base class. 232 ArraySize = 0; 233 IsArray = false; 234 } 235 } 236 return MostDerivedLength; 237 } 238 239 /// A path from a glvalue to a subobject of that glvalue. 240 struct SubobjectDesignator { 241 /// True if the subobject was named in a manner not supported by C++11. Such 242 /// lvalues can still be folded, but they are not core constant expressions 243 /// and we cannot perform lvalue-to-rvalue conversions on them. 244 unsigned Invalid : 1; 245 246 /// Is this a pointer one past the end of an object? 247 unsigned IsOnePastTheEnd : 1; 248 249 /// Indicator of whether the first entry is an unsized array. 250 unsigned FirstEntryIsAnUnsizedArray : 1; 251 252 /// Indicator of whether the most-derived object is an array element. 253 unsigned MostDerivedIsArrayElement : 1; 254 255 /// The length of the path to the most-derived object of which this is a 256 /// subobject. 257 unsigned MostDerivedPathLength : 28; 258 259 /// The size of the array of which the most-derived object is an element. 260 /// This will always be 0 if the most-derived object is not an array 261 /// element. 0 is not an indicator of whether or not the most-derived object 262 /// is an array, however, because 0-length arrays are allowed. 263 /// 264 /// If the current array is an unsized array, the value of this is 265 /// undefined. 266 uint64_t MostDerivedArraySize; 267 268 /// The type of the most derived object referred to by this address. 269 QualType MostDerivedType; 270 271 typedef APValue::LValuePathEntry PathEntry; 272 273 /// The entries on the path from the glvalue to the designated subobject. 274 SmallVector<PathEntry, 8> Entries; 275 276 SubobjectDesignator() : Invalid(true) {} 277 278 explicit SubobjectDesignator(QualType T) 279 : Invalid(false), IsOnePastTheEnd(false), 280 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 281 MostDerivedPathLength(0), MostDerivedArraySize(0), 282 MostDerivedType(T) {} 283 284 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 285 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 286 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 287 MostDerivedPathLength(0), MostDerivedArraySize(0) { 288 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 289 if (!Invalid) { 290 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 291 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 292 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 293 if (V.getLValueBase()) { 294 bool IsArray = false; 295 bool FirstIsUnsizedArray = false; 296 MostDerivedPathLength = findMostDerivedSubobject( 297 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 298 MostDerivedType, IsArray, FirstIsUnsizedArray); 299 MostDerivedIsArrayElement = IsArray; 300 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 301 } 302 } 303 } 304 305 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 306 unsigned NewLength) { 307 if (Invalid) 308 return; 309 310 assert(Base && "cannot truncate path for null pointer"); 311 assert(NewLength <= Entries.size() && "not a truncation"); 312 313 if (NewLength == Entries.size()) 314 return; 315 Entries.resize(NewLength); 316 317 bool IsArray = false; 318 bool FirstIsUnsizedArray = false; 319 MostDerivedPathLength = findMostDerivedSubobject( 320 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 321 FirstIsUnsizedArray); 322 MostDerivedIsArrayElement = IsArray; 323 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 324 } 325 326 void setInvalid() { 327 Invalid = true; 328 Entries.clear(); 329 } 330 331 /// Determine whether the most derived subobject is an array without a 332 /// known bound. 333 bool isMostDerivedAnUnsizedArray() const { 334 assert(!Invalid && "Calling this makes no sense on invalid designators"); 335 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 336 } 337 338 /// Determine what the most derived array's size is. Results in an assertion 339 /// failure if the most derived array lacks a size. 340 uint64_t getMostDerivedArraySize() const { 341 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 342 return MostDerivedArraySize; 343 } 344 345 /// Determine whether this is a one-past-the-end pointer. 346 bool isOnePastTheEnd() const { 347 assert(!Invalid); 348 if (IsOnePastTheEnd) 349 return true; 350 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 351 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 352 MostDerivedArraySize) 353 return true; 354 return false; 355 } 356 357 /// Get the range of valid index adjustments in the form 358 /// {maximum value that can be subtracted from this pointer, 359 /// maximum value that can be added to this pointer} 360 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 361 if (Invalid || isMostDerivedAnUnsizedArray()) 362 return {0, 0}; 363 364 // [expr.add]p4: For the purposes of these operators, a pointer to a 365 // nonarray object behaves the same as a pointer to the first element of 366 // an array of length one with the type of the object as its element type. 367 bool IsArray = MostDerivedPathLength == Entries.size() && 368 MostDerivedIsArrayElement; 369 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 370 : (uint64_t)IsOnePastTheEnd; 371 uint64_t ArraySize = 372 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 373 return {ArrayIndex, ArraySize - ArrayIndex}; 374 } 375 376 /// Check that this refers to a valid subobject. 377 bool isValidSubobject() const { 378 if (Invalid) 379 return false; 380 return !isOnePastTheEnd(); 381 } 382 /// Check that this refers to a valid subobject, and if not, produce a 383 /// relevant diagnostic and set the designator as invalid. 384 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 385 386 /// Get the type of the designated object. 387 QualType getType(ASTContext &Ctx) const { 388 assert(!Invalid && "invalid designator has no subobject type"); 389 return MostDerivedPathLength == Entries.size() 390 ? MostDerivedType 391 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 392 } 393 394 /// Update this designator to refer to the first element within this array. 395 void addArrayUnchecked(const ConstantArrayType *CAT) { 396 Entries.push_back(PathEntry::ArrayIndex(0)); 397 398 // This is a most-derived object. 399 MostDerivedType = CAT->getElementType(); 400 MostDerivedIsArrayElement = true; 401 MostDerivedArraySize = CAT->getSize().getZExtValue(); 402 MostDerivedPathLength = Entries.size(); 403 } 404 /// Update this designator to refer to the first element within the array of 405 /// elements of type T. This is an array of unknown size. 406 void addUnsizedArrayUnchecked(QualType ElemTy) { 407 Entries.push_back(PathEntry::ArrayIndex(0)); 408 409 MostDerivedType = ElemTy; 410 MostDerivedIsArrayElement = true; 411 // The value in MostDerivedArraySize is undefined in this case. So, set it 412 // to an arbitrary value that's likely to loudly break things if it's 413 // used. 414 MostDerivedArraySize = AssumedSizeForUnsizedArray; 415 MostDerivedPathLength = Entries.size(); 416 } 417 /// Update this designator to refer to the given base or member of this 418 /// object. 419 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 420 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 421 422 // If this isn't a base class, it's a new most-derived object. 423 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 424 MostDerivedType = FD->getType(); 425 MostDerivedIsArrayElement = false; 426 MostDerivedArraySize = 0; 427 MostDerivedPathLength = Entries.size(); 428 } 429 } 430 /// Update this designator to refer to the given complex component. 431 void addComplexUnchecked(QualType EltTy, bool Imag) { 432 Entries.push_back(PathEntry::ArrayIndex(Imag)); 433 434 // This is technically a most-derived object, though in practice this 435 // is unlikely to matter. 436 MostDerivedType = EltTy; 437 MostDerivedIsArrayElement = true; 438 MostDerivedArraySize = 2; 439 MostDerivedPathLength = Entries.size(); 440 } 441 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 442 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 443 const APSInt &N); 444 /// Add N to the address of this subobject. 445 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 446 if (Invalid || !N) return; 447 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 448 if (isMostDerivedAnUnsizedArray()) { 449 diagnoseUnsizedArrayPointerArithmetic(Info, E); 450 // Can't verify -- trust that the user is doing the right thing (or if 451 // not, trust that the caller will catch the bad behavior). 452 // FIXME: Should we reject if this overflows, at least? 453 Entries.back() = PathEntry::ArrayIndex( 454 Entries.back().getAsArrayIndex() + TruncatedN); 455 return; 456 } 457 458 // [expr.add]p4: For the purposes of these operators, a pointer to a 459 // nonarray object behaves the same as a pointer to the first element of 460 // an array of length one with the type of the object as its element type. 461 bool IsArray = MostDerivedPathLength == Entries.size() && 462 MostDerivedIsArrayElement; 463 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 464 : (uint64_t)IsOnePastTheEnd; 465 uint64_t ArraySize = 466 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 467 468 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 469 // Calculate the actual index in a wide enough type, so we can include 470 // it in the note. 471 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 472 (llvm::APInt&)N += ArrayIndex; 473 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 474 diagnosePointerArithmetic(Info, E, N); 475 setInvalid(); 476 return; 477 } 478 479 ArrayIndex += TruncatedN; 480 assert(ArrayIndex <= ArraySize && 481 "bounds check succeeded for out-of-bounds index"); 482 483 if (IsArray) 484 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 485 else 486 IsOnePastTheEnd = (ArrayIndex != 0); 487 } 488 }; 489 490 /// A stack frame in the constexpr call stack. 491 class CallStackFrame : public interp::Frame { 492 public: 493 EvalInfo &Info; 494 495 /// Parent - The caller of this stack frame. 496 CallStackFrame *Caller; 497 498 /// Callee - The function which was called. 499 const FunctionDecl *Callee; 500 501 /// This - The binding for the this pointer in this call, if any. 502 const LValue *This; 503 504 /// Arguments - Parameter bindings for this function call, indexed by 505 /// parameters' function scope indices. 506 APValue *Arguments; 507 508 /// Source location information about the default argument or default 509 /// initializer expression we're evaluating, if any. 510 CurrentSourceLocExprScope CurSourceLocExprScope; 511 512 // Note that we intentionally use std::map here so that references to 513 // values are stable. 514 typedef std::pair<const void *, unsigned> MapKeyTy; 515 typedef std::map<MapKeyTy, APValue> MapTy; 516 /// Temporaries - Temporary lvalues materialized within this stack frame. 517 MapTy Temporaries; 518 519 /// CallLoc - The location of the call expression for this call. 520 SourceLocation CallLoc; 521 522 /// Index - The call index of this call. 523 unsigned Index; 524 525 /// The stack of integers for tracking version numbers for temporaries. 526 SmallVector<unsigned, 2> TempVersionStack = {1}; 527 unsigned CurTempVersion = TempVersionStack.back(); 528 529 unsigned getTempVersion() const { return TempVersionStack.back(); } 530 531 void pushTempVersion() { 532 TempVersionStack.push_back(++CurTempVersion); 533 } 534 535 void popTempVersion() { 536 TempVersionStack.pop_back(); 537 } 538 539 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 540 // on the overall stack usage of deeply-recursing constexpr evaluations. 541 // (We should cache this map rather than recomputing it repeatedly.) 542 // But let's try this and see how it goes; we can look into caching the map 543 // as a later change. 544 545 /// LambdaCaptureFields - Mapping from captured variables/this to 546 /// corresponding data members in the closure class. 547 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 548 FieldDecl *LambdaThisCaptureField; 549 550 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 551 const FunctionDecl *Callee, const LValue *This, 552 APValue *Arguments); 553 ~CallStackFrame(); 554 555 // Return the temporary for Key whose version number is Version. 556 APValue *getTemporary(const void *Key, unsigned Version) { 557 MapKeyTy KV(Key, Version); 558 auto LB = Temporaries.lower_bound(KV); 559 if (LB != Temporaries.end() && LB->first == KV) 560 return &LB->second; 561 // Pair (Key,Version) wasn't found in the map. Check that no elements 562 // in the map have 'Key' as their key. 563 assert((LB == Temporaries.end() || LB->first.first != Key) && 564 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 565 "Element with key 'Key' found in map"); 566 return nullptr; 567 } 568 569 // Return the current temporary for Key in the map. 570 APValue *getCurrentTemporary(const void *Key) { 571 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 572 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 573 return &std::prev(UB)->second; 574 return nullptr; 575 } 576 577 // Return the version number of the current temporary for Key. 578 unsigned getCurrentTemporaryVersion(const void *Key) const { 579 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 580 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 581 return std::prev(UB)->first.second; 582 return 0; 583 } 584 585 /// Allocate storage for an object of type T in this stack frame. 586 /// Populates LV with a handle to the created object. Key identifies 587 /// the temporary within the stack frame, and must not be reused without 588 /// bumping the temporary version number. 589 template<typename KeyT> 590 APValue &createTemporary(const KeyT *Key, QualType T, 591 bool IsLifetimeExtended, LValue &LV); 592 593 void describe(llvm::raw_ostream &OS) override; 594 595 Frame *getCaller() const override { return Caller; } 596 SourceLocation getCallLocation() const override { return CallLoc; } 597 const FunctionDecl *getCallee() const override { return Callee; } 598 599 bool isStdFunction() const { 600 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 601 if (DC->isStdNamespace()) 602 return true; 603 return false; 604 } 605 }; 606 607 /// Temporarily override 'this'. 608 class ThisOverrideRAII { 609 public: 610 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 611 : Frame(Frame), OldThis(Frame.This) { 612 if (Enable) 613 Frame.This = NewThis; 614 } 615 ~ThisOverrideRAII() { 616 Frame.This = OldThis; 617 } 618 private: 619 CallStackFrame &Frame; 620 const LValue *OldThis; 621 }; 622 } 623 624 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 625 const LValue &This, QualType ThisType); 626 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 627 APValue::LValueBase LVBase, APValue &Value, 628 QualType T); 629 630 namespace { 631 /// A cleanup, and a flag indicating whether it is lifetime-extended. 632 class Cleanup { 633 llvm::PointerIntPair<APValue*, 1, bool> Value; 634 APValue::LValueBase Base; 635 QualType T; 636 637 public: 638 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 639 bool IsLifetimeExtended) 640 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} 641 642 bool isLifetimeExtended() const { return Value.getInt(); } 643 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 644 if (RunDestructors) { 645 SourceLocation Loc; 646 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 647 Loc = VD->getLocation(); 648 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 649 Loc = E->getExprLoc(); 650 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 651 } 652 *Value.getPointer() = APValue(); 653 return true; 654 } 655 656 bool hasSideEffect() { 657 return T.isDestructedType(); 658 } 659 }; 660 661 /// A reference to an object whose construction we are currently evaluating. 662 struct ObjectUnderConstruction { 663 APValue::LValueBase Base; 664 ArrayRef<APValue::LValuePathEntry> Path; 665 friend bool operator==(const ObjectUnderConstruction &LHS, 666 const ObjectUnderConstruction &RHS) { 667 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 668 } 669 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 670 return llvm::hash_combine(Obj.Base, Obj.Path); 671 } 672 }; 673 enum class ConstructionPhase { 674 None, 675 Bases, 676 AfterBases, 677 Destroying, 678 DestroyingBases 679 }; 680 } 681 682 namespace llvm { 683 template<> struct DenseMapInfo<ObjectUnderConstruction> { 684 using Base = DenseMapInfo<APValue::LValueBase>; 685 static ObjectUnderConstruction getEmptyKey() { 686 return {Base::getEmptyKey(), {}}; } 687 static ObjectUnderConstruction getTombstoneKey() { 688 return {Base::getTombstoneKey(), {}}; 689 } 690 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 691 return hash_value(Object); 692 } 693 static bool isEqual(const ObjectUnderConstruction &LHS, 694 const ObjectUnderConstruction &RHS) { 695 return LHS == RHS; 696 } 697 }; 698 } 699 700 namespace { 701 /// A dynamically-allocated heap object. 702 struct DynAlloc { 703 /// The value of this heap-allocated object. 704 APValue Value; 705 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 706 /// or a CallExpr (the latter is for direct calls to operator new inside 707 /// std::allocator<T>::allocate). 708 const Expr *AllocExpr = nullptr; 709 710 enum Kind { 711 New, 712 ArrayNew, 713 StdAllocator 714 }; 715 716 /// Get the kind of the allocation. This must match between allocation 717 /// and deallocation. 718 Kind getKind() const { 719 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 720 return NE->isArray() ? ArrayNew : New; 721 assert(isa<CallExpr>(AllocExpr)); 722 return StdAllocator; 723 } 724 }; 725 726 struct DynAllocOrder { 727 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 728 return L.getIndex() < R.getIndex(); 729 } 730 }; 731 732 /// EvalInfo - This is a private struct used by the evaluator to capture 733 /// information about a subexpression as it is folded. It retains information 734 /// about the AST context, but also maintains information about the folded 735 /// expression. 736 /// 737 /// If an expression could be evaluated, it is still possible it is not a C 738 /// "integer constant expression" or constant expression. If not, this struct 739 /// captures information about how and why not. 740 /// 741 /// One bit of information passed *into* the request for constant folding 742 /// indicates whether the subexpression is "evaluated" or not according to C 743 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 744 /// evaluate the expression regardless of what the RHS is, but C only allows 745 /// certain things in certain situations. 746 class EvalInfo : public interp::State { 747 public: 748 ASTContext &Ctx; 749 750 /// EvalStatus - Contains information about the evaluation. 751 Expr::EvalStatus &EvalStatus; 752 753 /// CurrentCall - The top of the constexpr call stack. 754 CallStackFrame *CurrentCall; 755 756 /// CallStackDepth - The number of calls in the call stack right now. 757 unsigned CallStackDepth; 758 759 /// NextCallIndex - The next call index to assign. 760 unsigned NextCallIndex; 761 762 /// StepsLeft - The remaining number of evaluation steps we're permitted 763 /// to perform. This is essentially a limit for the number of statements 764 /// we will evaluate. 765 unsigned StepsLeft; 766 767 /// Enable the experimental new constant interpreter. If an expression is 768 /// not supported by the interpreter, an error is triggered. 769 bool EnableNewConstInterp; 770 771 /// BottomFrame - The frame in which evaluation started. This must be 772 /// initialized after CurrentCall and CallStackDepth. 773 CallStackFrame BottomFrame; 774 775 /// A stack of values whose lifetimes end at the end of some surrounding 776 /// evaluation frame. 777 llvm::SmallVector<Cleanup, 16> CleanupStack; 778 779 /// EvaluatingDecl - This is the declaration whose initializer is being 780 /// evaluated, if any. 781 APValue::LValueBase EvaluatingDecl; 782 783 enum class EvaluatingDeclKind { 784 None, 785 /// We're evaluating the construction of EvaluatingDecl. 786 Ctor, 787 /// We're evaluating the destruction of EvaluatingDecl. 788 Dtor, 789 }; 790 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 791 792 /// EvaluatingDeclValue - This is the value being constructed for the 793 /// declaration whose initializer is being evaluated, if any. 794 APValue *EvaluatingDeclValue; 795 796 /// Set of objects that are currently being constructed. 797 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 798 ObjectsUnderConstruction; 799 800 /// Current heap allocations, along with the location where each was 801 /// allocated. We use std::map here because we need stable addresses 802 /// for the stored APValues. 803 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 804 805 /// The number of heap allocations performed so far in this evaluation. 806 unsigned NumHeapAllocs = 0; 807 808 struct EvaluatingConstructorRAII { 809 EvalInfo &EI; 810 ObjectUnderConstruction Object; 811 bool DidInsert; 812 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 813 bool HasBases) 814 : EI(EI), Object(Object) { 815 DidInsert = 816 EI.ObjectsUnderConstruction 817 .insert({Object, HasBases ? ConstructionPhase::Bases 818 : ConstructionPhase::AfterBases}) 819 .second; 820 } 821 void finishedConstructingBases() { 822 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 823 } 824 ~EvaluatingConstructorRAII() { 825 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 826 } 827 }; 828 829 struct EvaluatingDestructorRAII { 830 EvalInfo &EI; 831 ObjectUnderConstruction Object; 832 bool DidInsert; 833 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 834 : EI(EI), Object(Object) { 835 DidInsert = EI.ObjectsUnderConstruction 836 .insert({Object, ConstructionPhase::Destroying}) 837 .second; 838 } 839 void startedDestroyingBases() { 840 EI.ObjectsUnderConstruction[Object] = 841 ConstructionPhase::DestroyingBases; 842 } 843 ~EvaluatingDestructorRAII() { 844 if (DidInsert) 845 EI.ObjectsUnderConstruction.erase(Object); 846 } 847 }; 848 849 ConstructionPhase 850 isEvaluatingCtorDtor(APValue::LValueBase Base, 851 ArrayRef<APValue::LValuePathEntry> Path) { 852 return ObjectsUnderConstruction.lookup({Base, Path}); 853 } 854 855 /// If we're currently speculatively evaluating, the outermost call stack 856 /// depth at which we can mutate state, otherwise 0. 857 unsigned SpeculativeEvaluationDepth = 0; 858 859 /// The current array initialization index, if we're performing array 860 /// initialization. 861 uint64_t ArrayInitIndex = -1; 862 863 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 864 /// notes attached to it will also be stored, otherwise they will not be. 865 bool HasActiveDiagnostic; 866 867 /// Have we emitted a diagnostic explaining why we couldn't constant 868 /// fold (not just why it's not strictly a constant expression)? 869 bool HasFoldFailureDiagnostic; 870 871 /// Whether or not we're in a context where the front end requires a 872 /// constant value. 873 bool InConstantContext; 874 875 /// Whether we're checking that an expression is a potential constant 876 /// expression. If so, do not fail on constructs that could become constant 877 /// later on (such as a use of an undefined global). 878 bool CheckingPotentialConstantExpression = false; 879 880 /// Whether we're checking for an expression that has undefined behavior. 881 /// If so, we will produce warnings if we encounter an operation that is 882 /// always undefined. 883 bool CheckingForUndefinedBehavior = false; 884 885 enum EvaluationMode { 886 /// Evaluate as a constant expression. Stop if we find that the expression 887 /// is not a constant expression. 888 EM_ConstantExpression, 889 890 /// Evaluate as a constant expression. Stop if we find that the expression 891 /// is not a constant expression. Some expressions can be retried in the 892 /// optimizer if we don't constant fold them here, but in an unevaluated 893 /// context we try to fold them immediately since the optimizer never 894 /// gets a chance to look at it. 895 EM_ConstantExpressionUnevaluated, 896 897 /// Fold the expression to a constant. Stop if we hit a side-effect that 898 /// we can't model. 899 EM_ConstantFold, 900 901 /// Evaluate in any way we know how. Don't worry about side-effects that 902 /// can't be modeled. 903 EM_IgnoreSideEffects, 904 } EvalMode; 905 906 /// Are we checking whether the expression is a potential constant 907 /// expression? 908 bool checkingPotentialConstantExpression() const override { 909 return CheckingPotentialConstantExpression; 910 } 911 912 /// Are we checking an expression for overflow? 913 // FIXME: We should check for any kind of undefined or suspicious behavior 914 // in such constructs, not just overflow. 915 bool checkingForUndefinedBehavior() const override { 916 return CheckingForUndefinedBehavior; 917 } 918 919 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 920 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 921 CallStackDepth(0), NextCallIndex(1), 922 StepsLeft(C.getLangOpts().ConstexprStepLimit), 923 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 924 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 925 EvaluatingDecl((const ValueDecl *)nullptr), 926 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 927 HasFoldFailureDiagnostic(false), InConstantContext(false), 928 EvalMode(Mode) {} 929 930 ~EvalInfo() { 931 discardCleanups(); 932 } 933 934 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 935 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 936 EvaluatingDecl = Base; 937 IsEvaluatingDecl = EDK; 938 EvaluatingDeclValue = &Value; 939 } 940 941 bool CheckCallLimit(SourceLocation Loc) { 942 // Don't perform any constexpr calls (other than the call we're checking) 943 // when checking a potential constant expression. 944 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 945 return false; 946 if (NextCallIndex == 0) { 947 // NextCallIndex has wrapped around. 948 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 949 return false; 950 } 951 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 952 return true; 953 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 954 << getLangOpts().ConstexprCallDepth; 955 return false; 956 } 957 958 std::pair<CallStackFrame *, unsigned> 959 getCallFrameAndDepth(unsigned CallIndex) { 960 assert(CallIndex && "no call index in getCallFrameAndDepth"); 961 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 962 // be null in this loop. 963 unsigned Depth = CallStackDepth; 964 CallStackFrame *Frame = CurrentCall; 965 while (Frame->Index > CallIndex) { 966 Frame = Frame->Caller; 967 --Depth; 968 } 969 if (Frame->Index == CallIndex) 970 return {Frame, Depth}; 971 return {nullptr, 0}; 972 } 973 974 bool nextStep(const Stmt *S) { 975 if (!StepsLeft) { 976 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 977 return false; 978 } 979 --StepsLeft; 980 return true; 981 } 982 983 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 984 985 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 986 Optional<DynAlloc*> Result; 987 auto It = HeapAllocs.find(DA); 988 if (It != HeapAllocs.end()) 989 Result = &It->second; 990 return Result; 991 } 992 993 /// Information about a stack frame for std::allocator<T>::[de]allocate. 994 struct StdAllocatorCaller { 995 unsigned FrameIndex; 996 QualType ElemType; 997 explicit operator bool() const { return FrameIndex != 0; }; 998 }; 999 1000 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1001 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1002 Call = Call->Caller) { 1003 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1004 if (!MD) 1005 continue; 1006 const IdentifierInfo *FnII = MD->getIdentifier(); 1007 if (!FnII || !FnII->isStr(FnName)) 1008 continue; 1009 1010 const auto *CTSD = 1011 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1012 if (!CTSD) 1013 continue; 1014 1015 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1016 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1017 if (CTSD->isInStdNamespace() && ClassII && 1018 ClassII->isStr("allocator") && TAL.size() >= 1 && 1019 TAL[0].getKind() == TemplateArgument::Type) 1020 return {Call->Index, TAL[0].getAsType()}; 1021 } 1022 1023 return {}; 1024 } 1025 1026 void performLifetimeExtension() { 1027 // Disable the cleanups for lifetime-extended temporaries. 1028 CleanupStack.erase( 1029 std::remove_if(CleanupStack.begin(), CleanupStack.end(), 1030 [](Cleanup &C) { return C.isLifetimeExtended(); }), 1031 CleanupStack.end()); 1032 } 1033 1034 /// Throw away any remaining cleanups at the end of evaluation. If any 1035 /// cleanups would have had a side-effect, note that as an unmodeled 1036 /// side-effect and return false. Otherwise, return true. 1037 bool discardCleanups() { 1038 for (Cleanup &C : CleanupStack) { 1039 if (C.hasSideEffect() && !noteSideEffect()) { 1040 CleanupStack.clear(); 1041 return false; 1042 } 1043 } 1044 CleanupStack.clear(); 1045 return true; 1046 } 1047 1048 private: 1049 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1050 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1051 1052 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1053 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1054 1055 void setFoldFailureDiagnostic(bool Flag) override { 1056 HasFoldFailureDiagnostic = Flag; 1057 } 1058 1059 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1060 1061 ASTContext &getCtx() const override { return Ctx; } 1062 1063 // If we have a prior diagnostic, it will be noting that the expression 1064 // isn't a constant expression. This diagnostic is more important, 1065 // unless we require this evaluation to produce a constant expression. 1066 // 1067 // FIXME: We might want to show both diagnostics to the user in 1068 // EM_ConstantFold mode. 1069 bool hasPriorDiagnostic() override { 1070 if (!EvalStatus.Diag->empty()) { 1071 switch (EvalMode) { 1072 case EM_ConstantFold: 1073 case EM_IgnoreSideEffects: 1074 if (!HasFoldFailureDiagnostic) 1075 break; 1076 // We've already failed to fold something. Keep that diagnostic. 1077 LLVM_FALLTHROUGH; 1078 case EM_ConstantExpression: 1079 case EM_ConstantExpressionUnevaluated: 1080 setActiveDiagnostic(false); 1081 return true; 1082 } 1083 } 1084 return false; 1085 } 1086 1087 unsigned getCallStackDepth() override { return CallStackDepth; } 1088 1089 public: 1090 /// Should we continue evaluation after encountering a side-effect that we 1091 /// couldn't model? 1092 bool keepEvaluatingAfterSideEffect() { 1093 switch (EvalMode) { 1094 case EM_IgnoreSideEffects: 1095 return true; 1096 1097 case EM_ConstantExpression: 1098 case EM_ConstantExpressionUnevaluated: 1099 case EM_ConstantFold: 1100 // By default, assume any side effect might be valid in some other 1101 // evaluation of this expression from a different context. 1102 return checkingPotentialConstantExpression() || 1103 checkingForUndefinedBehavior(); 1104 } 1105 llvm_unreachable("Missed EvalMode case"); 1106 } 1107 1108 /// Note that we have had a side-effect, and determine whether we should 1109 /// keep evaluating. 1110 bool noteSideEffect() { 1111 EvalStatus.HasSideEffects = true; 1112 return keepEvaluatingAfterSideEffect(); 1113 } 1114 1115 /// Should we continue evaluation after encountering undefined behavior? 1116 bool keepEvaluatingAfterUndefinedBehavior() { 1117 switch (EvalMode) { 1118 case EM_IgnoreSideEffects: 1119 case EM_ConstantFold: 1120 return true; 1121 1122 case EM_ConstantExpression: 1123 case EM_ConstantExpressionUnevaluated: 1124 return checkingForUndefinedBehavior(); 1125 } 1126 llvm_unreachable("Missed EvalMode case"); 1127 } 1128 1129 /// Note that we hit something that was technically undefined behavior, but 1130 /// that we can evaluate past it (such as signed overflow or floating-point 1131 /// division by zero.) 1132 bool noteUndefinedBehavior() override { 1133 EvalStatus.HasUndefinedBehavior = true; 1134 return keepEvaluatingAfterUndefinedBehavior(); 1135 } 1136 1137 /// Should we continue evaluation as much as possible after encountering a 1138 /// construct which can't be reduced to a value? 1139 bool keepEvaluatingAfterFailure() const override { 1140 if (!StepsLeft) 1141 return false; 1142 1143 switch (EvalMode) { 1144 case EM_ConstantExpression: 1145 case EM_ConstantExpressionUnevaluated: 1146 case EM_ConstantFold: 1147 case EM_IgnoreSideEffects: 1148 return checkingPotentialConstantExpression() || 1149 checkingForUndefinedBehavior(); 1150 } 1151 llvm_unreachable("Missed EvalMode case"); 1152 } 1153 1154 /// Notes that we failed to evaluate an expression that other expressions 1155 /// directly depend on, and determine if we should keep evaluating. This 1156 /// should only be called if we actually intend to keep evaluating. 1157 /// 1158 /// Call noteSideEffect() instead if we may be able to ignore the value that 1159 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1160 /// 1161 /// (Foo(), 1) // use noteSideEffect 1162 /// (Foo() || true) // use noteSideEffect 1163 /// Foo() + 1 // use noteFailure 1164 LLVM_NODISCARD bool noteFailure() { 1165 // Failure when evaluating some expression often means there is some 1166 // subexpression whose evaluation was skipped. Therefore, (because we 1167 // don't track whether we skipped an expression when unwinding after an 1168 // evaluation failure) every evaluation failure that bubbles up from a 1169 // subexpression implies that a side-effect has potentially happened. We 1170 // skip setting the HasSideEffects flag to true until we decide to 1171 // continue evaluating after that point, which happens here. 1172 bool KeepGoing = keepEvaluatingAfterFailure(); 1173 EvalStatus.HasSideEffects |= KeepGoing; 1174 return KeepGoing; 1175 } 1176 1177 class ArrayInitLoopIndex { 1178 EvalInfo &Info; 1179 uint64_t OuterIndex; 1180 1181 public: 1182 ArrayInitLoopIndex(EvalInfo &Info) 1183 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1184 Info.ArrayInitIndex = 0; 1185 } 1186 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1187 1188 operator uint64_t&() { return Info.ArrayInitIndex; } 1189 }; 1190 }; 1191 1192 /// Object used to treat all foldable expressions as constant expressions. 1193 struct FoldConstant { 1194 EvalInfo &Info; 1195 bool Enabled; 1196 bool HadNoPriorDiags; 1197 EvalInfo::EvaluationMode OldMode; 1198 1199 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1200 : Info(Info), 1201 Enabled(Enabled), 1202 HadNoPriorDiags(Info.EvalStatus.Diag && 1203 Info.EvalStatus.Diag->empty() && 1204 !Info.EvalStatus.HasSideEffects), 1205 OldMode(Info.EvalMode) { 1206 if (Enabled) 1207 Info.EvalMode = EvalInfo::EM_ConstantFold; 1208 } 1209 void keepDiagnostics() { Enabled = false; } 1210 ~FoldConstant() { 1211 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1212 !Info.EvalStatus.HasSideEffects) 1213 Info.EvalStatus.Diag->clear(); 1214 Info.EvalMode = OldMode; 1215 } 1216 }; 1217 1218 /// RAII object used to set the current evaluation mode to ignore 1219 /// side-effects. 1220 struct IgnoreSideEffectsRAII { 1221 EvalInfo &Info; 1222 EvalInfo::EvaluationMode OldMode; 1223 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1224 : Info(Info), OldMode(Info.EvalMode) { 1225 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1226 } 1227 1228 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1229 }; 1230 1231 /// RAII object used to optionally suppress diagnostics and side-effects from 1232 /// a speculative evaluation. 1233 class SpeculativeEvaluationRAII { 1234 EvalInfo *Info = nullptr; 1235 Expr::EvalStatus OldStatus; 1236 unsigned OldSpeculativeEvaluationDepth; 1237 1238 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1239 Info = Other.Info; 1240 OldStatus = Other.OldStatus; 1241 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1242 Other.Info = nullptr; 1243 } 1244 1245 void maybeRestoreState() { 1246 if (!Info) 1247 return; 1248 1249 Info->EvalStatus = OldStatus; 1250 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1251 } 1252 1253 public: 1254 SpeculativeEvaluationRAII() = default; 1255 1256 SpeculativeEvaluationRAII( 1257 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1258 : Info(&Info), OldStatus(Info.EvalStatus), 1259 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1260 Info.EvalStatus.Diag = NewDiag; 1261 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1262 } 1263 1264 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1265 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1266 moveFromAndCancel(std::move(Other)); 1267 } 1268 1269 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1270 maybeRestoreState(); 1271 moveFromAndCancel(std::move(Other)); 1272 return *this; 1273 } 1274 1275 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1276 }; 1277 1278 /// RAII object wrapping a full-expression or block scope, and handling 1279 /// the ending of the lifetime of temporaries created within it. 1280 template<bool IsFullExpression> 1281 class ScopeRAII { 1282 EvalInfo &Info; 1283 unsigned OldStackSize; 1284 public: 1285 ScopeRAII(EvalInfo &Info) 1286 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1287 // Push a new temporary version. This is needed to distinguish between 1288 // temporaries created in different iterations of a loop. 1289 Info.CurrentCall->pushTempVersion(); 1290 } 1291 bool destroy(bool RunDestructors = true) { 1292 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1293 OldStackSize = -1U; 1294 return OK; 1295 } 1296 ~ScopeRAII() { 1297 if (OldStackSize != -1U) 1298 destroy(false); 1299 // Body moved to a static method to encourage the compiler to inline away 1300 // instances of this class. 1301 Info.CurrentCall->popTempVersion(); 1302 } 1303 private: 1304 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1305 unsigned OldStackSize) { 1306 assert(OldStackSize <= Info.CleanupStack.size() && 1307 "running cleanups out of order?"); 1308 1309 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1310 // for a full-expression scope. 1311 bool Success = true; 1312 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1313 if (!(IsFullExpression && 1314 Info.CleanupStack[I - 1].isLifetimeExtended())) { 1315 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1316 Success = false; 1317 break; 1318 } 1319 } 1320 } 1321 1322 // Compact lifetime-extended cleanups. 1323 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1324 if (IsFullExpression) 1325 NewEnd = 1326 std::remove_if(NewEnd, Info.CleanupStack.end(), 1327 [](Cleanup &C) { return !C.isLifetimeExtended(); }); 1328 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1329 return Success; 1330 } 1331 }; 1332 typedef ScopeRAII<false> BlockScopeRAII; 1333 typedef ScopeRAII<true> FullExpressionRAII; 1334 } 1335 1336 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1337 CheckSubobjectKind CSK) { 1338 if (Invalid) 1339 return false; 1340 if (isOnePastTheEnd()) { 1341 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1342 << CSK; 1343 setInvalid(); 1344 return false; 1345 } 1346 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1347 // must actually be at least one array element; even a VLA cannot have a 1348 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1349 return true; 1350 } 1351 1352 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1353 const Expr *E) { 1354 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1355 // Do not set the designator as invalid: we can represent this situation, 1356 // and correct handling of __builtin_object_size requires us to do so. 1357 } 1358 1359 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1360 const Expr *E, 1361 const APSInt &N) { 1362 // If we're complaining, we must be able to statically determine the size of 1363 // the most derived array. 1364 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1365 Info.CCEDiag(E, diag::note_constexpr_array_index) 1366 << N << /*array*/ 0 1367 << static_cast<unsigned>(getMostDerivedArraySize()); 1368 else 1369 Info.CCEDiag(E, diag::note_constexpr_array_index) 1370 << N << /*non-array*/ 1; 1371 setInvalid(); 1372 } 1373 1374 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1375 const FunctionDecl *Callee, const LValue *This, 1376 APValue *Arguments) 1377 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1378 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1379 Info.CurrentCall = this; 1380 ++Info.CallStackDepth; 1381 } 1382 1383 CallStackFrame::~CallStackFrame() { 1384 assert(Info.CurrentCall == this && "calls retired out of order"); 1385 --Info.CallStackDepth; 1386 Info.CurrentCall = Caller; 1387 } 1388 1389 static bool isRead(AccessKinds AK) { 1390 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1391 } 1392 1393 static bool isModification(AccessKinds AK) { 1394 switch (AK) { 1395 case AK_Read: 1396 case AK_ReadObjectRepresentation: 1397 case AK_MemberCall: 1398 case AK_DynamicCast: 1399 case AK_TypeId: 1400 return false; 1401 case AK_Assign: 1402 case AK_Increment: 1403 case AK_Decrement: 1404 case AK_Construct: 1405 case AK_Destroy: 1406 return true; 1407 } 1408 llvm_unreachable("unknown access kind"); 1409 } 1410 1411 static bool isAnyAccess(AccessKinds AK) { 1412 return isRead(AK) || isModification(AK); 1413 } 1414 1415 /// Is this an access per the C++ definition? 1416 static bool isFormalAccess(AccessKinds AK) { 1417 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1418 } 1419 1420 /// Is this kind of axcess valid on an indeterminate object value? 1421 static bool isValidIndeterminateAccess(AccessKinds AK) { 1422 switch (AK) { 1423 case AK_Read: 1424 case AK_Increment: 1425 case AK_Decrement: 1426 // These need the object's value. 1427 return false; 1428 1429 case AK_ReadObjectRepresentation: 1430 case AK_Assign: 1431 case AK_Construct: 1432 case AK_Destroy: 1433 // Construction and destruction don't need the value. 1434 return true; 1435 1436 case AK_MemberCall: 1437 case AK_DynamicCast: 1438 case AK_TypeId: 1439 // These aren't really meaningful on scalars. 1440 return true; 1441 } 1442 llvm_unreachable("unknown access kind"); 1443 } 1444 1445 namespace { 1446 struct ComplexValue { 1447 private: 1448 bool IsInt; 1449 1450 public: 1451 APSInt IntReal, IntImag; 1452 APFloat FloatReal, FloatImag; 1453 1454 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1455 1456 void makeComplexFloat() { IsInt = false; } 1457 bool isComplexFloat() const { return !IsInt; } 1458 APFloat &getComplexFloatReal() { return FloatReal; } 1459 APFloat &getComplexFloatImag() { return FloatImag; } 1460 1461 void makeComplexInt() { IsInt = true; } 1462 bool isComplexInt() const { return IsInt; } 1463 APSInt &getComplexIntReal() { return IntReal; } 1464 APSInt &getComplexIntImag() { return IntImag; } 1465 1466 void moveInto(APValue &v) const { 1467 if (isComplexFloat()) 1468 v = APValue(FloatReal, FloatImag); 1469 else 1470 v = APValue(IntReal, IntImag); 1471 } 1472 void setFrom(const APValue &v) { 1473 assert(v.isComplexFloat() || v.isComplexInt()); 1474 if (v.isComplexFloat()) { 1475 makeComplexFloat(); 1476 FloatReal = v.getComplexFloatReal(); 1477 FloatImag = v.getComplexFloatImag(); 1478 } else { 1479 makeComplexInt(); 1480 IntReal = v.getComplexIntReal(); 1481 IntImag = v.getComplexIntImag(); 1482 } 1483 } 1484 }; 1485 1486 struct LValue { 1487 APValue::LValueBase Base; 1488 CharUnits Offset; 1489 SubobjectDesignator Designator; 1490 bool IsNullPtr : 1; 1491 bool InvalidBase : 1; 1492 1493 const APValue::LValueBase getLValueBase() const { return Base; } 1494 CharUnits &getLValueOffset() { return Offset; } 1495 const CharUnits &getLValueOffset() const { return Offset; } 1496 SubobjectDesignator &getLValueDesignator() { return Designator; } 1497 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1498 bool isNullPointer() const { return IsNullPtr;} 1499 1500 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1501 unsigned getLValueVersion() const { return Base.getVersion(); } 1502 1503 void moveInto(APValue &V) const { 1504 if (Designator.Invalid) 1505 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1506 else { 1507 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1508 V = APValue(Base, Offset, Designator.Entries, 1509 Designator.IsOnePastTheEnd, IsNullPtr); 1510 } 1511 } 1512 void setFrom(ASTContext &Ctx, const APValue &V) { 1513 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1514 Base = V.getLValueBase(); 1515 Offset = V.getLValueOffset(); 1516 InvalidBase = false; 1517 Designator = SubobjectDesignator(Ctx, V); 1518 IsNullPtr = V.isNullPointer(); 1519 } 1520 1521 void set(APValue::LValueBase B, bool BInvalid = false) { 1522 #ifndef NDEBUG 1523 // We only allow a few types of invalid bases. Enforce that here. 1524 if (BInvalid) { 1525 const auto *E = B.get<const Expr *>(); 1526 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1527 "Unexpected type of invalid base"); 1528 } 1529 #endif 1530 1531 Base = B; 1532 Offset = CharUnits::fromQuantity(0); 1533 InvalidBase = BInvalid; 1534 Designator = SubobjectDesignator(getType(B)); 1535 IsNullPtr = false; 1536 } 1537 1538 void setNull(ASTContext &Ctx, QualType PointerTy) { 1539 Base = (Expr *)nullptr; 1540 Offset = 1541 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1542 InvalidBase = false; 1543 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1544 IsNullPtr = true; 1545 } 1546 1547 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1548 set(B, true); 1549 } 1550 1551 std::string toString(ASTContext &Ctx, QualType T) const { 1552 APValue Printable; 1553 moveInto(Printable); 1554 return Printable.getAsString(Ctx, T); 1555 } 1556 1557 private: 1558 // Check that this LValue is not based on a null pointer. If it is, produce 1559 // a diagnostic and mark the designator as invalid. 1560 template <typename GenDiagType> 1561 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1562 if (Designator.Invalid) 1563 return false; 1564 if (IsNullPtr) { 1565 GenDiag(); 1566 Designator.setInvalid(); 1567 return false; 1568 } 1569 return true; 1570 } 1571 1572 public: 1573 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1574 CheckSubobjectKind CSK) { 1575 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1576 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1577 }); 1578 } 1579 1580 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1581 AccessKinds AK) { 1582 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1583 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1584 }); 1585 } 1586 1587 // Check this LValue refers to an object. If not, set the designator to be 1588 // invalid and emit a diagnostic. 1589 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1590 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1591 Designator.checkSubobject(Info, E, CSK); 1592 } 1593 1594 void addDecl(EvalInfo &Info, const Expr *E, 1595 const Decl *D, bool Virtual = false) { 1596 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1597 Designator.addDeclUnchecked(D, Virtual); 1598 } 1599 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1600 if (!Designator.Entries.empty()) { 1601 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1602 Designator.setInvalid(); 1603 return; 1604 } 1605 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1606 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1607 Designator.FirstEntryIsAnUnsizedArray = true; 1608 Designator.addUnsizedArrayUnchecked(ElemTy); 1609 } 1610 } 1611 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1612 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1613 Designator.addArrayUnchecked(CAT); 1614 } 1615 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1616 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1617 Designator.addComplexUnchecked(EltTy, Imag); 1618 } 1619 void clearIsNullPointer() { 1620 IsNullPtr = false; 1621 } 1622 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1623 const APSInt &Index, CharUnits ElementSize) { 1624 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1625 // but we're not required to diagnose it and it's valid in C++.) 1626 if (!Index) 1627 return; 1628 1629 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1630 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1631 // offsets. 1632 uint64_t Offset64 = Offset.getQuantity(); 1633 uint64_t ElemSize64 = ElementSize.getQuantity(); 1634 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1635 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1636 1637 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1638 Designator.adjustIndex(Info, E, Index); 1639 clearIsNullPointer(); 1640 } 1641 void adjustOffset(CharUnits N) { 1642 Offset += N; 1643 if (N.getQuantity()) 1644 clearIsNullPointer(); 1645 } 1646 }; 1647 1648 struct MemberPtr { 1649 MemberPtr() {} 1650 explicit MemberPtr(const ValueDecl *Decl) : 1651 DeclAndIsDerivedMember(Decl, false), Path() {} 1652 1653 /// The member or (direct or indirect) field referred to by this member 1654 /// pointer, or 0 if this is a null member pointer. 1655 const ValueDecl *getDecl() const { 1656 return DeclAndIsDerivedMember.getPointer(); 1657 } 1658 /// Is this actually a member of some type derived from the relevant class? 1659 bool isDerivedMember() const { 1660 return DeclAndIsDerivedMember.getInt(); 1661 } 1662 /// Get the class which the declaration actually lives in. 1663 const CXXRecordDecl *getContainingRecord() const { 1664 return cast<CXXRecordDecl>( 1665 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1666 } 1667 1668 void moveInto(APValue &V) const { 1669 V = APValue(getDecl(), isDerivedMember(), Path); 1670 } 1671 void setFrom(const APValue &V) { 1672 assert(V.isMemberPointer()); 1673 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1674 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1675 Path.clear(); 1676 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1677 Path.insert(Path.end(), P.begin(), P.end()); 1678 } 1679 1680 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1681 /// whether the member is a member of some class derived from the class type 1682 /// of the member pointer. 1683 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1684 /// Path - The path of base/derived classes from the member declaration's 1685 /// class (exclusive) to the class type of the member pointer (inclusive). 1686 SmallVector<const CXXRecordDecl*, 4> Path; 1687 1688 /// Perform a cast towards the class of the Decl (either up or down the 1689 /// hierarchy). 1690 bool castBack(const CXXRecordDecl *Class) { 1691 assert(!Path.empty()); 1692 const CXXRecordDecl *Expected; 1693 if (Path.size() >= 2) 1694 Expected = Path[Path.size() - 2]; 1695 else 1696 Expected = getContainingRecord(); 1697 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1698 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1699 // if B does not contain the original member and is not a base or 1700 // derived class of the class containing the original member, the result 1701 // of the cast is undefined. 1702 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1703 // (D::*). We consider that to be a language defect. 1704 return false; 1705 } 1706 Path.pop_back(); 1707 return true; 1708 } 1709 /// Perform a base-to-derived member pointer cast. 1710 bool castToDerived(const CXXRecordDecl *Derived) { 1711 if (!getDecl()) 1712 return true; 1713 if (!isDerivedMember()) { 1714 Path.push_back(Derived); 1715 return true; 1716 } 1717 if (!castBack(Derived)) 1718 return false; 1719 if (Path.empty()) 1720 DeclAndIsDerivedMember.setInt(false); 1721 return true; 1722 } 1723 /// Perform a derived-to-base member pointer cast. 1724 bool castToBase(const CXXRecordDecl *Base) { 1725 if (!getDecl()) 1726 return true; 1727 if (Path.empty()) 1728 DeclAndIsDerivedMember.setInt(true); 1729 if (isDerivedMember()) { 1730 Path.push_back(Base); 1731 return true; 1732 } 1733 return castBack(Base); 1734 } 1735 }; 1736 1737 /// Compare two member pointers, which are assumed to be of the same type. 1738 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1739 if (!LHS.getDecl() || !RHS.getDecl()) 1740 return !LHS.getDecl() && !RHS.getDecl(); 1741 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1742 return false; 1743 return LHS.Path == RHS.Path; 1744 } 1745 } 1746 1747 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1748 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1749 const LValue &This, const Expr *E, 1750 bool AllowNonLiteralTypes = false); 1751 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1752 bool InvalidBaseOK = false); 1753 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1754 bool InvalidBaseOK = false); 1755 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1756 EvalInfo &Info); 1757 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1758 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1759 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1760 EvalInfo &Info); 1761 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1762 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1763 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1764 EvalInfo &Info); 1765 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1766 1767 /// Evaluate an integer or fixed point expression into an APResult. 1768 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1769 EvalInfo &Info); 1770 1771 /// Evaluate only a fixed point expression into an APResult. 1772 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1773 EvalInfo &Info); 1774 1775 //===----------------------------------------------------------------------===// 1776 // Misc utilities 1777 //===----------------------------------------------------------------------===// 1778 1779 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1780 /// preserving its value (by extending by up to one bit as needed). 1781 static void negateAsSigned(APSInt &Int) { 1782 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1783 Int = Int.extend(Int.getBitWidth() + 1); 1784 Int.setIsSigned(true); 1785 } 1786 Int = -Int; 1787 } 1788 1789 template<typename KeyT> 1790 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1791 bool IsLifetimeExtended, LValue &LV) { 1792 unsigned Version = getTempVersion(); 1793 APValue::LValueBase Base(Key, Index, Version); 1794 LV.set(Base); 1795 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1796 assert(Result.isAbsent() && "temporary created multiple times"); 1797 1798 // If we're creating a temporary immediately in the operand of a speculative 1799 // evaluation, don't register a cleanup to be run outside the speculative 1800 // evaluation context, since we won't actually be able to initialize this 1801 // object. 1802 if (Index <= Info.SpeculativeEvaluationDepth) { 1803 if (T.isDestructedType()) 1804 Info.noteSideEffect(); 1805 } else { 1806 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); 1807 } 1808 return Result; 1809 } 1810 1811 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1812 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1813 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1814 return nullptr; 1815 } 1816 1817 DynamicAllocLValue DA(NumHeapAllocs++); 1818 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1819 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1820 std::forward_as_tuple(DA), std::tuple<>()); 1821 assert(Result.second && "reused a heap alloc index?"); 1822 Result.first->second.AllocExpr = E; 1823 return &Result.first->second.Value; 1824 } 1825 1826 /// Produce a string describing the given constexpr call. 1827 void CallStackFrame::describe(raw_ostream &Out) { 1828 unsigned ArgIndex = 0; 1829 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1830 !isa<CXXConstructorDecl>(Callee) && 1831 cast<CXXMethodDecl>(Callee)->isInstance(); 1832 1833 if (!IsMemberCall) 1834 Out << *Callee << '('; 1835 1836 if (This && IsMemberCall) { 1837 APValue Val; 1838 This->moveInto(Val); 1839 Val.printPretty(Out, Info.Ctx, 1840 This->Designator.MostDerivedType); 1841 // FIXME: Add parens around Val if needed. 1842 Out << "->" << *Callee << '('; 1843 IsMemberCall = false; 1844 } 1845 1846 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1847 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1848 if (ArgIndex > (unsigned)IsMemberCall) 1849 Out << ", "; 1850 1851 const ParmVarDecl *Param = *I; 1852 const APValue &Arg = Arguments[ArgIndex]; 1853 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1854 1855 if (ArgIndex == 0 && IsMemberCall) 1856 Out << "->" << *Callee << '('; 1857 } 1858 1859 Out << ')'; 1860 } 1861 1862 /// Evaluate an expression to see if it had side-effects, and discard its 1863 /// result. 1864 /// \return \c true if the caller should keep evaluating. 1865 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1866 APValue Scratch; 1867 if (!Evaluate(Scratch, Info, E)) 1868 // We don't need the value, but we might have skipped a side effect here. 1869 return Info.noteSideEffect(); 1870 return true; 1871 } 1872 1873 /// Should this call expression be treated as a string literal? 1874 static bool IsStringLiteralCall(const CallExpr *E) { 1875 unsigned Builtin = E->getBuiltinCallee(); 1876 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1877 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1878 } 1879 1880 static bool IsGlobalLValue(APValue::LValueBase B) { 1881 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1882 // constant expression of pointer type that evaluates to... 1883 1884 // ... a null pointer value, or a prvalue core constant expression of type 1885 // std::nullptr_t. 1886 if (!B) return true; 1887 1888 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1889 // ... the address of an object with static storage duration, 1890 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1891 return VD->hasGlobalStorage(); 1892 // ... the address of a function, 1893 return isa<FunctionDecl>(D); 1894 } 1895 1896 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1897 return true; 1898 1899 const Expr *E = B.get<const Expr*>(); 1900 switch (E->getStmtClass()) { 1901 default: 1902 return false; 1903 case Expr::CompoundLiteralExprClass: { 1904 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1905 return CLE->isFileScope() && CLE->isLValue(); 1906 } 1907 case Expr::MaterializeTemporaryExprClass: 1908 // A materialized temporary might have been lifetime-extended to static 1909 // storage duration. 1910 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1911 // A string literal has static storage duration. 1912 case Expr::StringLiteralClass: 1913 case Expr::PredefinedExprClass: 1914 case Expr::ObjCStringLiteralClass: 1915 case Expr::ObjCEncodeExprClass: 1916 case Expr::CXXUuidofExprClass: 1917 return true; 1918 case Expr::ObjCBoxedExprClass: 1919 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1920 case Expr::CallExprClass: 1921 return IsStringLiteralCall(cast<CallExpr>(E)); 1922 // For GCC compatibility, &&label has static storage duration. 1923 case Expr::AddrLabelExprClass: 1924 return true; 1925 // A Block literal expression may be used as the initialization value for 1926 // Block variables at global or local static scope. 1927 case Expr::BlockExprClass: 1928 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1929 case Expr::ImplicitValueInitExprClass: 1930 // FIXME: 1931 // We can never form an lvalue with an implicit value initialization as its 1932 // base through expression evaluation, so these only appear in one case: the 1933 // implicit variable declaration we invent when checking whether a constexpr 1934 // constructor can produce a constant expression. We must assume that such 1935 // an expression might be a global lvalue. 1936 return true; 1937 } 1938 } 1939 1940 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1941 return LVal.Base.dyn_cast<const ValueDecl*>(); 1942 } 1943 1944 static bool IsLiteralLValue(const LValue &Value) { 1945 if (Value.getLValueCallIndex()) 1946 return false; 1947 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1948 return E && !isa<MaterializeTemporaryExpr>(E); 1949 } 1950 1951 static bool IsWeakLValue(const LValue &Value) { 1952 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1953 return Decl && Decl->isWeak(); 1954 } 1955 1956 static bool isZeroSized(const LValue &Value) { 1957 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1958 if (Decl && isa<VarDecl>(Decl)) { 1959 QualType Ty = Decl->getType(); 1960 if (Ty->isArrayType()) 1961 return Ty->isIncompleteType() || 1962 Decl->getASTContext().getTypeSize(Ty) == 0; 1963 } 1964 return false; 1965 } 1966 1967 static bool HasSameBase(const LValue &A, const LValue &B) { 1968 if (!A.getLValueBase()) 1969 return !B.getLValueBase(); 1970 if (!B.getLValueBase()) 1971 return false; 1972 1973 if (A.getLValueBase().getOpaqueValue() != 1974 B.getLValueBase().getOpaqueValue()) { 1975 const Decl *ADecl = GetLValueBaseDecl(A); 1976 if (!ADecl) 1977 return false; 1978 const Decl *BDecl = GetLValueBaseDecl(B); 1979 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1980 return false; 1981 } 1982 1983 return IsGlobalLValue(A.getLValueBase()) || 1984 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1985 A.getLValueVersion() == B.getLValueVersion()); 1986 } 1987 1988 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1989 assert(Base && "no location for a null lvalue"); 1990 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1991 if (VD) 1992 Info.Note(VD->getLocation(), diag::note_declared_at); 1993 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1994 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1995 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 1996 // FIXME: Produce a note for dangling pointers too. 1997 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 1998 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 1999 diag::note_constexpr_dynamic_alloc_here); 2000 } 2001 // We have no information to show for a typeid(T) object. 2002 } 2003 2004 enum class CheckEvaluationResultKind { 2005 ConstantExpression, 2006 FullyInitialized, 2007 }; 2008 2009 /// Materialized temporaries that we've already checked to determine if they're 2010 /// initializsed by a constant expression. 2011 using CheckedTemporaries = 2012 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2013 2014 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2015 EvalInfo &Info, SourceLocation DiagLoc, 2016 QualType Type, const APValue &Value, 2017 Expr::ConstExprUsage Usage, 2018 SourceLocation SubobjectLoc, 2019 CheckedTemporaries &CheckedTemps); 2020 2021 /// Check that this reference or pointer core constant expression is a valid 2022 /// value for an address or reference constant expression. Return true if we 2023 /// can fold this expression, whether or not it's a constant expression. 2024 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2025 QualType Type, const LValue &LVal, 2026 Expr::ConstExprUsage Usage, 2027 CheckedTemporaries &CheckedTemps) { 2028 bool IsReferenceType = Type->isReferenceType(); 2029 2030 APValue::LValueBase Base = LVal.getLValueBase(); 2031 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2032 2033 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2034 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2035 if (FD->isConsteval()) { 2036 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2037 << !Type->isAnyPointerType(); 2038 Info.Note(FD->getLocation(), diag::note_declared_at); 2039 return false; 2040 } 2041 } 2042 } 2043 2044 // Check that the object is a global. Note that the fake 'this' object we 2045 // manufacture when checking potential constant expressions is conservatively 2046 // assumed to be global here. 2047 if (!IsGlobalLValue(Base)) { 2048 if (Info.getLangOpts().CPlusPlus11) { 2049 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2050 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2051 << IsReferenceType << !Designator.Entries.empty() 2052 << !!VD << VD; 2053 NoteLValueLocation(Info, Base); 2054 } else { 2055 Info.FFDiag(Loc); 2056 } 2057 // Don't allow references to temporaries to escape. 2058 return false; 2059 } 2060 assert((Info.checkingPotentialConstantExpression() || 2061 LVal.getLValueCallIndex() == 0) && 2062 "have call index for global lvalue"); 2063 2064 if (Base.is<DynamicAllocLValue>()) { 2065 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2066 << IsReferenceType << !Designator.Entries.empty(); 2067 NoteLValueLocation(Info, Base); 2068 return false; 2069 } 2070 2071 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2072 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2073 // Check if this is a thread-local variable. 2074 if (Var->getTLSKind()) 2075 // FIXME: Diagnostic! 2076 return false; 2077 2078 // A dllimport variable never acts like a constant. 2079 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2080 // FIXME: Diagnostic! 2081 return false; 2082 } 2083 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2084 // __declspec(dllimport) must be handled very carefully: 2085 // We must never initialize an expression with the thunk in C++. 2086 // Doing otherwise would allow the same id-expression to yield 2087 // different addresses for the same function in different translation 2088 // units. However, this means that we must dynamically initialize the 2089 // expression with the contents of the import address table at runtime. 2090 // 2091 // The C language has no notion of ODR; furthermore, it has no notion of 2092 // dynamic initialization. This means that we are permitted to 2093 // perform initialization with the address of the thunk. 2094 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2095 FD->hasAttr<DLLImportAttr>()) 2096 // FIXME: Diagnostic! 2097 return false; 2098 } 2099 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2100 Base.dyn_cast<const Expr *>())) { 2101 if (CheckedTemps.insert(MTE).second) { 2102 QualType TempType = getType(Base); 2103 if (TempType.isDestructedType()) { 2104 Info.FFDiag(MTE->getExprLoc(), 2105 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2106 << TempType; 2107 return false; 2108 } 2109 2110 APValue *V = MTE->getOrCreateValue(false); 2111 assert(V && "evasluation result refers to uninitialised temporary"); 2112 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2113 Info, MTE->getExprLoc(), TempType, *V, 2114 Usage, SourceLocation(), CheckedTemps)) 2115 return false; 2116 } 2117 } 2118 2119 // Allow address constant expressions to be past-the-end pointers. This is 2120 // an extension: the standard requires them to point to an object. 2121 if (!IsReferenceType) 2122 return true; 2123 2124 // A reference constant expression must refer to an object. 2125 if (!Base) { 2126 // FIXME: diagnostic 2127 Info.CCEDiag(Loc); 2128 return true; 2129 } 2130 2131 // Does this refer one past the end of some object? 2132 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2133 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2134 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2135 << !Designator.Entries.empty() << !!VD << VD; 2136 NoteLValueLocation(Info, Base); 2137 } 2138 2139 return true; 2140 } 2141 2142 /// Member pointers are constant expressions unless they point to a 2143 /// non-virtual dllimport member function. 2144 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2145 SourceLocation Loc, 2146 QualType Type, 2147 const APValue &Value, 2148 Expr::ConstExprUsage Usage) { 2149 const ValueDecl *Member = Value.getMemberPointerDecl(); 2150 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2151 if (!FD) 2152 return true; 2153 if (FD->isConsteval()) { 2154 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2155 Info.Note(FD->getLocation(), diag::note_declared_at); 2156 return false; 2157 } 2158 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2159 !FD->hasAttr<DLLImportAttr>(); 2160 } 2161 2162 /// Check that this core constant expression is of literal type, and if not, 2163 /// produce an appropriate diagnostic. 2164 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2165 const LValue *This = nullptr) { 2166 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2167 return true; 2168 2169 // C++1y: A constant initializer for an object o [...] may also invoke 2170 // constexpr constructors for o and its subobjects even if those objects 2171 // are of non-literal class types. 2172 // 2173 // C++11 missed this detail for aggregates, so classes like this: 2174 // struct foo_t { union { int i; volatile int j; } u; }; 2175 // are not (obviously) initializable like so: 2176 // __attribute__((__require_constant_initialization__)) 2177 // static const foo_t x = {{0}}; 2178 // because "i" is a subobject with non-literal initialization (due to the 2179 // volatile member of the union). See: 2180 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2181 // Therefore, we use the C++1y behavior. 2182 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2183 return true; 2184 2185 // Prvalue constant expressions must be of literal types. 2186 if (Info.getLangOpts().CPlusPlus11) 2187 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2188 << E->getType(); 2189 else 2190 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2191 return false; 2192 } 2193 2194 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2195 EvalInfo &Info, SourceLocation DiagLoc, 2196 QualType Type, const APValue &Value, 2197 Expr::ConstExprUsage Usage, 2198 SourceLocation SubobjectLoc, 2199 CheckedTemporaries &CheckedTemps) { 2200 if (!Value.hasValue()) { 2201 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2202 << true << Type; 2203 if (SubobjectLoc.isValid()) 2204 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2205 return false; 2206 } 2207 2208 // We allow _Atomic(T) to be initialized from anything that T can be 2209 // initialized from. 2210 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2211 Type = AT->getValueType(); 2212 2213 // Core issue 1454: For a literal constant expression of array or class type, 2214 // each subobject of its value shall have been initialized by a constant 2215 // expression. 2216 if (Value.isArray()) { 2217 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2218 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2219 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2220 Value.getArrayInitializedElt(I), Usage, 2221 SubobjectLoc, CheckedTemps)) 2222 return false; 2223 } 2224 if (!Value.hasArrayFiller()) 2225 return true; 2226 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2227 Value.getArrayFiller(), Usage, SubobjectLoc, 2228 CheckedTemps); 2229 } 2230 if (Value.isUnion() && Value.getUnionField()) { 2231 return CheckEvaluationResult( 2232 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2233 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2234 CheckedTemps); 2235 } 2236 if (Value.isStruct()) { 2237 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2238 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2239 unsigned BaseIndex = 0; 2240 for (const CXXBaseSpecifier &BS : CD->bases()) { 2241 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2242 Value.getStructBase(BaseIndex), Usage, 2243 BS.getBeginLoc(), CheckedTemps)) 2244 return false; 2245 ++BaseIndex; 2246 } 2247 } 2248 for (const auto *I : RD->fields()) { 2249 if (I->isUnnamedBitfield()) 2250 continue; 2251 2252 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2253 Value.getStructField(I->getFieldIndex()), 2254 Usage, I->getLocation(), CheckedTemps)) 2255 return false; 2256 } 2257 } 2258 2259 if (Value.isLValue() && 2260 CERK == CheckEvaluationResultKind::ConstantExpression) { 2261 LValue LVal; 2262 LVal.setFrom(Info.Ctx, Value); 2263 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2264 CheckedTemps); 2265 } 2266 2267 if (Value.isMemberPointer() && 2268 CERK == CheckEvaluationResultKind::ConstantExpression) 2269 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2270 2271 // Everything else is fine. 2272 return true; 2273 } 2274 2275 /// Check that this core constant expression value is a valid value for a 2276 /// constant expression. If not, report an appropriate diagnostic. Does not 2277 /// check that the expression is of literal type. 2278 static bool 2279 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2280 const APValue &Value, 2281 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2282 CheckedTemporaries CheckedTemps; 2283 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2284 Info, DiagLoc, Type, Value, Usage, 2285 SourceLocation(), CheckedTemps); 2286 } 2287 2288 /// Check that this evaluated value is fully-initialized and can be loaded by 2289 /// an lvalue-to-rvalue conversion. 2290 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2291 QualType Type, const APValue &Value) { 2292 CheckedTemporaries CheckedTemps; 2293 return CheckEvaluationResult( 2294 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2295 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2296 } 2297 2298 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2299 /// "the allocated storage is deallocated within the evaluation". 2300 static bool CheckMemoryLeaks(EvalInfo &Info) { 2301 if (!Info.HeapAllocs.empty()) { 2302 // We can still fold to a constant despite a compile-time memory leak, 2303 // so long as the heap allocation isn't referenced in the result (we check 2304 // that in CheckConstantExpression). 2305 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2306 diag::note_constexpr_memory_leak) 2307 << unsigned(Info.HeapAllocs.size() - 1); 2308 } 2309 return true; 2310 } 2311 2312 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2313 // A null base expression indicates a null pointer. These are always 2314 // evaluatable, and they are false unless the offset is zero. 2315 if (!Value.getLValueBase()) { 2316 Result = !Value.getLValueOffset().isZero(); 2317 return true; 2318 } 2319 2320 // We have a non-null base. These are generally known to be true, but if it's 2321 // a weak declaration it can be null at runtime. 2322 Result = true; 2323 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2324 return !Decl || !Decl->isWeak(); 2325 } 2326 2327 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2328 switch (Val.getKind()) { 2329 case APValue::None: 2330 case APValue::Indeterminate: 2331 return false; 2332 case APValue::Int: 2333 Result = Val.getInt().getBoolValue(); 2334 return true; 2335 case APValue::FixedPoint: 2336 Result = Val.getFixedPoint().getBoolValue(); 2337 return true; 2338 case APValue::Float: 2339 Result = !Val.getFloat().isZero(); 2340 return true; 2341 case APValue::ComplexInt: 2342 Result = Val.getComplexIntReal().getBoolValue() || 2343 Val.getComplexIntImag().getBoolValue(); 2344 return true; 2345 case APValue::ComplexFloat: 2346 Result = !Val.getComplexFloatReal().isZero() || 2347 !Val.getComplexFloatImag().isZero(); 2348 return true; 2349 case APValue::LValue: 2350 return EvalPointerValueAsBool(Val, Result); 2351 case APValue::MemberPointer: 2352 Result = Val.getMemberPointerDecl(); 2353 return true; 2354 case APValue::Vector: 2355 case APValue::Array: 2356 case APValue::Struct: 2357 case APValue::Union: 2358 case APValue::AddrLabelDiff: 2359 return false; 2360 } 2361 2362 llvm_unreachable("unknown APValue kind"); 2363 } 2364 2365 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2366 EvalInfo &Info) { 2367 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2368 APValue Val; 2369 if (!Evaluate(Val, Info, E)) 2370 return false; 2371 return HandleConversionToBool(Val, Result); 2372 } 2373 2374 template<typename T> 2375 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2376 const T &SrcValue, QualType DestType) { 2377 Info.CCEDiag(E, diag::note_constexpr_overflow) 2378 << SrcValue << DestType; 2379 return Info.noteUndefinedBehavior(); 2380 } 2381 2382 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2383 QualType SrcType, const APFloat &Value, 2384 QualType DestType, APSInt &Result) { 2385 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2386 // Determine whether we are converting to unsigned or signed. 2387 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2388 2389 Result = APSInt(DestWidth, !DestSigned); 2390 bool ignored; 2391 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2392 & APFloat::opInvalidOp) 2393 return HandleOverflow(Info, E, Value, DestType); 2394 return true; 2395 } 2396 2397 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2398 QualType SrcType, QualType DestType, 2399 APFloat &Result) { 2400 APFloat Value = Result; 2401 bool ignored; 2402 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2403 APFloat::rmNearestTiesToEven, &ignored); 2404 return true; 2405 } 2406 2407 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2408 QualType DestType, QualType SrcType, 2409 const APSInt &Value) { 2410 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2411 // Figure out if this is a truncate, extend or noop cast. 2412 // If the input is signed, do a sign extend, noop, or truncate. 2413 APSInt Result = Value.extOrTrunc(DestWidth); 2414 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2415 if (DestType->isBooleanType()) 2416 Result = Value.getBoolValue(); 2417 return Result; 2418 } 2419 2420 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2421 QualType SrcType, const APSInt &Value, 2422 QualType DestType, APFloat &Result) { 2423 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2424 Result.convertFromAPInt(Value, Value.isSigned(), 2425 APFloat::rmNearestTiesToEven); 2426 return true; 2427 } 2428 2429 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2430 APValue &Value, const FieldDecl *FD) { 2431 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2432 2433 if (!Value.isInt()) { 2434 // Trying to store a pointer-cast-to-integer into a bitfield. 2435 // FIXME: In this case, we should provide the diagnostic for casting 2436 // a pointer to an integer. 2437 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2438 Info.FFDiag(E); 2439 return false; 2440 } 2441 2442 APSInt &Int = Value.getInt(); 2443 unsigned OldBitWidth = Int.getBitWidth(); 2444 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2445 if (NewBitWidth < OldBitWidth) 2446 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2447 return true; 2448 } 2449 2450 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2451 llvm::APInt &Res) { 2452 APValue SVal; 2453 if (!Evaluate(SVal, Info, E)) 2454 return false; 2455 if (SVal.isInt()) { 2456 Res = SVal.getInt(); 2457 return true; 2458 } 2459 if (SVal.isFloat()) { 2460 Res = SVal.getFloat().bitcastToAPInt(); 2461 return true; 2462 } 2463 if (SVal.isVector()) { 2464 QualType VecTy = E->getType(); 2465 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2466 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2467 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2468 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2469 Res = llvm::APInt::getNullValue(VecSize); 2470 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2471 APValue &Elt = SVal.getVectorElt(i); 2472 llvm::APInt EltAsInt; 2473 if (Elt.isInt()) { 2474 EltAsInt = Elt.getInt(); 2475 } else if (Elt.isFloat()) { 2476 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2477 } else { 2478 // Don't try to handle vectors of anything other than int or float 2479 // (not sure if it's possible to hit this case). 2480 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2481 return false; 2482 } 2483 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2484 if (BigEndian) 2485 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2486 else 2487 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2488 } 2489 return true; 2490 } 2491 // Give up if the input isn't an int, float, or vector. For example, we 2492 // reject "(v4i16)(intptr_t)&a". 2493 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2494 return false; 2495 } 2496 2497 /// Perform the given integer operation, which is known to need at most BitWidth 2498 /// bits, and check for overflow in the original type (if that type was not an 2499 /// unsigned type). 2500 template<typename Operation> 2501 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2502 const APSInt &LHS, const APSInt &RHS, 2503 unsigned BitWidth, Operation Op, 2504 APSInt &Result) { 2505 if (LHS.isUnsigned()) { 2506 Result = Op(LHS, RHS); 2507 return true; 2508 } 2509 2510 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2511 Result = Value.trunc(LHS.getBitWidth()); 2512 if (Result.extend(BitWidth) != Value) { 2513 if (Info.checkingForUndefinedBehavior()) 2514 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2515 diag::warn_integer_constant_overflow) 2516 << Result.toString(10) << E->getType(); 2517 else 2518 return HandleOverflow(Info, E, Value, E->getType()); 2519 } 2520 return true; 2521 } 2522 2523 /// Perform the given binary integer operation. 2524 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2525 BinaryOperatorKind Opcode, APSInt RHS, 2526 APSInt &Result) { 2527 switch (Opcode) { 2528 default: 2529 Info.FFDiag(E); 2530 return false; 2531 case BO_Mul: 2532 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2533 std::multiplies<APSInt>(), Result); 2534 case BO_Add: 2535 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2536 std::plus<APSInt>(), Result); 2537 case BO_Sub: 2538 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2539 std::minus<APSInt>(), Result); 2540 case BO_And: Result = LHS & RHS; return true; 2541 case BO_Xor: Result = LHS ^ RHS; return true; 2542 case BO_Or: Result = LHS | RHS; return true; 2543 case BO_Div: 2544 case BO_Rem: 2545 if (RHS == 0) { 2546 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2547 return false; 2548 } 2549 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2550 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2551 // this operation and gives the two's complement result. 2552 if (RHS.isNegative() && RHS.isAllOnesValue() && 2553 LHS.isSigned() && LHS.isMinSignedValue()) 2554 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2555 E->getType()); 2556 return true; 2557 case BO_Shl: { 2558 if (Info.getLangOpts().OpenCL) 2559 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2560 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2561 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2562 RHS.isUnsigned()); 2563 else if (RHS.isSigned() && RHS.isNegative()) { 2564 // During constant-folding, a negative shift is an opposite shift. Such 2565 // a shift is not a constant expression. 2566 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2567 RHS = -RHS; 2568 goto shift_right; 2569 } 2570 shift_left: 2571 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2572 // the shifted type. 2573 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2574 if (SA != RHS) { 2575 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2576 << RHS << E->getType() << LHS.getBitWidth(); 2577 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) { 2578 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2579 // operand, and must not overflow the corresponding unsigned type. 2580 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2581 // E1 x 2^E2 module 2^N. 2582 if (LHS.isNegative()) 2583 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2584 else if (LHS.countLeadingZeros() < SA) 2585 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2586 } 2587 Result = LHS << SA; 2588 return true; 2589 } 2590 case BO_Shr: { 2591 if (Info.getLangOpts().OpenCL) 2592 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2593 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2594 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2595 RHS.isUnsigned()); 2596 else if (RHS.isSigned() && RHS.isNegative()) { 2597 // During constant-folding, a negative shift is an opposite shift. Such a 2598 // shift is not a constant expression. 2599 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2600 RHS = -RHS; 2601 goto shift_left; 2602 } 2603 shift_right: 2604 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2605 // shifted type. 2606 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2607 if (SA != RHS) 2608 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2609 << RHS << E->getType() << LHS.getBitWidth(); 2610 Result = LHS >> SA; 2611 return true; 2612 } 2613 2614 case BO_LT: Result = LHS < RHS; return true; 2615 case BO_GT: Result = LHS > RHS; return true; 2616 case BO_LE: Result = LHS <= RHS; return true; 2617 case BO_GE: Result = LHS >= RHS; return true; 2618 case BO_EQ: Result = LHS == RHS; return true; 2619 case BO_NE: Result = LHS != RHS; return true; 2620 case BO_Cmp: 2621 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2622 } 2623 } 2624 2625 /// Perform the given binary floating-point operation, in-place, on LHS. 2626 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2627 APFloat &LHS, BinaryOperatorKind Opcode, 2628 const APFloat &RHS) { 2629 switch (Opcode) { 2630 default: 2631 Info.FFDiag(E); 2632 return false; 2633 case BO_Mul: 2634 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2635 break; 2636 case BO_Add: 2637 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2638 break; 2639 case BO_Sub: 2640 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2641 break; 2642 case BO_Div: 2643 // [expr.mul]p4: 2644 // If the second operand of / or % is zero the behavior is undefined. 2645 if (RHS.isZero()) 2646 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2647 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2648 break; 2649 } 2650 2651 // [expr.pre]p4: 2652 // If during the evaluation of an expression, the result is not 2653 // mathematically defined [...], the behavior is undefined. 2654 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2655 if (LHS.isNaN()) { 2656 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2657 return Info.noteUndefinedBehavior(); 2658 } 2659 return true; 2660 } 2661 2662 /// Cast an lvalue referring to a base subobject to a derived class, by 2663 /// truncating the lvalue's path to the given length. 2664 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2665 const RecordDecl *TruncatedType, 2666 unsigned TruncatedElements) { 2667 SubobjectDesignator &D = Result.Designator; 2668 2669 // Check we actually point to a derived class object. 2670 if (TruncatedElements == D.Entries.size()) 2671 return true; 2672 assert(TruncatedElements >= D.MostDerivedPathLength && 2673 "not casting to a derived class"); 2674 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2675 return false; 2676 2677 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2678 const RecordDecl *RD = TruncatedType; 2679 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2680 if (RD->isInvalidDecl()) return false; 2681 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2682 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2683 if (isVirtualBaseClass(D.Entries[I])) 2684 Result.Offset -= Layout.getVBaseClassOffset(Base); 2685 else 2686 Result.Offset -= Layout.getBaseClassOffset(Base); 2687 RD = Base; 2688 } 2689 D.Entries.resize(TruncatedElements); 2690 return true; 2691 } 2692 2693 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2694 const CXXRecordDecl *Derived, 2695 const CXXRecordDecl *Base, 2696 const ASTRecordLayout *RL = nullptr) { 2697 if (!RL) { 2698 if (Derived->isInvalidDecl()) return false; 2699 RL = &Info.Ctx.getASTRecordLayout(Derived); 2700 } 2701 2702 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2703 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2704 return true; 2705 } 2706 2707 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2708 const CXXRecordDecl *DerivedDecl, 2709 const CXXBaseSpecifier *Base) { 2710 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2711 2712 if (!Base->isVirtual()) 2713 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2714 2715 SubobjectDesignator &D = Obj.Designator; 2716 if (D.Invalid) 2717 return false; 2718 2719 // Extract most-derived object and corresponding type. 2720 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2721 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2722 return false; 2723 2724 // Find the virtual base class. 2725 if (DerivedDecl->isInvalidDecl()) return false; 2726 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2727 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2728 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2729 return true; 2730 } 2731 2732 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2733 QualType Type, LValue &Result) { 2734 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2735 PathE = E->path_end(); 2736 PathI != PathE; ++PathI) { 2737 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2738 *PathI)) 2739 return false; 2740 Type = (*PathI)->getType(); 2741 } 2742 return true; 2743 } 2744 2745 /// Cast an lvalue referring to a derived class to a known base subobject. 2746 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2747 const CXXRecordDecl *DerivedRD, 2748 const CXXRecordDecl *BaseRD) { 2749 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2750 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2751 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2752 llvm_unreachable("Class must be derived from the passed in base class!"); 2753 2754 for (CXXBasePathElement &Elem : Paths.front()) 2755 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2756 return false; 2757 return true; 2758 } 2759 2760 /// Update LVal to refer to the given field, which must be a member of the type 2761 /// currently described by LVal. 2762 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2763 const FieldDecl *FD, 2764 const ASTRecordLayout *RL = nullptr) { 2765 if (!RL) { 2766 if (FD->getParent()->isInvalidDecl()) return false; 2767 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2768 } 2769 2770 unsigned I = FD->getFieldIndex(); 2771 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2772 LVal.addDecl(Info, E, FD); 2773 return true; 2774 } 2775 2776 /// Update LVal to refer to the given indirect field. 2777 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2778 LValue &LVal, 2779 const IndirectFieldDecl *IFD) { 2780 for (const auto *C : IFD->chain()) 2781 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2782 return false; 2783 return true; 2784 } 2785 2786 /// Get the size of the given type in char units. 2787 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2788 QualType Type, CharUnits &Size) { 2789 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2790 // extension. 2791 if (Type->isVoidType() || Type->isFunctionType()) { 2792 Size = CharUnits::One(); 2793 return true; 2794 } 2795 2796 if (Type->isDependentType()) { 2797 Info.FFDiag(Loc); 2798 return false; 2799 } 2800 2801 if (!Type->isConstantSizeType()) { 2802 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2803 // FIXME: Better diagnostic. 2804 Info.FFDiag(Loc); 2805 return false; 2806 } 2807 2808 Size = Info.Ctx.getTypeSizeInChars(Type); 2809 return true; 2810 } 2811 2812 /// Update a pointer value to model pointer arithmetic. 2813 /// \param Info - Information about the ongoing evaluation. 2814 /// \param E - The expression being evaluated, for diagnostic purposes. 2815 /// \param LVal - The pointer value to be updated. 2816 /// \param EltTy - The pointee type represented by LVal. 2817 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2818 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2819 LValue &LVal, QualType EltTy, 2820 APSInt Adjustment) { 2821 CharUnits SizeOfPointee; 2822 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2823 return false; 2824 2825 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2826 return true; 2827 } 2828 2829 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2830 LValue &LVal, QualType EltTy, 2831 int64_t Adjustment) { 2832 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2833 APSInt::get(Adjustment)); 2834 } 2835 2836 /// Update an lvalue to refer to a component of a complex number. 2837 /// \param Info - Information about the ongoing evaluation. 2838 /// \param LVal - The lvalue to be updated. 2839 /// \param EltTy - The complex number's component type. 2840 /// \param Imag - False for the real component, true for the imaginary. 2841 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2842 LValue &LVal, QualType EltTy, 2843 bool Imag) { 2844 if (Imag) { 2845 CharUnits SizeOfComponent; 2846 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2847 return false; 2848 LVal.Offset += SizeOfComponent; 2849 } 2850 LVal.addComplex(Info, E, EltTy, Imag); 2851 return true; 2852 } 2853 2854 /// Try to evaluate the initializer for a variable declaration. 2855 /// 2856 /// \param Info Information about the ongoing evaluation. 2857 /// \param E An expression to be used when printing diagnostics. 2858 /// \param VD The variable whose initializer should be obtained. 2859 /// \param Frame The frame in which the variable was created. Must be null 2860 /// if this variable is not local to the evaluation. 2861 /// \param Result Filled in with a pointer to the value of the variable. 2862 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2863 const VarDecl *VD, CallStackFrame *Frame, 2864 APValue *&Result, const LValue *LVal) { 2865 2866 // If this is a parameter to an active constexpr function call, perform 2867 // argument substitution. 2868 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2869 // Assume arguments of a potential constant expression are unknown 2870 // constant expressions. 2871 if (Info.checkingPotentialConstantExpression()) 2872 return false; 2873 if (!Frame || !Frame->Arguments) { 2874 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2875 return false; 2876 } 2877 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2878 return true; 2879 } 2880 2881 // If this is a local variable, dig out its value. 2882 if (Frame) { 2883 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2884 : Frame->getCurrentTemporary(VD); 2885 if (!Result) { 2886 // Assume variables referenced within a lambda's call operator that were 2887 // not declared within the call operator are captures and during checking 2888 // of a potential constant expression, assume they are unknown constant 2889 // expressions. 2890 assert(isLambdaCallOperator(Frame->Callee) && 2891 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2892 "missing value for local variable"); 2893 if (Info.checkingPotentialConstantExpression()) 2894 return false; 2895 // FIXME: implement capture evaluation during constant expr evaluation. 2896 Info.FFDiag(E->getBeginLoc(), 2897 diag::note_unimplemented_constexpr_lambda_feature_ast) 2898 << "captures not currently allowed"; 2899 return false; 2900 } 2901 return true; 2902 } 2903 2904 // Dig out the initializer, and use the declaration which it's attached to. 2905 const Expr *Init = VD->getAnyInitializer(VD); 2906 if (!Init || Init->isValueDependent()) { 2907 // If we're checking a potential constant expression, the variable could be 2908 // initialized later. 2909 if (!Info.checkingPotentialConstantExpression()) 2910 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2911 return false; 2912 } 2913 2914 // If we're currently evaluating the initializer of this declaration, use that 2915 // in-flight value. 2916 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2917 Result = Info.EvaluatingDeclValue; 2918 return true; 2919 } 2920 2921 // Never evaluate the initializer of a weak variable. We can't be sure that 2922 // this is the definition which will be used. 2923 if (VD->isWeak()) { 2924 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2925 return false; 2926 } 2927 2928 // Check that we can fold the initializer. In C++, we will have already done 2929 // this in the cases where it matters for conformance. 2930 SmallVector<PartialDiagnosticAt, 8> Notes; 2931 if (!VD->evaluateValue(Notes)) { 2932 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2933 Notes.size() + 1) << VD; 2934 Info.Note(VD->getLocation(), diag::note_declared_at); 2935 Info.addNotes(Notes); 2936 return false; 2937 } else if (!VD->checkInitIsICE()) { 2938 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2939 Notes.size() + 1) << VD; 2940 Info.Note(VD->getLocation(), diag::note_declared_at); 2941 Info.addNotes(Notes); 2942 } 2943 2944 Result = VD->getEvaluatedValue(); 2945 return true; 2946 } 2947 2948 static bool IsConstNonVolatile(QualType T) { 2949 Qualifiers Quals = T.getQualifiers(); 2950 return Quals.hasConst() && !Quals.hasVolatile(); 2951 } 2952 2953 /// Get the base index of the given base class within an APValue representing 2954 /// the given derived class. 2955 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2956 const CXXRecordDecl *Base) { 2957 Base = Base->getCanonicalDecl(); 2958 unsigned Index = 0; 2959 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2960 E = Derived->bases_end(); I != E; ++I, ++Index) { 2961 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2962 return Index; 2963 } 2964 2965 llvm_unreachable("base class missing from derived class's bases list"); 2966 } 2967 2968 /// Extract the value of a character from a string literal. 2969 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2970 uint64_t Index) { 2971 assert(!isa<SourceLocExpr>(Lit) && 2972 "SourceLocExpr should have already been converted to a StringLiteral"); 2973 2974 // FIXME: Support MakeStringConstant 2975 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2976 std::string Str; 2977 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2978 assert(Index <= Str.size() && "Index too large"); 2979 return APSInt::getUnsigned(Str.c_str()[Index]); 2980 } 2981 2982 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2983 Lit = PE->getFunctionName(); 2984 const StringLiteral *S = cast<StringLiteral>(Lit); 2985 const ConstantArrayType *CAT = 2986 Info.Ctx.getAsConstantArrayType(S->getType()); 2987 assert(CAT && "string literal isn't an array"); 2988 QualType CharType = CAT->getElementType(); 2989 assert(CharType->isIntegerType() && "unexpected character type"); 2990 2991 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2992 CharType->isUnsignedIntegerType()); 2993 if (Index < S->getLength()) 2994 Value = S->getCodeUnit(Index); 2995 return Value; 2996 } 2997 2998 // Expand a string literal into an array of characters. 2999 // 3000 // FIXME: This is inefficient; we should probably introduce something similar 3001 // to the LLVM ConstantDataArray to make this cheaper. 3002 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3003 APValue &Result, 3004 QualType AllocType = QualType()) { 3005 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3006 AllocType.isNull() ? S->getType() : AllocType); 3007 assert(CAT && "string literal isn't an array"); 3008 QualType CharType = CAT->getElementType(); 3009 assert(CharType->isIntegerType() && "unexpected character type"); 3010 3011 unsigned Elts = CAT->getSize().getZExtValue(); 3012 Result = APValue(APValue::UninitArray(), 3013 std::min(S->getLength(), Elts), Elts); 3014 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3015 CharType->isUnsignedIntegerType()); 3016 if (Result.hasArrayFiller()) 3017 Result.getArrayFiller() = APValue(Value); 3018 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3019 Value = S->getCodeUnit(I); 3020 Result.getArrayInitializedElt(I) = APValue(Value); 3021 } 3022 } 3023 3024 // Expand an array so that it has more than Index filled elements. 3025 static void expandArray(APValue &Array, unsigned Index) { 3026 unsigned Size = Array.getArraySize(); 3027 assert(Index < Size); 3028 3029 // Always at least double the number of elements for which we store a value. 3030 unsigned OldElts = Array.getArrayInitializedElts(); 3031 unsigned NewElts = std::max(Index+1, OldElts * 2); 3032 NewElts = std::min(Size, std::max(NewElts, 8u)); 3033 3034 // Copy the data across. 3035 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3036 for (unsigned I = 0; I != OldElts; ++I) 3037 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3038 for (unsigned I = OldElts; I != NewElts; ++I) 3039 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3040 if (NewValue.hasArrayFiller()) 3041 NewValue.getArrayFiller() = Array.getArrayFiller(); 3042 Array.swap(NewValue); 3043 } 3044 3045 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3046 /// conversion. If it's of class type, we may assume that the copy operation 3047 /// is trivial. Note that this is never true for a union type with fields 3048 /// (because the copy always "reads" the active member) and always true for 3049 /// a non-class type. 3050 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3051 static bool isReadByLvalueToRvalueConversion(QualType T) { 3052 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3053 return !RD || isReadByLvalueToRvalueConversion(RD); 3054 } 3055 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3056 // FIXME: A trivial copy of a union copies the object representation, even if 3057 // the union is empty. 3058 if (RD->isUnion()) 3059 return !RD->field_empty(); 3060 if (RD->isEmpty()) 3061 return false; 3062 3063 for (auto *Field : RD->fields()) 3064 if (!Field->isUnnamedBitfield() && 3065 isReadByLvalueToRvalueConversion(Field->getType())) 3066 return true; 3067 3068 for (auto &BaseSpec : RD->bases()) 3069 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3070 return true; 3071 3072 return false; 3073 } 3074 3075 /// Diagnose an attempt to read from any unreadable field within the specified 3076 /// type, which might be a class type. 3077 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3078 QualType T) { 3079 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3080 if (!RD) 3081 return false; 3082 3083 if (!RD->hasMutableFields()) 3084 return false; 3085 3086 for (auto *Field : RD->fields()) { 3087 // If we're actually going to read this field in some way, then it can't 3088 // be mutable. If we're in a union, then assigning to a mutable field 3089 // (even an empty one) can change the active member, so that's not OK. 3090 // FIXME: Add core issue number for the union case. 3091 if (Field->isMutable() && 3092 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3093 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3094 Info.Note(Field->getLocation(), diag::note_declared_at); 3095 return true; 3096 } 3097 3098 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3099 return true; 3100 } 3101 3102 for (auto &BaseSpec : RD->bases()) 3103 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3104 return true; 3105 3106 // All mutable fields were empty, and thus not actually read. 3107 return false; 3108 } 3109 3110 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3111 APValue::LValueBase Base, 3112 bool MutableSubobject = false) { 3113 // A temporary we created. 3114 if (Base.getCallIndex()) 3115 return true; 3116 3117 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3118 if (!Evaluating) 3119 return false; 3120 3121 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3122 3123 switch (Info.IsEvaluatingDecl) { 3124 case EvalInfo::EvaluatingDeclKind::None: 3125 return false; 3126 3127 case EvalInfo::EvaluatingDeclKind::Ctor: 3128 // The variable whose initializer we're evaluating. 3129 if (BaseD) 3130 return declaresSameEntity(Evaluating, BaseD); 3131 3132 // A temporary lifetime-extended by the variable whose initializer we're 3133 // evaluating. 3134 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3135 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3136 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3137 return false; 3138 3139 case EvalInfo::EvaluatingDeclKind::Dtor: 3140 // C++2a [expr.const]p6: 3141 // [during constant destruction] the lifetime of a and its non-mutable 3142 // subobjects (but not its mutable subobjects) [are] considered to start 3143 // within e. 3144 // 3145 // FIXME: We can meaningfully extend this to cover non-const objects, but 3146 // we will need special handling: we should be able to access only 3147 // subobjects of such objects that are themselves declared const. 3148 if (!BaseD || 3149 !(BaseD->getType().isConstQualified() || 3150 BaseD->getType()->isReferenceType()) || 3151 MutableSubobject) 3152 return false; 3153 return declaresSameEntity(Evaluating, BaseD); 3154 } 3155 3156 llvm_unreachable("unknown evaluating decl kind"); 3157 } 3158 3159 namespace { 3160 /// A handle to a complete object (an object that is not a subobject of 3161 /// another object). 3162 struct CompleteObject { 3163 /// The identity of the object. 3164 APValue::LValueBase Base; 3165 /// The value of the complete object. 3166 APValue *Value; 3167 /// The type of the complete object. 3168 QualType Type; 3169 3170 CompleteObject() : Value(nullptr) {} 3171 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3172 : Base(Base), Value(Value), Type(Type) {} 3173 3174 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3175 // If this isn't a "real" access (eg, if it's just accessing the type 3176 // info), allow it. We assume the type doesn't change dynamically for 3177 // subobjects of constexpr objects (even though we'd hit UB here if it 3178 // did). FIXME: Is this right? 3179 if (!isAnyAccess(AK)) 3180 return true; 3181 3182 // In C++14 onwards, it is permitted to read a mutable member whose 3183 // lifetime began within the evaluation. 3184 // FIXME: Should we also allow this in C++11? 3185 if (!Info.getLangOpts().CPlusPlus14) 3186 return false; 3187 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3188 } 3189 3190 explicit operator bool() const { return !Type.isNull(); } 3191 }; 3192 } // end anonymous namespace 3193 3194 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3195 bool IsMutable = false) { 3196 // C++ [basic.type.qualifier]p1: 3197 // - A const object is an object of type const T or a non-mutable subobject 3198 // of a const object. 3199 if (ObjType.isConstQualified() && !IsMutable) 3200 SubobjType.addConst(); 3201 // - A volatile object is an object of type const T or a subobject of a 3202 // volatile object. 3203 if (ObjType.isVolatileQualified()) 3204 SubobjType.addVolatile(); 3205 return SubobjType; 3206 } 3207 3208 /// Find the designated sub-object of an rvalue. 3209 template<typename SubobjectHandler> 3210 typename SubobjectHandler::result_type 3211 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3212 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3213 if (Sub.Invalid) 3214 // A diagnostic will have already been produced. 3215 return handler.failed(); 3216 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3217 if (Info.getLangOpts().CPlusPlus11) 3218 Info.FFDiag(E, Sub.isOnePastTheEnd() 3219 ? diag::note_constexpr_access_past_end 3220 : diag::note_constexpr_access_unsized_array) 3221 << handler.AccessKind; 3222 else 3223 Info.FFDiag(E); 3224 return handler.failed(); 3225 } 3226 3227 APValue *O = Obj.Value; 3228 QualType ObjType = Obj.Type; 3229 const FieldDecl *LastField = nullptr; 3230 const FieldDecl *VolatileField = nullptr; 3231 3232 // Walk the designator's path to find the subobject. 3233 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3234 // Reading an indeterminate value is undefined, but assigning over one is OK. 3235 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3236 (O->isIndeterminate() && 3237 !isValidIndeterminateAccess(handler.AccessKind))) { 3238 if (!Info.checkingPotentialConstantExpression()) 3239 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3240 << handler.AccessKind << O->isIndeterminate(); 3241 return handler.failed(); 3242 } 3243 3244 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3245 // const and volatile semantics are not applied on an object under 3246 // {con,de}struction. 3247 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3248 ObjType->isRecordType() && 3249 Info.isEvaluatingCtorDtor( 3250 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3251 Sub.Entries.begin() + I)) != 3252 ConstructionPhase::None) { 3253 ObjType = Info.Ctx.getCanonicalType(ObjType); 3254 ObjType.removeLocalConst(); 3255 ObjType.removeLocalVolatile(); 3256 } 3257 3258 // If this is our last pass, check that the final object type is OK. 3259 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3260 // Accesses to volatile objects are prohibited. 3261 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3262 if (Info.getLangOpts().CPlusPlus) { 3263 int DiagKind; 3264 SourceLocation Loc; 3265 const NamedDecl *Decl = nullptr; 3266 if (VolatileField) { 3267 DiagKind = 2; 3268 Loc = VolatileField->getLocation(); 3269 Decl = VolatileField; 3270 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3271 DiagKind = 1; 3272 Loc = VD->getLocation(); 3273 Decl = VD; 3274 } else { 3275 DiagKind = 0; 3276 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3277 Loc = E->getExprLoc(); 3278 } 3279 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3280 << handler.AccessKind << DiagKind << Decl; 3281 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3282 } else { 3283 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3284 } 3285 return handler.failed(); 3286 } 3287 3288 // If we are reading an object of class type, there may still be more 3289 // things we need to check: if there are any mutable subobjects, we 3290 // cannot perform this read. (This only happens when performing a trivial 3291 // copy or assignment.) 3292 if (ObjType->isRecordType() && 3293 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3294 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3295 return handler.failed(); 3296 } 3297 3298 if (I == N) { 3299 if (!handler.found(*O, ObjType)) 3300 return false; 3301 3302 // If we modified a bit-field, truncate it to the right width. 3303 if (isModification(handler.AccessKind) && 3304 LastField && LastField->isBitField() && 3305 !truncateBitfieldValue(Info, E, *O, LastField)) 3306 return false; 3307 3308 return true; 3309 } 3310 3311 LastField = nullptr; 3312 if (ObjType->isArrayType()) { 3313 // Next subobject is an array element. 3314 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3315 assert(CAT && "vla in literal type?"); 3316 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3317 if (CAT->getSize().ule(Index)) { 3318 // Note, it should not be possible to form a pointer with a valid 3319 // designator which points more than one past the end of the array. 3320 if (Info.getLangOpts().CPlusPlus11) 3321 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3322 << handler.AccessKind; 3323 else 3324 Info.FFDiag(E); 3325 return handler.failed(); 3326 } 3327 3328 ObjType = CAT->getElementType(); 3329 3330 if (O->getArrayInitializedElts() > Index) 3331 O = &O->getArrayInitializedElt(Index); 3332 else if (!isRead(handler.AccessKind)) { 3333 expandArray(*O, Index); 3334 O = &O->getArrayInitializedElt(Index); 3335 } else 3336 O = &O->getArrayFiller(); 3337 } else if (ObjType->isAnyComplexType()) { 3338 // Next subobject is a complex number. 3339 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3340 if (Index > 1) { 3341 if (Info.getLangOpts().CPlusPlus11) 3342 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3343 << handler.AccessKind; 3344 else 3345 Info.FFDiag(E); 3346 return handler.failed(); 3347 } 3348 3349 ObjType = getSubobjectType( 3350 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3351 3352 assert(I == N - 1 && "extracting subobject of scalar?"); 3353 if (O->isComplexInt()) { 3354 return handler.found(Index ? O->getComplexIntImag() 3355 : O->getComplexIntReal(), ObjType); 3356 } else { 3357 assert(O->isComplexFloat()); 3358 return handler.found(Index ? O->getComplexFloatImag() 3359 : O->getComplexFloatReal(), ObjType); 3360 } 3361 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3362 if (Field->isMutable() && 3363 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3364 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3365 << handler.AccessKind << Field; 3366 Info.Note(Field->getLocation(), diag::note_declared_at); 3367 return handler.failed(); 3368 } 3369 3370 // Next subobject is a class, struct or union field. 3371 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3372 if (RD->isUnion()) { 3373 const FieldDecl *UnionField = O->getUnionField(); 3374 if (!UnionField || 3375 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3376 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3377 // Placement new onto an inactive union member makes it active. 3378 O->setUnion(Field, APValue()); 3379 } else { 3380 // FIXME: If O->getUnionValue() is absent, report that there's no 3381 // active union member rather than reporting the prior active union 3382 // member. We'll need to fix nullptr_t to not use APValue() as its 3383 // representation first. 3384 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3385 << handler.AccessKind << Field << !UnionField << UnionField; 3386 return handler.failed(); 3387 } 3388 } 3389 O = &O->getUnionValue(); 3390 } else 3391 O = &O->getStructField(Field->getFieldIndex()); 3392 3393 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3394 LastField = Field; 3395 if (Field->getType().isVolatileQualified()) 3396 VolatileField = Field; 3397 } else { 3398 // Next subobject is a base class. 3399 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3400 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3401 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3402 3403 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3404 } 3405 } 3406 } 3407 3408 namespace { 3409 struct ExtractSubobjectHandler { 3410 EvalInfo &Info; 3411 const Expr *E; 3412 APValue &Result; 3413 const AccessKinds AccessKind; 3414 3415 typedef bool result_type; 3416 bool failed() { return false; } 3417 bool found(APValue &Subobj, QualType SubobjType) { 3418 Result = Subobj; 3419 if (AccessKind == AK_ReadObjectRepresentation) 3420 return true; 3421 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3422 } 3423 bool found(APSInt &Value, QualType SubobjType) { 3424 Result = APValue(Value); 3425 return true; 3426 } 3427 bool found(APFloat &Value, QualType SubobjType) { 3428 Result = APValue(Value); 3429 return true; 3430 } 3431 }; 3432 } // end anonymous namespace 3433 3434 /// Extract the designated sub-object of an rvalue. 3435 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3436 const CompleteObject &Obj, 3437 const SubobjectDesignator &Sub, APValue &Result, 3438 AccessKinds AK = AK_Read) { 3439 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3440 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3441 return findSubobject(Info, E, Obj, Sub, Handler); 3442 } 3443 3444 namespace { 3445 struct ModifySubobjectHandler { 3446 EvalInfo &Info; 3447 APValue &NewVal; 3448 const Expr *E; 3449 3450 typedef bool result_type; 3451 static const AccessKinds AccessKind = AK_Assign; 3452 3453 bool checkConst(QualType QT) { 3454 // Assigning to a const object has undefined behavior. 3455 if (QT.isConstQualified()) { 3456 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3457 return false; 3458 } 3459 return true; 3460 } 3461 3462 bool failed() { return false; } 3463 bool found(APValue &Subobj, QualType SubobjType) { 3464 if (!checkConst(SubobjType)) 3465 return false; 3466 // We've been given ownership of NewVal, so just swap it in. 3467 Subobj.swap(NewVal); 3468 return true; 3469 } 3470 bool found(APSInt &Value, QualType SubobjType) { 3471 if (!checkConst(SubobjType)) 3472 return false; 3473 if (!NewVal.isInt()) { 3474 // Maybe trying to write a cast pointer value into a complex? 3475 Info.FFDiag(E); 3476 return false; 3477 } 3478 Value = NewVal.getInt(); 3479 return true; 3480 } 3481 bool found(APFloat &Value, QualType SubobjType) { 3482 if (!checkConst(SubobjType)) 3483 return false; 3484 Value = NewVal.getFloat(); 3485 return true; 3486 } 3487 }; 3488 } // end anonymous namespace 3489 3490 const AccessKinds ModifySubobjectHandler::AccessKind; 3491 3492 /// Update the designated sub-object of an rvalue to the given value. 3493 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3494 const CompleteObject &Obj, 3495 const SubobjectDesignator &Sub, 3496 APValue &NewVal) { 3497 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3498 return findSubobject(Info, E, Obj, Sub, Handler); 3499 } 3500 3501 /// Find the position where two subobject designators diverge, or equivalently 3502 /// the length of the common initial subsequence. 3503 static unsigned FindDesignatorMismatch(QualType ObjType, 3504 const SubobjectDesignator &A, 3505 const SubobjectDesignator &B, 3506 bool &WasArrayIndex) { 3507 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3508 for (/**/; I != N; ++I) { 3509 if (!ObjType.isNull() && 3510 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3511 // Next subobject is an array element. 3512 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3513 WasArrayIndex = true; 3514 return I; 3515 } 3516 if (ObjType->isAnyComplexType()) 3517 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3518 else 3519 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3520 } else { 3521 if (A.Entries[I].getAsBaseOrMember() != 3522 B.Entries[I].getAsBaseOrMember()) { 3523 WasArrayIndex = false; 3524 return I; 3525 } 3526 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3527 // Next subobject is a field. 3528 ObjType = FD->getType(); 3529 else 3530 // Next subobject is a base class. 3531 ObjType = QualType(); 3532 } 3533 } 3534 WasArrayIndex = false; 3535 return I; 3536 } 3537 3538 /// Determine whether the given subobject designators refer to elements of the 3539 /// same array object. 3540 static bool AreElementsOfSameArray(QualType ObjType, 3541 const SubobjectDesignator &A, 3542 const SubobjectDesignator &B) { 3543 if (A.Entries.size() != B.Entries.size()) 3544 return false; 3545 3546 bool IsArray = A.MostDerivedIsArrayElement; 3547 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3548 // A is a subobject of the array element. 3549 return false; 3550 3551 // If A (and B) designates an array element, the last entry will be the array 3552 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3553 // of length 1' case, and the entire path must match. 3554 bool WasArrayIndex; 3555 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3556 return CommonLength >= A.Entries.size() - IsArray; 3557 } 3558 3559 /// Find the complete object to which an LValue refers. 3560 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3561 AccessKinds AK, const LValue &LVal, 3562 QualType LValType) { 3563 if (LVal.InvalidBase) { 3564 Info.FFDiag(E); 3565 return CompleteObject(); 3566 } 3567 3568 if (!LVal.Base) { 3569 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3570 return CompleteObject(); 3571 } 3572 3573 CallStackFrame *Frame = nullptr; 3574 unsigned Depth = 0; 3575 if (LVal.getLValueCallIndex()) { 3576 std::tie(Frame, Depth) = 3577 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3578 if (!Frame) { 3579 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3580 << AK << LVal.Base.is<const ValueDecl*>(); 3581 NoteLValueLocation(Info, LVal.Base); 3582 return CompleteObject(); 3583 } 3584 } 3585 3586 bool IsAccess = isAnyAccess(AK); 3587 3588 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3589 // is not a constant expression (even if the object is non-volatile). We also 3590 // apply this rule to C++98, in order to conform to the expected 'volatile' 3591 // semantics. 3592 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3593 if (Info.getLangOpts().CPlusPlus) 3594 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3595 << AK << LValType; 3596 else 3597 Info.FFDiag(E); 3598 return CompleteObject(); 3599 } 3600 3601 // Compute value storage location and type of base object. 3602 APValue *BaseVal = nullptr; 3603 QualType BaseType = getType(LVal.Base); 3604 3605 if (const ConstantExpr *CE = 3606 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3607 /// Nested immediate invocation have been previously removed so if we found 3608 /// a ConstantExpr it can only be the EvaluatingDecl. 3609 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3610 (void)CE; 3611 BaseVal = Info.EvaluatingDeclValue; 3612 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3613 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3614 // In C++11, constexpr, non-volatile variables initialized with constant 3615 // expressions are constant expressions too. Inside constexpr functions, 3616 // parameters are constant expressions even if they're non-const. 3617 // In C++1y, objects local to a constant expression (those with a Frame) are 3618 // both readable and writable inside constant expressions. 3619 // In C, such things can also be folded, although they are not ICEs. 3620 const VarDecl *VD = dyn_cast<VarDecl>(D); 3621 if (VD) { 3622 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3623 VD = VDef; 3624 } 3625 if (!VD || VD->isInvalidDecl()) { 3626 Info.FFDiag(E); 3627 return CompleteObject(); 3628 } 3629 3630 // Unless we're looking at a local variable or argument in a constexpr call, 3631 // the variable we're reading must be const. 3632 if (!Frame) { 3633 if (Info.getLangOpts().CPlusPlus14 && 3634 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3635 // OK, we can read and modify an object if we're in the process of 3636 // evaluating its initializer, because its lifetime began in this 3637 // evaluation. 3638 } else if (isModification(AK)) { 3639 // All the remaining cases do not permit modification of the object. 3640 Info.FFDiag(E, diag::note_constexpr_modify_global); 3641 return CompleteObject(); 3642 } else if (VD->isConstexpr()) { 3643 // OK, we can read this variable. 3644 } else if (BaseType->isIntegralOrEnumerationType()) { 3645 // In OpenCL if a variable is in constant address space it is a const 3646 // value. 3647 if (!(BaseType.isConstQualified() || 3648 (Info.getLangOpts().OpenCL && 3649 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3650 if (!IsAccess) 3651 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3652 if (Info.getLangOpts().CPlusPlus) { 3653 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3654 Info.Note(VD->getLocation(), diag::note_declared_at); 3655 } else { 3656 Info.FFDiag(E); 3657 } 3658 return CompleteObject(); 3659 } 3660 } else if (!IsAccess) { 3661 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3662 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3663 // We support folding of const floating-point types, in order to make 3664 // static const data members of such types (supported as an extension) 3665 // more useful. 3666 if (Info.getLangOpts().CPlusPlus11) { 3667 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3668 Info.Note(VD->getLocation(), diag::note_declared_at); 3669 } else { 3670 Info.CCEDiag(E); 3671 } 3672 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3673 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3674 // Keep evaluating to see what we can do. 3675 } else { 3676 // FIXME: Allow folding of values of any literal type in all languages. 3677 if (Info.checkingPotentialConstantExpression() && 3678 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3679 // The definition of this variable could be constexpr. We can't 3680 // access it right now, but may be able to in future. 3681 } else if (Info.getLangOpts().CPlusPlus11) { 3682 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3683 Info.Note(VD->getLocation(), diag::note_declared_at); 3684 } else { 3685 Info.FFDiag(E); 3686 } 3687 return CompleteObject(); 3688 } 3689 } 3690 3691 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3692 return CompleteObject(); 3693 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3694 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3695 if (!Alloc) { 3696 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3697 return CompleteObject(); 3698 } 3699 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3700 LVal.Base.getDynamicAllocType()); 3701 } else { 3702 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3703 3704 if (!Frame) { 3705 if (const MaterializeTemporaryExpr *MTE = 3706 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3707 assert(MTE->getStorageDuration() == SD_Static && 3708 "should have a frame for a non-global materialized temporary"); 3709 3710 // Per C++1y [expr.const]p2: 3711 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3712 // - a [...] glvalue of integral or enumeration type that refers to 3713 // a non-volatile const object [...] 3714 // [...] 3715 // - a [...] glvalue of literal type that refers to a non-volatile 3716 // object whose lifetime began within the evaluation of e. 3717 // 3718 // C++11 misses the 'began within the evaluation of e' check and 3719 // instead allows all temporaries, including things like: 3720 // int &&r = 1; 3721 // int x = ++r; 3722 // constexpr int k = r; 3723 // Therefore we use the C++14 rules in C++11 too. 3724 // 3725 // Note that temporaries whose lifetimes began while evaluating a 3726 // variable's constructor are not usable while evaluating the 3727 // corresponding destructor, not even if they're of const-qualified 3728 // types. 3729 if (!(BaseType.isConstQualified() && 3730 BaseType->isIntegralOrEnumerationType()) && 3731 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 3732 if (!IsAccess) 3733 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3734 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3735 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3736 return CompleteObject(); 3737 } 3738 3739 BaseVal = MTE->getOrCreateValue(false); 3740 assert(BaseVal && "got reference to unevaluated temporary"); 3741 } else { 3742 if (!IsAccess) 3743 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3744 APValue Val; 3745 LVal.moveInto(Val); 3746 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3747 << AK 3748 << Val.getAsString(Info.Ctx, 3749 Info.Ctx.getLValueReferenceType(LValType)); 3750 NoteLValueLocation(Info, LVal.Base); 3751 return CompleteObject(); 3752 } 3753 } else { 3754 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3755 assert(BaseVal && "missing value for temporary"); 3756 } 3757 } 3758 3759 // In C++14, we can't safely access any mutable state when we might be 3760 // evaluating after an unmodeled side effect. 3761 // 3762 // FIXME: Not all local state is mutable. Allow local constant subobjects 3763 // to be read here (but take care with 'mutable' fields). 3764 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3765 Info.EvalStatus.HasSideEffects) || 3766 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3767 return CompleteObject(); 3768 3769 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3770 } 3771 3772 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3773 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3774 /// glvalue referred to by an entity of reference type. 3775 /// 3776 /// \param Info - Information about the ongoing evaluation. 3777 /// \param Conv - The expression for which we are performing the conversion. 3778 /// Used for diagnostics. 3779 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3780 /// case of a non-class type). 3781 /// \param LVal - The glvalue on which we are attempting to perform this action. 3782 /// \param RVal - The produced value will be placed here. 3783 /// \param WantObjectRepresentation - If true, we're looking for the object 3784 /// representation rather than the value, and in particular, 3785 /// there is no requirement that the result be fully initialized. 3786 static bool 3787 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 3788 const LValue &LVal, APValue &RVal, 3789 bool WantObjectRepresentation = false) { 3790 if (LVal.Designator.Invalid) 3791 return false; 3792 3793 // Check for special cases where there is no existing APValue to look at. 3794 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3795 3796 AccessKinds AK = 3797 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 3798 3799 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3800 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3801 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3802 // initializer until now for such expressions. Such an expression can't be 3803 // an ICE in C, so this only matters for fold. 3804 if (Type.isVolatileQualified()) { 3805 Info.FFDiag(Conv); 3806 return false; 3807 } 3808 APValue Lit; 3809 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3810 return false; 3811 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 3812 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 3813 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3814 // Special-case character extraction so we don't have to construct an 3815 // APValue for the whole string. 3816 assert(LVal.Designator.Entries.size() <= 1 && 3817 "Can only read characters from string literals"); 3818 if (LVal.Designator.Entries.empty()) { 3819 // Fail for now for LValue to RValue conversion of an array. 3820 // (This shouldn't show up in C/C++, but it could be triggered by a 3821 // weird EvaluateAsRValue call from a tool.) 3822 Info.FFDiag(Conv); 3823 return false; 3824 } 3825 if (LVal.Designator.isOnePastTheEnd()) { 3826 if (Info.getLangOpts().CPlusPlus11) 3827 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 3828 else 3829 Info.FFDiag(Conv); 3830 return false; 3831 } 3832 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 3833 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 3834 return true; 3835 } 3836 } 3837 3838 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 3839 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 3840 } 3841 3842 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3843 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3844 QualType LValType, APValue &Val) { 3845 if (LVal.Designator.Invalid) 3846 return false; 3847 3848 if (!Info.getLangOpts().CPlusPlus14) { 3849 Info.FFDiag(E); 3850 return false; 3851 } 3852 3853 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3854 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3855 } 3856 3857 namespace { 3858 struct CompoundAssignSubobjectHandler { 3859 EvalInfo &Info; 3860 const Expr *E; 3861 QualType PromotedLHSType; 3862 BinaryOperatorKind Opcode; 3863 const APValue &RHS; 3864 3865 static const AccessKinds AccessKind = AK_Assign; 3866 3867 typedef bool result_type; 3868 3869 bool checkConst(QualType QT) { 3870 // Assigning to a const object has undefined behavior. 3871 if (QT.isConstQualified()) { 3872 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3873 return false; 3874 } 3875 return true; 3876 } 3877 3878 bool failed() { return false; } 3879 bool found(APValue &Subobj, QualType SubobjType) { 3880 switch (Subobj.getKind()) { 3881 case APValue::Int: 3882 return found(Subobj.getInt(), SubobjType); 3883 case APValue::Float: 3884 return found(Subobj.getFloat(), SubobjType); 3885 case APValue::ComplexInt: 3886 case APValue::ComplexFloat: 3887 // FIXME: Implement complex compound assignment. 3888 Info.FFDiag(E); 3889 return false; 3890 case APValue::LValue: 3891 return foundPointer(Subobj, SubobjType); 3892 default: 3893 // FIXME: can this happen? 3894 Info.FFDiag(E); 3895 return false; 3896 } 3897 } 3898 bool found(APSInt &Value, QualType SubobjType) { 3899 if (!checkConst(SubobjType)) 3900 return false; 3901 3902 if (!SubobjType->isIntegerType()) { 3903 // We don't support compound assignment on integer-cast-to-pointer 3904 // values. 3905 Info.FFDiag(E); 3906 return false; 3907 } 3908 3909 if (RHS.isInt()) { 3910 APSInt LHS = 3911 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 3912 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3913 return false; 3914 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3915 return true; 3916 } else if (RHS.isFloat()) { 3917 APFloat FValue(0.0); 3918 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 3919 FValue) && 3920 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 3921 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 3922 Value); 3923 } 3924 3925 Info.FFDiag(E); 3926 return false; 3927 } 3928 bool found(APFloat &Value, QualType SubobjType) { 3929 return checkConst(SubobjType) && 3930 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3931 Value) && 3932 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3933 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3934 } 3935 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3936 if (!checkConst(SubobjType)) 3937 return false; 3938 3939 QualType PointeeType; 3940 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3941 PointeeType = PT->getPointeeType(); 3942 3943 if (PointeeType.isNull() || !RHS.isInt() || 3944 (Opcode != BO_Add && Opcode != BO_Sub)) { 3945 Info.FFDiag(E); 3946 return false; 3947 } 3948 3949 APSInt Offset = RHS.getInt(); 3950 if (Opcode == BO_Sub) 3951 negateAsSigned(Offset); 3952 3953 LValue LVal; 3954 LVal.setFrom(Info.Ctx, Subobj); 3955 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3956 return false; 3957 LVal.moveInto(Subobj); 3958 return true; 3959 } 3960 }; 3961 } // end anonymous namespace 3962 3963 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3964 3965 /// Perform a compound assignment of LVal <op>= RVal. 3966 static bool handleCompoundAssignment( 3967 EvalInfo &Info, const Expr *E, 3968 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3969 BinaryOperatorKind Opcode, const APValue &RVal) { 3970 if (LVal.Designator.Invalid) 3971 return false; 3972 3973 if (!Info.getLangOpts().CPlusPlus14) { 3974 Info.FFDiag(E); 3975 return false; 3976 } 3977 3978 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3979 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3980 RVal }; 3981 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3982 } 3983 3984 namespace { 3985 struct IncDecSubobjectHandler { 3986 EvalInfo &Info; 3987 const UnaryOperator *E; 3988 AccessKinds AccessKind; 3989 APValue *Old; 3990 3991 typedef bool result_type; 3992 3993 bool checkConst(QualType QT) { 3994 // Assigning to a const object has undefined behavior. 3995 if (QT.isConstQualified()) { 3996 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3997 return false; 3998 } 3999 return true; 4000 } 4001 4002 bool failed() { return false; } 4003 bool found(APValue &Subobj, QualType SubobjType) { 4004 // Stash the old value. Also clear Old, so we don't clobber it later 4005 // if we're post-incrementing a complex. 4006 if (Old) { 4007 *Old = Subobj; 4008 Old = nullptr; 4009 } 4010 4011 switch (Subobj.getKind()) { 4012 case APValue::Int: 4013 return found(Subobj.getInt(), SubobjType); 4014 case APValue::Float: 4015 return found(Subobj.getFloat(), SubobjType); 4016 case APValue::ComplexInt: 4017 return found(Subobj.getComplexIntReal(), 4018 SubobjType->castAs<ComplexType>()->getElementType() 4019 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4020 case APValue::ComplexFloat: 4021 return found(Subobj.getComplexFloatReal(), 4022 SubobjType->castAs<ComplexType>()->getElementType() 4023 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4024 case APValue::LValue: 4025 return foundPointer(Subobj, SubobjType); 4026 default: 4027 // FIXME: can this happen? 4028 Info.FFDiag(E); 4029 return false; 4030 } 4031 } 4032 bool found(APSInt &Value, QualType SubobjType) { 4033 if (!checkConst(SubobjType)) 4034 return false; 4035 4036 if (!SubobjType->isIntegerType()) { 4037 // We don't support increment / decrement on integer-cast-to-pointer 4038 // values. 4039 Info.FFDiag(E); 4040 return false; 4041 } 4042 4043 if (Old) *Old = APValue(Value); 4044 4045 // bool arithmetic promotes to int, and the conversion back to bool 4046 // doesn't reduce mod 2^n, so special-case it. 4047 if (SubobjType->isBooleanType()) { 4048 if (AccessKind == AK_Increment) 4049 Value = 1; 4050 else 4051 Value = !Value; 4052 return true; 4053 } 4054 4055 bool WasNegative = Value.isNegative(); 4056 if (AccessKind == AK_Increment) { 4057 ++Value; 4058 4059 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4060 APSInt ActualValue(Value, /*IsUnsigned*/true); 4061 return HandleOverflow(Info, E, ActualValue, SubobjType); 4062 } 4063 } else { 4064 --Value; 4065 4066 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4067 unsigned BitWidth = Value.getBitWidth(); 4068 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4069 ActualValue.setBit(BitWidth); 4070 return HandleOverflow(Info, E, ActualValue, SubobjType); 4071 } 4072 } 4073 return true; 4074 } 4075 bool found(APFloat &Value, QualType SubobjType) { 4076 if (!checkConst(SubobjType)) 4077 return false; 4078 4079 if (Old) *Old = APValue(Value); 4080 4081 APFloat One(Value.getSemantics(), 1); 4082 if (AccessKind == AK_Increment) 4083 Value.add(One, APFloat::rmNearestTiesToEven); 4084 else 4085 Value.subtract(One, APFloat::rmNearestTiesToEven); 4086 return true; 4087 } 4088 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4089 if (!checkConst(SubobjType)) 4090 return false; 4091 4092 QualType PointeeType; 4093 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4094 PointeeType = PT->getPointeeType(); 4095 else { 4096 Info.FFDiag(E); 4097 return false; 4098 } 4099 4100 LValue LVal; 4101 LVal.setFrom(Info.Ctx, Subobj); 4102 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4103 AccessKind == AK_Increment ? 1 : -1)) 4104 return false; 4105 LVal.moveInto(Subobj); 4106 return true; 4107 } 4108 }; 4109 } // end anonymous namespace 4110 4111 /// Perform an increment or decrement on LVal. 4112 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4113 QualType LValType, bool IsIncrement, APValue *Old) { 4114 if (LVal.Designator.Invalid) 4115 return false; 4116 4117 if (!Info.getLangOpts().CPlusPlus14) { 4118 Info.FFDiag(E); 4119 return false; 4120 } 4121 4122 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4123 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4124 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4125 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4126 } 4127 4128 /// Build an lvalue for the object argument of a member function call. 4129 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4130 LValue &This) { 4131 if (Object->getType()->isPointerType() && Object->isRValue()) 4132 return EvaluatePointer(Object, This, Info); 4133 4134 if (Object->isGLValue()) 4135 return EvaluateLValue(Object, This, Info); 4136 4137 if (Object->getType()->isLiteralType(Info.Ctx)) 4138 return EvaluateTemporary(Object, This, Info); 4139 4140 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4141 return false; 4142 } 4143 4144 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4145 /// lvalue referring to the result. 4146 /// 4147 /// \param Info - Information about the ongoing evaluation. 4148 /// \param LV - An lvalue referring to the base of the member pointer. 4149 /// \param RHS - The member pointer expression. 4150 /// \param IncludeMember - Specifies whether the member itself is included in 4151 /// the resulting LValue subobject designator. This is not possible when 4152 /// creating a bound member function. 4153 /// \return The field or method declaration to which the member pointer refers, 4154 /// or 0 if evaluation fails. 4155 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4156 QualType LVType, 4157 LValue &LV, 4158 const Expr *RHS, 4159 bool IncludeMember = true) { 4160 MemberPtr MemPtr; 4161 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4162 return nullptr; 4163 4164 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4165 // member value, the behavior is undefined. 4166 if (!MemPtr.getDecl()) { 4167 // FIXME: Specific diagnostic. 4168 Info.FFDiag(RHS); 4169 return nullptr; 4170 } 4171 4172 if (MemPtr.isDerivedMember()) { 4173 // This is a member of some derived class. Truncate LV appropriately. 4174 // The end of the derived-to-base path for the base object must match the 4175 // derived-to-base path for the member pointer. 4176 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4177 LV.Designator.Entries.size()) { 4178 Info.FFDiag(RHS); 4179 return nullptr; 4180 } 4181 unsigned PathLengthToMember = 4182 LV.Designator.Entries.size() - MemPtr.Path.size(); 4183 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4184 const CXXRecordDecl *LVDecl = getAsBaseClass( 4185 LV.Designator.Entries[PathLengthToMember + I]); 4186 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4187 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4188 Info.FFDiag(RHS); 4189 return nullptr; 4190 } 4191 } 4192 4193 // Truncate the lvalue to the appropriate derived class. 4194 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4195 PathLengthToMember)) 4196 return nullptr; 4197 } else if (!MemPtr.Path.empty()) { 4198 // Extend the LValue path with the member pointer's path. 4199 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4200 MemPtr.Path.size() + IncludeMember); 4201 4202 // Walk down to the appropriate base class. 4203 if (const PointerType *PT = LVType->getAs<PointerType>()) 4204 LVType = PT->getPointeeType(); 4205 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4206 assert(RD && "member pointer access on non-class-type expression"); 4207 // The first class in the path is that of the lvalue. 4208 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4209 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4210 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4211 return nullptr; 4212 RD = Base; 4213 } 4214 // Finally cast to the class containing the member. 4215 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4216 MemPtr.getContainingRecord())) 4217 return nullptr; 4218 } 4219 4220 // Add the member. Note that we cannot build bound member functions here. 4221 if (IncludeMember) { 4222 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4223 if (!HandleLValueMember(Info, RHS, LV, FD)) 4224 return nullptr; 4225 } else if (const IndirectFieldDecl *IFD = 4226 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4227 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4228 return nullptr; 4229 } else { 4230 llvm_unreachable("can't construct reference to bound member function"); 4231 } 4232 } 4233 4234 return MemPtr.getDecl(); 4235 } 4236 4237 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4238 const BinaryOperator *BO, 4239 LValue &LV, 4240 bool IncludeMember = true) { 4241 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4242 4243 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4244 if (Info.noteFailure()) { 4245 MemberPtr MemPtr; 4246 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4247 } 4248 return nullptr; 4249 } 4250 4251 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4252 BO->getRHS(), IncludeMember); 4253 } 4254 4255 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4256 /// the provided lvalue, which currently refers to the base object. 4257 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4258 LValue &Result) { 4259 SubobjectDesignator &D = Result.Designator; 4260 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4261 return false; 4262 4263 QualType TargetQT = E->getType(); 4264 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4265 TargetQT = PT->getPointeeType(); 4266 4267 // Check this cast lands within the final derived-to-base subobject path. 4268 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4269 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4270 << D.MostDerivedType << TargetQT; 4271 return false; 4272 } 4273 4274 // Check the type of the final cast. We don't need to check the path, 4275 // since a cast can only be formed if the path is unique. 4276 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4277 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4278 const CXXRecordDecl *FinalType; 4279 if (NewEntriesSize == D.MostDerivedPathLength) 4280 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4281 else 4282 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4283 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4284 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4285 << D.MostDerivedType << TargetQT; 4286 return false; 4287 } 4288 4289 // Truncate the lvalue to the appropriate derived class. 4290 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4291 } 4292 4293 /// Get the value to use for a default-initialized object of type T. 4294 static APValue getDefaultInitValue(QualType T) { 4295 if (auto *RD = T->getAsCXXRecordDecl()) { 4296 if (RD->isUnion()) 4297 return APValue((const FieldDecl*)nullptr); 4298 4299 APValue Struct(APValue::UninitStruct(), RD->getNumBases(), 4300 std::distance(RD->field_begin(), RD->field_end())); 4301 4302 unsigned Index = 0; 4303 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4304 End = RD->bases_end(); I != End; ++I, ++Index) 4305 Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); 4306 4307 for (const auto *I : RD->fields()) { 4308 if (I->isUnnamedBitfield()) 4309 continue; 4310 Struct.getStructField(I->getFieldIndex()) = 4311 getDefaultInitValue(I->getType()); 4312 } 4313 return Struct; 4314 } 4315 4316 if (auto *AT = 4317 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4318 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4319 if (Array.hasArrayFiller()) 4320 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); 4321 return Array; 4322 } 4323 4324 return APValue::IndeterminateValue(); 4325 } 4326 4327 namespace { 4328 enum EvalStmtResult { 4329 /// Evaluation failed. 4330 ESR_Failed, 4331 /// Hit a 'return' statement. 4332 ESR_Returned, 4333 /// Evaluation succeeded. 4334 ESR_Succeeded, 4335 /// Hit a 'continue' statement. 4336 ESR_Continue, 4337 /// Hit a 'break' statement. 4338 ESR_Break, 4339 /// Still scanning for 'case' or 'default' statement. 4340 ESR_CaseNotFound 4341 }; 4342 } 4343 4344 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4345 // We don't need to evaluate the initializer for a static local. 4346 if (!VD->hasLocalStorage()) 4347 return true; 4348 4349 LValue Result; 4350 APValue &Val = 4351 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4352 4353 const Expr *InitE = VD->getInit(); 4354 if (!InitE) { 4355 Val = getDefaultInitValue(VD->getType()); 4356 return true; 4357 } 4358 4359 if (InitE->isValueDependent()) 4360 return false; 4361 4362 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4363 // Wipe out any partially-computed value, to allow tracking that this 4364 // evaluation failed. 4365 Val = APValue(); 4366 return false; 4367 } 4368 4369 return true; 4370 } 4371 4372 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4373 bool OK = true; 4374 4375 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4376 OK &= EvaluateVarDecl(Info, VD); 4377 4378 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4379 for (auto *BD : DD->bindings()) 4380 if (auto *VD = BD->getHoldingVar()) 4381 OK &= EvaluateDecl(Info, VD); 4382 4383 return OK; 4384 } 4385 4386 4387 /// Evaluate a condition (either a variable declaration or an expression). 4388 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4389 const Expr *Cond, bool &Result) { 4390 FullExpressionRAII Scope(Info); 4391 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4392 return false; 4393 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4394 return false; 4395 return Scope.destroy(); 4396 } 4397 4398 namespace { 4399 /// A location where the result (returned value) of evaluating a 4400 /// statement should be stored. 4401 struct StmtResult { 4402 /// The APValue that should be filled in with the returned value. 4403 APValue &Value; 4404 /// The location containing the result, if any (used to support RVO). 4405 const LValue *Slot; 4406 }; 4407 4408 struct TempVersionRAII { 4409 CallStackFrame &Frame; 4410 4411 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4412 Frame.pushTempVersion(); 4413 } 4414 4415 ~TempVersionRAII() { 4416 Frame.popTempVersion(); 4417 } 4418 }; 4419 4420 } 4421 4422 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4423 const Stmt *S, 4424 const SwitchCase *SC = nullptr); 4425 4426 /// Evaluate the body of a loop, and translate the result as appropriate. 4427 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4428 const Stmt *Body, 4429 const SwitchCase *Case = nullptr) { 4430 BlockScopeRAII Scope(Info); 4431 4432 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4433 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4434 ESR = ESR_Failed; 4435 4436 switch (ESR) { 4437 case ESR_Break: 4438 return ESR_Succeeded; 4439 case ESR_Succeeded: 4440 case ESR_Continue: 4441 return ESR_Continue; 4442 case ESR_Failed: 4443 case ESR_Returned: 4444 case ESR_CaseNotFound: 4445 return ESR; 4446 } 4447 llvm_unreachable("Invalid EvalStmtResult!"); 4448 } 4449 4450 /// Evaluate a switch statement. 4451 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4452 const SwitchStmt *SS) { 4453 BlockScopeRAII Scope(Info); 4454 4455 // Evaluate the switch condition. 4456 APSInt Value; 4457 { 4458 if (const Stmt *Init = SS->getInit()) { 4459 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4460 if (ESR != ESR_Succeeded) { 4461 if (ESR != ESR_Failed && !Scope.destroy()) 4462 ESR = ESR_Failed; 4463 return ESR; 4464 } 4465 } 4466 4467 FullExpressionRAII CondScope(Info); 4468 if (SS->getConditionVariable() && 4469 !EvaluateDecl(Info, SS->getConditionVariable())) 4470 return ESR_Failed; 4471 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4472 return ESR_Failed; 4473 if (!CondScope.destroy()) 4474 return ESR_Failed; 4475 } 4476 4477 // Find the switch case corresponding to the value of the condition. 4478 // FIXME: Cache this lookup. 4479 const SwitchCase *Found = nullptr; 4480 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4481 SC = SC->getNextSwitchCase()) { 4482 if (isa<DefaultStmt>(SC)) { 4483 Found = SC; 4484 continue; 4485 } 4486 4487 const CaseStmt *CS = cast<CaseStmt>(SC); 4488 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4489 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4490 : LHS; 4491 if (LHS <= Value && Value <= RHS) { 4492 Found = SC; 4493 break; 4494 } 4495 } 4496 4497 if (!Found) 4498 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4499 4500 // Search the switch body for the switch case and evaluate it from there. 4501 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4502 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4503 return ESR_Failed; 4504 4505 switch (ESR) { 4506 case ESR_Break: 4507 return ESR_Succeeded; 4508 case ESR_Succeeded: 4509 case ESR_Continue: 4510 case ESR_Failed: 4511 case ESR_Returned: 4512 return ESR; 4513 case ESR_CaseNotFound: 4514 // This can only happen if the switch case is nested within a statement 4515 // expression. We have no intention of supporting that. 4516 Info.FFDiag(Found->getBeginLoc(), 4517 diag::note_constexpr_stmt_expr_unsupported); 4518 return ESR_Failed; 4519 } 4520 llvm_unreachable("Invalid EvalStmtResult!"); 4521 } 4522 4523 // Evaluate a statement. 4524 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4525 const Stmt *S, const SwitchCase *Case) { 4526 if (!Info.nextStep(S)) 4527 return ESR_Failed; 4528 4529 // If we're hunting down a 'case' or 'default' label, recurse through 4530 // substatements until we hit the label. 4531 if (Case) { 4532 switch (S->getStmtClass()) { 4533 case Stmt::CompoundStmtClass: 4534 // FIXME: Precompute which substatement of a compound statement we 4535 // would jump to, and go straight there rather than performing a 4536 // linear scan each time. 4537 case Stmt::LabelStmtClass: 4538 case Stmt::AttributedStmtClass: 4539 case Stmt::DoStmtClass: 4540 break; 4541 4542 case Stmt::CaseStmtClass: 4543 case Stmt::DefaultStmtClass: 4544 if (Case == S) 4545 Case = nullptr; 4546 break; 4547 4548 case Stmt::IfStmtClass: { 4549 // FIXME: Precompute which side of an 'if' we would jump to, and go 4550 // straight there rather than scanning both sides. 4551 const IfStmt *IS = cast<IfStmt>(S); 4552 4553 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4554 // preceded by our switch label. 4555 BlockScopeRAII Scope(Info); 4556 4557 // Step into the init statement in case it brings an (uninitialized) 4558 // variable into scope. 4559 if (const Stmt *Init = IS->getInit()) { 4560 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4561 if (ESR != ESR_CaseNotFound) { 4562 assert(ESR != ESR_Succeeded); 4563 return ESR; 4564 } 4565 } 4566 4567 // Condition variable must be initialized if it exists. 4568 // FIXME: We can skip evaluating the body if there's a condition 4569 // variable, as there can't be any case labels within it. 4570 // (The same is true for 'for' statements.) 4571 4572 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4573 if (ESR == ESR_Failed) 4574 return ESR; 4575 if (ESR != ESR_CaseNotFound) 4576 return Scope.destroy() ? ESR : ESR_Failed; 4577 if (!IS->getElse()) 4578 return ESR_CaseNotFound; 4579 4580 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4581 if (ESR == ESR_Failed) 4582 return ESR; 4583 if (ESR != ESR_CaseNotFound) 4584 return Scope.destroy() ? ESR : ESR_Failed; 4585 return ESR_CaseNotFound; 4586 } 4587 4588 case Stmt::WhileStmtClass: { 4589 EvalStmtResult ESR = 4590 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4591 if (ESR != ESR_Continue) 4592 return ESR; 4593 break; 4594 } 4595 4596 case Stmt::ForStmtClass: { 4597 const ForStmt *FS = cast<ForStmt>(S); 4598 BlockScopeRAII Scope(Info); 4599 4600 // Step into the init statement in case it brings an (uninitialized) 4601 // variable into scope. 4602 if (const Stmt *Init = FS->getInit()) { 4603 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4604 if (ESR != ESR_CaseNotFound) { 4605 assert(ESR != ESR_Succeeded); 4606 return ESR; 4607 } 4608 } 4609 4610 EvalStmtResult ESR = 4611 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4612 if (ESR != ESR_Continue) 4613 return ESR; 4614 if (FS->getInc()) { 4615 FullExpressionRAII IncScope(Info); 4616 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4617 return ESR_Failed; 4618 } 4619 break; 4620 } 4621 4622 case Stmt::DeclStmtClass: { 4623 // Start the lifetime of any uninitialized variables we encounter. They 4624 // might be used by the selected branch of the switch. 4625 const DeclStmt *DS = cast<DeclStmt>(S); 4626 for (const auto *D : DS->decls()) { 4627 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4628 if (VD->hasLocalStorage() && !VD->getInit()) 4629 if (!EvaluateVarDecl(Info, VD)) 4630 return ESR_Failed; 4631 // FIXME: If the variable has initialization that can't be jumped 4632 // over, bail out of any immediately-surrounding compound-statement 4633 // too. There can't be any case labels here. 4634 } 4635 } 4636 return ESR_CaseNotFound; 4637 } 4638 4639 default: 4640 return ESR_CaseNotFound; 4641 } 4642 } 4643 4644 switch (S->getStmtClass()) { 4645 default: 4646 if (const Expr *E = dyn_cast<Expr>(S)) { 4647 // Don't bother evaluating beyond an expression-statement which couldn't 4648 // be evaluated. 4649 // FIXME: Do we need the FullExpressionRAII object here? 4650 // VisitExprWithCleanups should create one when necessary. 4651 FullExpressionRAII Scope(Info); 4652 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4653 return ESR_Failed; 4654 return ESR_Succeeded; 4655 } 4656 4657 Info.FFDiag(S->getBeginLoc()); 4658 return ESR_Failed; 4659 4660 case Stmt::NullStmtClass: 4661 return ESR_Succeeded; 4662 4663 case Stmt::DeclStmtClass: { 4664 const DeclStmt *DS = cast<DeclStmt>(S); 4665 for (const auto *D : DS->decls()) { 4666 // Each declaration initialization is its own full-expression. 4667 FullExpressionRAII Scope(Info); 4668 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4669 return ESR_Failed; 4670 if (!Scope.destroy()) 4671 return ESR_Failed; 4672 } 4673 return ESR_Succeeded; 4674 } 4675 4676 case Stmt::ReturnStmtClass: { 4677 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4678 FullExpressionRAII Scope(Info); 4679 if (RetExpr && 4680 !(Result.Slot 4681 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4682 : Evaluate(Result.Value, Info, RetExpr))) 4683 return ESR_Failed; 4684 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4685 } 4686 4687 case Stmt::CompoundStmtClass: { 4688 BlockScopeRAII Scope(Info); 4689 4690 const CompoundStmt *CS = cast<CompoundStmt>(S); 4691 for (const auto *BI : CS->body()) { 4692 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4693 if (ESR == ESR_Succeeded) 4694 Case = nullptr; 4695 else if (ESR != ESR_CaseNotFound) { 4696 if (ESR != ESR_Failed && !Scope.destroy()) 4697 return ESR_Failed; 4698 return ESR; 4699 } 4700 } 4701 if (Case) 4702 return ESR_CaseNotFound; 4703 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4704 } 4705 4706 case Stmt::IfStmtClass: { 4707 const IfStmt *IS = cast<IfStmt>(S); 4708 4709 // Evaluate the condition, as either a var decl or as an expression. 4710 BlockScopeRAII Scope(Info); 4711 if (const Stmt *Init = IS->getInit()) { 4712 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4713 if (ESR != ESR_Succeeded) { 4714 if (ESR != ESR_Failed && !Scope.destroy()) 4715 return ESR_Failed; 4716 return ESR; 4717 } 4718 } 4719 bool Cond; 4720 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4721 return ESR_Failed; 4722 4723 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4724 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4725 if (ESR != ESR_Succeeded) { 4726 if (ESR != ESR_Failed && !Scope.destroy()) 4727 return ESR_Failed; 4728 return ESR; 4729 } 4730 } 4731 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4732 } 4733 4734 case Stmt::WhileStmtClass: { 4735 const WhileStmt *WS = cast<WhileStmt>(S); 4736 while (true) { 4737 BlockScopeRAII Scope(Info); 4738 bool Continue; 4739 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4740 Continue)) 4741 return ESR_Failed; 4742 if (!Continue) 4743 break; 4744 4745 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4746 if (ESR != ESR_Continue) { 4747 if (ESR != ESR_Failed && !Scope.destroy()) 4748 return ESR_Failed; 4749 return ESR; 4750 } 4751 if (!Scope.destroy()) 4752 return ESR_Failed; 4753 } 4754 return ESR_Succeeded; 4755 } 4756 4757 case Stmt::DoStmtClass: { 4758 const DoStmt *DS = cast<DoStmt>(S); 4759 bool Continue; 4760 do { 4761 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4762 if (ESR != ESR_Continue) 4763 return ESR; 4764 Case = nullptr; 4765 4766 FullExpressionRAII CondScope(Info); 4767 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 4768 !CondScope.destroy()) 4769 return ESR_Failed; 4770 } while (Continue); 4771 return ESR_Succeeded; 4772 } 4773 4774 case Stmt::ForStmtClass: { 4775 const ForStmt *FS = cast<ForStmt>(S); 4776 BlockScopeRAII ForScope(Info); 4777 if (FS->getInit()) { 4778 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4779 if (ESR != ESR_Succeeded) { 4780 if (ESR != ESR_Failed && !ForScope.destroy()) 4781 return ESR_Failed; 4782 return ESR; 4783 } 4784 } 4785 while (true) { 4786 BlockScopeRAII IterScope(Info); 4787 bool Continue = true; 4788 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4789 FS->getCond(), Continue)) 4790 return ESR_Failed; 4791 if (!Continue) 4792 break; 4793 4794 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4795 if (ESR != ESR_Continue) { 4796 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 4797 return ESR_Failed; 4798 return ESR; 4799 } 4800 4801 if (FS->getInc()) { 4802 FullExpressionRAII IncScope(Info); 4803 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4804 return ESR_Failed; 4805 } 4806 4807 if (!IterScope.destroy()) 4808 return ESR_Failed; 4809 } 4810 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 4811 } 4812 4813 case Stmt::CXXForRangeStmtClass: { 4814 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4815 BlockScopeRAII Scope(Info); 4816 4817 // Evaluate the init-statement if present. 4818 if (FS->getInit()) { 4819 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4820 if (ESR != ESR_Succeeded) { 4821 if (ESR != ESR_Failed && !Scope.destroy()) 4822 return ESR_Failed; 4823 return ESR; 4824 } 4825 } 4826 4827 // Initialize the __range variable. 4828 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4829 if (ESR != ESR_Succeeded) { 4830 if (ESR != ESR_Failed && !Scope.destroy()) 4831 return ESR_Failed; 4832 return ESR; 4833 } 4834 4835 // Create the __begin and __end iterators. 4836 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4837 if (ESR != ESR_Succeeded) { 4838 if (ESR != ESR_Failed && !Scope.destroy()) 4839 return ESR_Failed; 4840 return ESR; 4841 } 4842 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4843 if (ESR != ESR_Succeeded) { 4844 if (ESR != ESR_Failed && !Scope.destroy()) 4845 return ESR_Failed; 4846 return ESR; 4847 } 4848 4849 while (true) { 4850 // Condition: __begin != __end. 4851 { 4852 bool Continue = true; 4853 FullExpressionRAII CondExpr(Info); 4854 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4855 return ESR_Failed; 4856 if (!Continue) 4857 break; 4858 } 4859 4860 // User's variable declaration, initialized by *__begin. 4861 BlockScopeRAII InnerScope(Info); 4862 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4863 if (ESR != ESR_Succeeded) { 4864 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 4865 return ESR_Failed; 4866 return ESR; 4867 } 4868 4869 // Loop body. 4870 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4871 if (ESR != ESR_Continue) { 4872 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 4873 return ESR_Failed; 4874 return ESR; 4875 } 4876 4877 // Increment: ++__begin 4878 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4879 return ESR_Failed; 4880 4881 if (!InnerScope.destroy()) 4882 return ESR_Failed; 4883 } 4884 4885 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4886 } 4887 4888 case Stmt::SwitchStmtClass: 4889 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4890 4891 case Stmt::ContinueStmtClass: 4892 return ESR_Continue; 4893 4894 case Stmt::BreakStmtClass: 4895 return ESR_Break; 4896 4897 case Stmt::LabelStmtClass: 4898 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4899 4900 case Stmt::AttributedStmtClass: 4901 // As a general principle, C++11 attributes can be ignored without 4902 // any semantic impact. 4903 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4904 Case); 4905 4906 case Stmt::CaseStmtClass: 4907 case Stmt::DefaultStmtClass: 4908 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4909 case Stmt::CXXTryStmtClass: 4910 // Evaluate try blocks by evaluating all sub statements. 4911 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 4912 } 4913 } 4914 4915 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4916 /// default constructor. If so, we'll fold it whether or not it's marked as 4917 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4918 /// so we need special handling. 4919 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4920 const CXXConstructorDecl *CD, 4921 bool IsValueInitialization) { 4922 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4923 return false; 4924 4925 // Value-initialization does not call a trivial default constructor, so such a 4926 // call is a core constant expression whether or not the constructor is 4927 // constexpr. 4928 if (!CD->isConstexpr() && !IsValueInitialization) { 4929 if (Info.getLangOpts().CPlusPlus11) { 4930 // FIXME: If DiagDecl is an implicitly-declared special member function, 4931 // we should be much more explicit about why it's not constexpr. 4932 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4933 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4934 Info.Note(CD->getLocation(), diag::note_declared_at); 4935 } else { 4936 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4937 } 4938 } 4939 return true; 4940 } 4941 4942 /// CheckConstexprFunction - Check that a function can be called in a constant 4943 /// expression. 4944 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4945 const FunctionDecl *Declaration, 4946 const FunctionDecl *Definition, 4947 const Stmt *Body) { 4948 // Potential constant expressions can contain calls to declared, but not yet 4949 // defined, constexpr functions. 4950 if (Info.checkingPotentialConstantExpression() && !Definition && 4951 Declaration->isConstexpr()) 4952 return false; 4953 4954 // Bail out if the function declaration itself is invalid. We will 4955 // have produced a relevant diagnostic while parsing it, so just 4956 // note the problematic sub-expression. 4957 if (Declaration->isInvalidDecl()) { 4958 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4959 return false; 4960 } 4961 4962 // DR1872: An instantiated virtual constexpr function can't be called in a 4963 // constant expression (prior to C++20). We can still constant-fold such a 4964 // call. 4965 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && 4966 cast<CXXMethodDecl>(Declaration)->isVirtual()) 4967 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 4968 4969 if (Definition && Definition->isInvalidDecl()) { 4970 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4971 return false; 4972 } 4973 4974 // Can we evaluate this function call? 4975 if (Definition && Definition->isConstexpr() && Body) 4976 return true; 4977 4978 if (Info.getLangOpts().CPlusPlus11) { 4979 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4980 4981 // If this function is not constexpr because it is an inherited 4982 // non-constexpr constructor, diagnose that directly. 4983 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4984 if (CD && CD->isInheritingConstructor()) { 4985 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4986 if (!Inherited->isConstexpr()) 4987 DiagDecl = CD = Inherited; 4988 } 4989 4990 // FIXME: If DiagDecl is an implicitly-declared special member function 4991 // or an inheriting constructor, we should be much more explicit about why 4992 // it's not constexpr. 4993 if (CD && CD->isInheritingConstructor()) 4994 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4995 << CD->getInheritedConstructor().getConstructor()->getParent(); 4996 else 4997 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4998 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4999 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5000 } else { 5001 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5002 } 5003 return false; 5004 } 5005 5006 namespace { 5007 struct CheckDynamicTypeHandler { 5008 AccessKinds AccessKind; 5009 typedef bool result_type; 5010 bool failed() { return false; } 5011 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5012 bool found(APSInt &Value, QualType SubobjType) { return true; } 5013 bool found(APFloat &Value, QualType SubobjType) { return true; } 5014 }; 5015 } // end anonymous namespace 5016 5017 /// Check that we can access the notional vptr of an object / determine its 5018 /// dynamic type. 5019 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5020 AccessKinds AK, bool Polymorphic) { 5021 if (This.Designator.Invalid) 5022 return false; 5023 5024 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5025 5026 if (!Obj) 5027 return false; 5028 5029 if (!Obj.Value) { 5030 // The object is not usable in constant expressions, so we can't inspect 5031 // its value to see if it's in-lifetime or what the active union members 5032 // are. We can still check for a one-past-the-end lvalue. 5033 if (This.Designator.isOnePastTheEnd() || 5034 This.Designator.isMostDerivedAnUnsizedArray()) { 5035 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5036 ? diag::note_constexpr_access_past_end 5037 : diag::note_constexpr_access_unsized_array) 5038 << AK; 5039 return false; 5040 } else if (Polymorphic) { 5041 // Conservatively refuse to perform a polymorphic operation if we would 5042 // not be able to read a notional 'vptr' value. 5043 APValue Val; 5044 This.moveInto(Val); 5045 QualType StarThisType = 5046 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5047 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5048 << AK << Val.getAsString(Info.Ctx, StarThisType); 5049 return false; 5050 } 5051 return true; 5052 } 5053 5054 CheckDynamicTypeHandler Handler{AK}; 5055 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5056 } 5057 5058 /// Check that the pointee of the 'this' pointer in a member function call is 5059 /// either within its lifetime or in its period of construction or destruction. 5060 static bool 5061 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5062 const LValue &This, 5063 const CXXMethodDecl *NamedMember) { 5064 return checkDynamicType( 5065 Info, E, This, 5066 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5067 } 5068 5069 struct DynamicType { 5070 /// The dynamic class type of the object. 5071 const CXXRecordDecl *Type; 5072 /// The corresponding path length in the lvalue. 5073 unsigned PathLength; 5074 }; 5075 5076 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5077 unsigned PathLength) { 5078 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5079 Designator.Entries.size() && "invalid path length"); 5080 return (PathLength == Designator.MostDerivedPathLength) 5081 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5082 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5083 } 5084 5085 /// Determine the dynamic type of an object. 5086 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5087 LValue &This, AccessKinds AK) { 5088 // If we don't have an lvalue denoting an object of class type, there is no 5089 // meaningful dynamic type. (We consider objects of non-class type to have no 5090 // dynamic type.) 5091 if (!checkDynamicType(Info, E, This, AK, true)) 5092 return None; 5093 5094 // Refuse to compute a dynamic type in the presence of virtual bases. This 5095 // shouldn't happen other than in constant-folding situations, since literal 5096 // types can't have virtual bases. 5097 // 5098 // Note that consumers of DynamicType assume that the type has no virtual 5099 // bases, and will need modifications if this restriction is relaxed. 5100 const CXXRecordDecl *Class = 5101 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5102 if (!Class || Class->getNumVBases()) { 5103 Info.FFDiag(E); 5104 return None; 5105 } 5106 5107 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5108 // binary search here instead. But the overwhelmingly common case is that 5109 // we're not in the middle of a constructor, so it probably doesn't matter 5110 // in practice. 5111 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5112 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5113 PathLength <= Path.size(); ++PathLength) { 5114 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5115 Path.slice(0, PathLength))) { 5116 case ConstructionPhase::Bases: 5117 case ConstructionPhase::DestroyingBases: 5118 // We're constructing or destroying a base class. This is not the dynamic 5119 // type. 5120 break; 5121 5122 case ConstructionPhase::None: 5123 case ConstructionPhase::AfterBases: 5124 case ConstructionPhase::Destroying: 5125 // We've finished constructing the base classes and not yet started 5126 // destroying them again, so this is the dynamic type. 5127 return DynamicType{getBaseClassType(This.Designator, PathLength), 5128 PathLength}; 5129 } 5130 } 5131 5132 // CWG issue 1517: we're constructing a base class of the object described by 5133 // 'This', so that object has not yet begun its period of construction and 5134 // any polymorphic operation on it results in undefined behavior. 5135 Info.FFDiag(E); 5136 return None; 5137 } 5138 5139 /// Perform virtual dispatch. 5140 static const CXXMethodDecl *HandleVirtualDispatch( 5141 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5142 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5143 Optional<DynamicType> DynType = ComputeDynamicType( 5144 Info, E, This, 5145 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5146 if (!DynType) 5147 return nullptr; 5148 5149 // Find the final overrider. It must be declared in one of the classes on the 5150 // path from the dynamic type to the static type. 5151 // FIXME: If we ever allow literal types to have virtual base classes, that 5152 // won't be true. 5153 const CXXMethodDecl *Callee = Found; 5154 unsigned PathLength = DynType->PathLength; 5155 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5156 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5157 const CXXMethodDecl *Overrider = 5158 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5159 if (Overrider) { 5160 Callee = Overrider; 5161 break; 5162 } 5163 } 5164 5165 // C++2a [class.abstract]p6: 5166 // the effect of making a virtual call to a pure virtual function [...] is 5167 // undefined 5168 if (Callee->isPure()) { 5169 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5170 Info.Note(Callee->getLocation(), diag::note_declared_at); 5171 return nullptr; 5172 } 5173 5174 // If necessary, walk the rest of the path to determine the sequence of 5175 // covariant adjustment steps to apply. 5176 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5177 Found->getReturnType())) { 5178 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5179 for (unsigned CovariantPathLength = PathLength + 1; 5180 CovariantPathLength != This.Designator.Entries.size(); 5181 ++CovariantPathLength) { 5182 const CXXRecordDecl *NextClass = 5183 getBaseClassType(This.Designator, CovariantPathLength); 5184 const CXXMethodDecl *Next = 5185 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5186 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5187 Next->getReturnType(), CovariantAdjustmentPath.back())) 5188 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5189 } 5190 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5191 CovariantAdjustmentPath.back())) 5192 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5193 } 5194 5195 // Perform 'this' adjustment. 5196 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5197 return nullptr; 5198 5199 return Callee; 5200 } 5201 5202 /// Perform the adjustment from a value returned by a virtual function to 5203 /// a value of the statically expected type, which may be a pointer or 5204 /// reference to a base class of the returned type. 5205 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5206 APValue &Result, 5207 ArrayRef<QualType> Path) { 5208 assert(Result.isLValue() && 5209 "unexpected kind of APValue for covariant return"); 5210 if (Result.isNullPointer()) 5211 return true; 5212 5213 LValue LVal; 5214 LVal.setFrom(Info.Ctx, Result); 5215 5216 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5217 for (unsigned I = 1; I != Path.size(); ++I) { 5218 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5219 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5220 if (OldClass != NewClass && 5221 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5222 return false; 5223 OldClass = NewClass; 5224 } 5225 5226 LVal.moveInto(Result); 5227 return true; 5228 } 5229 5230 /// Determine whether \p Base, which is known to be a direct base class of 5231 /// \p Derived, is a public base class. 5232 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5233 const CXXRecordDecl *Base) { 5234 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5235 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5236 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5237 return BaseSpec.getAccessSpecifier() == AS_public; 5238 } 5239 llvm_unreachable("Base is not a direct base of Derived"); 5240 } 5241 5242 /// Apply the given dynamic cast operation on the provided lvalue. 5243 /// 5244 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5245 /// to find a suitable target subobject. 5246 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5247 LValue &Ptr) { 5248 // We can't do anything with a non-symbolic pointer value. 5249 SubobjectDesignator &D = Ptr.Designator; 5250 if (D.Invalid) 5251 return false; 5252 5253 // C++ [expr.dynamic.cast]p6: 5254 // If v is a null pointer value, the result is a null pointer value. 5255 if (Ptr.isNullPointer() && !E->isGLValue()) 5256 return true; 5257 5258 // For all the other cases, we need the pointer to point to an object within 5259 // its lifetime / period of construction / destruction, and we need to know 5260 // its dynamic type. 5261 Optional<DynamicType> DynType = 5262 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5263 if (!DynType) 5264 return false; 5265 5266 // C++ [expr.dynamic.cast]p7: 5267 // If T is "pointer to cv void", then the result is a pointer to the most 5268 // derived object 5269 if (E->getType()->isVoidPointerType()) 5270 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5271 5272 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5273 assert(C && "dynamic_cast target is not void pointer nor class"); 5274 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5275 5276 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5277 // C++ [expr.dynamic.cast]p9: 5278 if (!E->isGLValue()) { 5279 // The value of a failed cast to pointer type is the null pointer value 5280 // of the required result type. 5281 Ptr.setNull(Info.Ctx, E->getType()); 5282 return true; 5283 } 5284 5285 // A failed cast to reference type throws [...] std::bad_cast. 5286 unsigned DiagKind; 5287 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5288 DynType->Type->isDerivedFrom(C))) 5289 DiagKind = 0; 5290 else if (!Paths || Paths->begin() == Paths->end()) 5291 DiagKind = 1; 5292 else if (Paths->isAmbiguous(CQT)) 5293 DiagKind = 2; 5294 else { 5295 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5296 DiagKind = 3; 5297 } 5298 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5299 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5300 << Info.Ctx.getRecordType(DynType->Type) 5301 << E->getType().getUnqualifiedType(); 5302 return false; 5303 }; 5304 5305 // Runtime check, phase 1: 5306 // Walk from the base subobject towards the derived object looking for the 5307 // target type. 5308 for (int PathLength = Ptr.Designator.Entries.size(); 5309 PathLength >= (int)DynType->PathLength; --PathLength) { 5310 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5311 if (declaresSameEntity(Class, C)) 5312 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5313 // We can only walk across public inheritance edges. 5314 if (PathLength > (int)DynType->PathLength && 5315 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5316 Class)) 5317 return RuntimeCheckFailed(nullptr); 5318 } 5319 5320 // Runtime check, phase 2: 5321 // Search the dynamic type for an unambiguous public base of type C. 5322 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5323 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5324 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5325 Paths.front().Access == AS_public) { 5326 // Downcast to the dynamic type... 5327 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5328 return false; 5329 // ... then upcast to the chosen base class subobject. 5330 for (CXXBasePathElement &Elem : Paths.front()) 5331 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5332 return false; 5333 return true; 5334 } 5335 5336 // Otherwise, the runtime check fails. 5337 return RuntimeCheckFailed(&Paths); 5338 } 5339 5340 namespace { 5341 struct StartLifetimeOfUnionMemberHandler { 5342 const FieldDecl *Field; 5343 5344 static const AccessKinds AccessKind = AK_Assign; 5345 5346 typedef bool result_type; 5347 bool failed() { return false; } 5348 bool found(APValue &Subobj, QualType SubobjType) { 5349 // We are supposed to perform no initialization but begin the lifetime of 5350 // the object. We interpret that as meaning to do what default 5351 // initialization of the object would do if all constructors involved were 5352 // trivial: 5353 // * All base, non-variant member, and array element subobjects' lifetimes 5354 // begin 5355 // * No variant members' lifetimes begin 5356 // * All scalar subobjects whose lifetimes begin have indeterminate values 5357 assert(SubobjType->isUnionType()); 5358 if (!declaresSameEntity(Subobj.getUnionField(), Field) || 5359 !Subobj.getUnionValue().hasValue()) 5360 Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); 5361 return true; 5362 } 5363 bool found(APSInt &Value, QualType SubobjType) { 5364 llvm_unreachable("wrong value kind for union object"); 5365 } 5366 bool found(APFloat &Value, QualType SubobjType) { 5367 llvm_unreachable("wrong value kind for union object"); 5368 } 5369 }; 5370 } // end anonymous namespace 5371 5372 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5373 5374 /// Handle a builtin simple-assignment or a call to a trivial assignment 5375 /// operator whose left-hand side might involve a union member access. If it 5376 /// does, implicitly start the lifetime of any accessed union elements per 5377 /// C++20 [class.union]5. 5378 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5379 const LValue &LHS) { 5380 if (LHS.InvalidBase || LHS.Designator.Invalid) 5381 return false; 5382 5383 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5384 // C++ [class.union]p5: 5385 // define the set S(E) of subexpressions of E as follows: 5386 unsigned PathLength = LHS.Designator.Entries.size(); 5387 for (const Expr *E = LHSExpr; E != nullptr;) { 5388 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5389 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5390 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5391 // Note that we can't implicitly start the lifetime of a reference, 5392 // so we don't need to proceed any further if we reach one. 5393 if (!FD || FD->getType()->isReferenceType()) 5394 break; 5395 5396 // ... and also contains A.B if B names a union member ... 5397 if (FD->getParent()->isUnion()) { 5398 // ... of a non-class, non-array type, or of a class type with a 5399 // trivial default constructor that is not deleted, or an array of 5400 // such types. 5401 auto *RD = 5402 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5403 if (!RD || RD->hasTrivialDefaultConstructor()) 5404 UnionPathLengths.push_back({PathLength - 1, FD}); 5405 } 5406 5407 E = ME->getBase(); 5408 --PathLength; 5409 assert(declaresSameEntity(FD, 5410 LHS.Designator.Entries[PathLength] 5411 .getAsBaseOrMember().getPointer())); 5412 5413 // -- If E is of the form A[B] and is interpreted as a built-in array 5414 // subscripting operator, S(E) is [S(the array operand, if any)]. 5415 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5416 // Step over an ArrayToPointerDecay implicit cast. 5417 auto *Base = ASE->getBase()->IgnoreImplicit(); 5418 if (!Base->getType()->isArrayType()) 5419 break; 5420 5421 E = Base; 5422 --PathLength; 5423 5424 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5425 // Step over a derived-to-base conversion. 5426 E = ICE->getSubExpr(); 5427 if (ICE->getCastKind() == CK_NoOp) 5428 continue; 5429 if (ICE->getCastKind() != CK_DerivedToBase && 5430 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5431 break; 5432 // Walk path backwards as we walk up from the base to the derived class. 5433 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5434 --PathLength; 5435 (void)Elt; 5436 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5437 LHS.Designator.Entries[PathLength] 5438 .getAsBaseOrMember().getPointer())); 5439 } 5440 5441 // -- Otherwise, S(E) is empty. 5442 } else { 5443 break; 5444 } 5445 } 5446 5447 // Common case: no unions' lifetimes are started. 5448 if (UnionPathLengths.empty()) 5449 return true; 5450 5451 // if modification of X [would access an inactive union member], an object 5452 // of the type of X is implicitly created 5453 CompleteObject Obj = 5454 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5455 if (!Obj) 5456 return false; 5457 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5458 llvm::reverse(UnionPathLengths)) { 5459 // Form a designator for the union object. 5460 SubobjectDesignator D = LHS.Designator; 5461 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5462 5463 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; 5464 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5465 return false; 5466 } 5467 5468 return true; 5469 } 5470 5471 namespace { 5472 typedef SmallVector<APValue, 8> ArgVector; 5473 } 5474 5475 /// EvaluateArgs - Evaluate the arguments to a function call. 5476 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5477 EvalInfo &Info, const FunctionDecl *Callee) { 5478 bool Success = true; 5479 llvm::SmallBitVector ForbiddenNullArgs; 5480 if (Callee->hasAttr<NonNullAttr>()) { 5481 ForbiddenNullArgs.resize(Args.size()); 5482 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5483 if (!Attr->args_size()) { 5484 ForbiddenNullArgs.set(); 5485 break; 5486 } else 5487 for (auto Idx : Attr->args()) { 5488 unsigned ASTIdx = Idx.getASTIndex(); 5489 if (ASTIdx >= Args.size()) 5490 continue; 5491 ForbiddenNullArgs[ASTIdx] = 1; 5492 } 5493 } 5494 } 5495 // FIXME: This is the wrong evaluation order for an assignment operator 5496 // called via operator syntax. 5497 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5498 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5499 // If we're checking for a potential constant expression, evaluate all 5500 // initializers even if some of them fail. 5501 if (!Info.noteFailure()) 5502 return false; 5503 Success = false; 5504 } else if (!ForbiddenNullArgs.empty() && 5505 ForbiddenNullArgs[Idx] && 5506 ArgValues[Idx].isLValue() && 5507 ArgValues[Idx].isNullPointer()) { 5508 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5509 if (!Info.noteFailure()) 5510 return false; 5511 Success = false; 5512 } 5513 } 5514 return Success; 5515 } 5516 5517 /// Evaluate a function call. 5518 static bool HandleFunctionCall(SourceLocation CallLoc, 5519 const FunctionDecl *Callee, const LValue *This, 5520 ArrayRef<const Expr*> Args, const Stmt *Body, 5521 EvalInfo &Info, APValue &Result, 5522 const LValue *ResultSlot) { 5523 ArgVector ArgValues(Args.size()); 5524 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5525 return false; 5526 5527 if (!Info.CheckCallLimit(CallLoc)) 5528 return false; 5529 5530 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5531 5532 // For a trivial copy or move assignment, perform an APValue copy. This is 5533 // essential for unions, where the operations performed by the assignment 5534 // operator cannot be represented as statements. 5535 // 5536 // Skip this for non-union classes with no fields; in that case, the defaulted 5537 // copy/move does not actually read the object. 5538 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5539 if (MD && MD->isDefaulted() && 5540 (MD->getParent()->isUnion() || 5541 (MD->isTrivial() && 5542 isReadByLvalueToRvalueConversion(MD->getParent())))) { 5543 assert(This && 5544 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5545 LValue RHS; 5546 RHS.setFrom(Info.Ctx, ArgValues[0]); 5547 APValue RHSValue; 5548 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5549 RHSValue, MD->getParent()->isUnion())) 5550 return false; 5551 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && 5552 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5553 return false; 5554 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5555 RHSValue)) 5556 return false; 5557 This->moveInto(Result); 5558 return true; 5559 } else if (MD && isLambdaCallOperator(MD)) { 5560 // We're in a lambda; determine the lambda capture field maps unless we're 5561 // just constexpr checking a lambda's call operator. constexpr checking is 5562 // done before the captures have been added to the closure object (unless 5563 // we're inferring constexpr-ness), so we don't have access to them in this 5564 // case. But since we don't need the captures to constexpr check, we can 5565 // just ignore them. 5566 if (!Info.checkingPotentialConstantExpression()) 5567 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5568 Frame.LambdaThisCaptureField); 5569 } 5570 5571 StmtResult Ret = {Result, ResultSlot}; 5572 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5573 if (ESR == ESR_Succeeded) { 5574 if (Callee->getReturnType()->isVoidType()) 5575 return true; 5576 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5577 } 5578 return ESR == ESR_Returned; 5579 } 5580 5581 /// Evaluate a constructor call. 5582 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5583 APValue *ArgValues, 5584 const CXXConstructorDecl *Definition, 5585 EvalInfo &Info, APValue &Result) { 5586 SourceLocation CallLoc = E->getExprLoc(); 5587 if (!Info.CheckCallLimit(CallLoc)) 5588 return false; 5589 5590 const CXXRecordDecl *RD = Definition->getParent(); 5591 if (RD->getNumVBases()) { 5592 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5593 return false; 5594 } 5595 5596 EvalInfo::EvaluatingConstructorRAII EvalObj( 5597 Info, 5598 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5599 RD->getNumBases()); 5600 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5601 5602 // FIXME: Creating an APValue just to hold a nonexistent return value is 5603 // wasteful. 5604 APValue RetVal; 5605 StmtResult Ret = {RetVal, nullptr}; 5606 5607 // If it's a delegating constructor, delegate. 5608 if (Definition->isDelegatingConstructor()) { 5609 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5610 { 5611 FullExpressionRAII InitScope(Info); 5612 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5613 !InitScope.destroy()) 5614 return false; 5615 } 5616 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5617 } 5618 5619 // For a trivial copy or move constructor, perform an APValue copy. This is 5620 // essential for unions (or classes with anonymous union members), where the 5621 // operations performed by the constructor cannot be represented by 5622 // ctor-initializers. 5623 // 5624 // Skip this for empty non-union classes; we should not perform an 5625 // lvalue-to-rvalue conversion on them because their copy constructor does not 5626 // actually read them. 5627 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5628 (Definition->getParent()->isUnion() || 5629 (Definition->isTrivial() && 5630 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 5631 LValue RHS; 5632 RHS.setFrom(Info.Ctx, ArgValues[0]); 5633 return handleLValueToRValueConversion( 5634 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5635 RHS, Result, Definition->getParent()->isUnion()); 5636 } 5637 5638 // Reserve space for the struct members. 5639 if (!Result.hasValue()) { 5640 if (!RD->isUnion()) 5641 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5642 std::distance(RD->field_begin(), RD->field_end())); 5643 else 5644 // A union starts with no active member. 5645 Result = APValue((const FieldDecl*)nullptr); 5646 } 5647 5648 if (RD->isInvalidDecl()) return false; 5649 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5650 5651 // A scope for temporaries lifetime-extended by reference members. 5652 BlockScopeRAII LifetimeExtendedScope(Info); 5653 5654 bool Success = true; 5655 unsigned BasesSeen = 0; 5656 #ifndef NDEBUG 5657 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5658 #endif 5659 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5660 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5661 // We might be initializing the same field again if this is an indirect 5662 // field initialization. 5663 if (FieldIt == RD->field_end() || 5664 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5665 assert(Indirect && "fields out of order?"); 5666 return; 5667 } 5668 5669 // Default-initialize any fields with no explicit initializer. 5670 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5671 assert(FieldIt != RD->field_end() && "missing field?"); 5672 if (!FieldIt->isUnnamedBitfield()) 5673 Result.getStructField(FieldIt->getFieldIndex()) = 5674 getDefaultInitValue(FieldIt->getType()); 5675 } 5676 ++FieldIt; 5677 }; 5678 for (const auto *I : Definition->inits()) { 5679 LValue Subobject = This; 5680 LValue SubobjectParent = This; 5681 APValue *Value = &Result; 5682 5683 // Determine the subobject to initialize. 5684 FieldDecl *FD = nullptr; 5685 if (I->isBaseInitializer()) { 5686 QualType BaseType(I->getBaseClass(), 0); 5687 #ifndef NDEBUG 5688 // Non-virtual base classes are initialized in the order in the class 5689 // definition. We have already checked for virtual base classes. 5690 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5691 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5692 "base class initializers not in expected order"); 5693 ++BaseIt; 5694 #endif 5695 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5696 BaseType->getAsCXXRecordDecl(), &Layout)) 5697 return false; 5698 Value = &Result.getStructBase(BasesSeen++); 5699 } else if ((FD = I->getMember())) { 5700 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5701 return false; 5702 if (RD->isUnion()) { 5703 Result = APValue(FD); 5704 Value = &Result.getUnionValue(); 5705 } else { 5706 SkipToField(FD, false); 5707 Value = &Result.getStructField(FD->getFieldIndex()); 5708 } 5709 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5710 // Walk the indirect field decl's chain to find the object to initialize, 5711 // and make sure we've initialized every step along it. 5712 auto IndirectFieldChain = IFD->chain(); 5713 for (auto *C : IndirectFieldChain) { 5714 FD = cast<FieldDecl>(C); 5715 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5716 // Switch the union field if it differs. This happens if we had 5717 // preceding zero-initialization, and we're now initializing a union 5718 // subobject other than the first. 5719 // FIXME: In this case, the values of the other subobjects are 5720 // specified, since zero-initialization sets all padding bits to zero. 5721 if (!Value->hasValue() || 5722 (Value->isUnion() && Value->getUnionField() != FD)) { 5723 if (CD->isUnion()) 5724 *Value = APValue(FD); 5725 else 5726 // FIXME: This immediately starts the lifetime of all members of an 5727 // anonymous struct. It would be preferable to strictly start member 5728 // lifetime in initialization order. 5729 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD)); 5730 } 5731 // Store Subobject as its parent before updating it for the last element 5732 // in the chain. 5733 if (C == IndirectFieldChain.back()) 5734 SubobjectParent = Subobject; 5735 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 5736 return false; 5737 if (CD->isUnion()) 5738 Value = &Value->getUnionValue(); 5739 else { 5740 if (C == IndirectFieldChain.front() && !RD->isUnion()) 5741 SkipToField(FD, true); 5742 Value = &Value->getStructField(FD->getFieldIndex()); 5743 } 5744 } 5745 } else { 5746 llvm_unreachable("unknown base initializer kind"); 5747 } 5748 5749 // Need to override This for implicit field initializers as in this case 5750 // This refers to innermost anonymous struct/union containing initializer, 5751 // not to currently constructed class. 5752 const Expr *Init = I->getInit(); 5753 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 5754 isa<CXXDefaultInitExpr>(Init)); 5755 FullExpressionRAII InitScope(Info); 5756 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 5757 (FD && FD->isBitField() && 5758 !truncateBitfieldValue(Info, Init, *Value, FD))) { 5759 // If we're checking for a potential constant expression, evaluate all 5760 // initializers even if some of them fail. 5761 if (!Info.noteFailure()) 5762 return false; 5763 Success = false; 5764 } 5765 5766 // This is the point at which the dynamic type of the object becomes this 5767 // class type. 5768 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 5769 EvalObj.finishedConstructingBases(); 5770 } 5771 5772 // Default-initialize any remaining fields. 5773 if (!RD->isUnion()) { 5774 for (; FieldIt != RD->field_end(); ++FieldIt) { 5775 if (!FieldIt->isUnnamedBitfield()) 5776 Result.getStructField(FieldIt->getFieldIndex()) = 5777 getDefaultInitValue(FieldIt->getType()); 5778 } 5779 } 5780 5781 return Success && 5782 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 5783 LifetimeExtendedScope.destroy(); 5784 } 5785 5786 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5787 ArrayRef<const Expr*> Args, 5788 const CXXConstructorDecl *Definition, 5789 EvalInfo &Info, APValue &Result) { 5790 ArgVector ArgValues(Args.size()); 5791 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 5792 return false; 5793 5794 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 5795 Info, Result); 5796 } 5797 5798 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 5799 const LValue &This, APValue &Value, 5800 QualType T) { 5801 // Objects can only be destroyed while they're within their lifetimes. 5802 // FIXME: We have no representation for whether an object of type nullptr_t 5803 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 5804 // as indeterminate instead? 5805 if (Value.isAbsent() && !T->isNullPtrType()) { 5806 APValue Printable; 5807 This.moveInto(Printable); 5808 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 5809 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 5810 return false; 5811 } 5812 5813 // Invent an expression for location purposes. 5814 // FIXME: We shouldn't need to do this. 5815 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 5816 5817 // For arrays, destroy elements right-to-left. 5818 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 5819 uint64_t Size = CAT->getSize().getZExtValue(); 5820 QualType ElemT = CAT->getElementType(); 5821 5822 LValue ElemLV = This; 5823 ElemLV.addArray(Info, &LocE, CAT); 5824 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 5825 return false; 5826 5827 // Ensure that we have actual array elements available to destroy; the 5828 // destructors might mutate the value, so we can't run them on the array 5829 // filler. 5830 if (Size && Size > Value.getArrayInitializedElts()) 5831 expandArray(Value, Value.getArraySize() - 1); 5832 5833 for (; Size != 0; --Size) { 5834 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 5835 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 5836 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 5837 return false; 5838 } 5839 5840 // End the lifetime of this array now. 5841 Value = APValue(); 5842 return true; 5843 } 5844 5845 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5846 if (!RD) { 5847 if (T.isDestructedType()) { 5848 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 5849 return false; 5850 } 5851 5852 Value = APValue(); 5853 return true; 5854 } 5855 5856 if (RD->getNumVBases()) { 5857 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5858 return false; 5859 } 5860 5861 const CXXDestructorDecl *DD = RD->getDestructor(); 5862 if (!DD && !RD->hasTrivialDestructor()) { 5863 Info.FFDiag(CallLoc); 5864 return false; 5865 } 5866 5867 if (!DD || DD->isTrivial() || 5868 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 5869 // A trivial destructor just ends the lifetime of the object. Check for 5870 // this case before checking for a body, because we might not bother 5871 // building a body for a trivial destructor. Note that it doesn't matter 5872 // whether the destructor is constexpr in this case; all trivial 5873 // destructors are constexpr. 5874 // 5875 // If an anonymous union would be destroyed, some enclosing destructor must 5876 // have been explicitly defined, and the anonymous union destruction should 5877 // have no effect. 5878 Value = APValue(); 5879 return true; 5880 } 5881 5882 if (!Info.CheckCallLimit(CallLoc)) 5883 return false; 5884 5885 const FunctionDecl *Definition = nullptr; 5886 const Stmt *Body = DD->getBody(Definition); 5887 5888 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 5889 return false; 5890 5891 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 5892 5893 // We're now in the period of destruction of this object. 5894 unsigned BasesLeft = RD->getNumBases(); 5895 EvalInfo::EvaluatingDestructorRAII EvalObj( 5896 Info, 5897 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 5898 if (!EvalObj.DidInsert) { 5899 // C++2a [class.dtor]p19: 5900 // the behavior is undefined if the destructor is invoked for an object 5901 // whose lifetime has ended 5902 // (Note that formally the lifetime ends when the period of destruction 5903 // begins, even though certain uses of the object remain valid until the 5904 // period of destruction ends.) 5905 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 5906 return false; 5907 } 5908 5909 // FIXME: Creating an APValue just to hold a nonexistent return value is 5910 // wasteful. 5911 APValue RetVal; 5912 StmtResult Ret = {RetVal, nullptr}; 5913 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 5914 return false; 5915 5916 // A union destructor does not implicitly destroy its members. 5917 if (RD->isUnion()) 5918 return true; 5919 5920 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5921 5922 // We don't have a good way to iterate fields in reverse, so collect all the 5923 // fields first and then walk them backwards. 5924 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 5925 for (const FieldDecl *FD : llvm::reverse(Fields)) { 5926 if (FD->isUnnamedBitfield()) 5927 continue; 5928 5929 LValue Subobject = This; 5930 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 5931 return false; 5932 5933 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 5934 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 5935 FD->getType())) 5936 return false; 5937 } 5938 5939 if (BasesLeft != 0) 5940 EvalObj.startedDestroyingBases(); 5941 5942 // Destroy base classes in reverse order. 5943 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 5944 --BasesLeft; 5945 5946 QualType BaseType = Base.getType(); 5947 LValue Subobject = This; 5948 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 5949 BaseType->getAsCXXRecordDecl(), &Layout)) 5950 return false; 5951 5952 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 5953 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 5954 BaseType)) 5955 return false; 5956 } 5957 assert(BasesLeft == 0 && "NumBases was wrong?"); 5958 5959 // The period of destruction ends now. The object is gone. 5960 Value = APValue(); 5961 return true; 5962 } 5963 5964 namespace { 5965 struct DestroyObjectHandler { 5966 EvalInfo &Info; 5967 const Expr *E; 5968 const LValue &This; 5969 const AccessKinds AccessKind; 5970 5971 typedef bool result_type; 5972 bool failed() { return false; } 5973 bool found(APValue &Subobj, QualType SubobjType) { 5974 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 5975 SubobjType); 5976 } 5977 bool found(APSInt &Value, QualType SubobjType) { 5978 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 5979 return false; 5980 } 5981 bool found(APFloat &Value, QualType SubobjType) { 5982 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 5983 return false; 5984 } 5985 }; 5986 } 5987 5988 /// Perform a destructor or pseudo-destructor call on the given object, which 5989 /// might in general not be a complete object. 5990 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 5991 const LValue &This, QualType ThisType) { 5992 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 5993 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 5994 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5995 } 5996 5997 /// Destroy and end the lifetime of the given complete object. 5998 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 5999 APValue::LValueBase LVBase, APValue &Value, 6000 QualType T) { 6001 // If we've had an unmodeled side-effect, we can't rely on mutable state 6002 // (such as the object we're about to destroy) being correct. 6003 if (Info.EvalStatus.HasSideEffects) 6004 return false; 6005 6006 LValue LV; 6007 LV.set({LVBase}); 6008 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6009 } 6010 6011 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6012 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6013 LValue &Result) { 6014 if (Info.checkingPotentialConstantExpression() || 6015 Info.SpeculativeEvaluationDepth) 6016 return false; 6017 6018 // This is permitted only within a call to std::allocator<T>::allocate. 6019 auto Caller = Info.getStdAllocatorCaller("allocate"); 6020 if (!Caller) { 6021 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a 6022 ? diag::note_constexpr_new_untyped 6023 : diag::note_constexpr_new); 6024 return false; 6025 } 6026 6027 QualType ElemType = Caller.ElemType; 6028 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6029 Info.FFDiag(E->getExprLoc(), 6030 diag::note_constexpr_new_not_complete_object_type) 6031 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6032 return false; 6033 } 6034 6035 APSInt ByteSize; 6036 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6037 return false; 6038 bool IsNothrow = false; 6039 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6040 EvaluateIgnoredValue(Info, E->getArg(I)); 6041 IsNothrow |= E->getType()->isNothrowT(); 6042 } 6043 6044 CharUnits ElemSize; 6045 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6046 return false; 6047 APInt Size, Remainder; 6048 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6049 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6050 if (Remainder != 0) { 6051 // This likely indicates a bug in the implementation of 'std::allocator'. 6052 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6053 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6054 return false; 6055 } 6056 6057 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6058 if (IsNothrow) { 6059 Result.setNull(Info.Ctx, E->getType()); 6060 return true; 6061 } 6062 6063 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6064 return false; 6065 } 6066 6067 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6068 ArrayType::Normal, 0); 6069 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6070 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6071 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6072 return true; 6073 } 6074 6075 static bool hasVirtualDestructor(QualType T) { 6076 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6077 if (CXXDestructorDecl *DD = RD->getDestructor()) 6078 return DD->isVirtual(); 6079 return false; 6080 } 6081 6082 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6083 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6084 if (CXXDestructorDecl *DD = RD->getDestructor()) 6085 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6086 return nullptr; 6087 } 6088 6089 /// Check that the given object is a suitable pointer to a heap allocation that 6090 /// still exists and is of the right kind for the purpose of a deletion. 6091 /// 6092 /// On success, returns the heap allocation to deallocate. On failure, produces 6093 /// a diagnostic and returns None. 6094 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6095 const LValue &Pointer, 6096 DynAlloc::Kind DeallocKind) { 6097 auto PointerAsString = [&] { 6098 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6099 }; 6100 6101 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6102 if (!DA) { 6103 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6104 << PointerAsString(); 6105 if (Pointer.Base) 6106 NoteLValueLocation(Info, Pointer.Base); 6107 return None; 6108 } 6109 6110 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6111 if (!Alloc) { 6112 Info.FFDiag(E, diag::note_constexpr_double_delete); 6113 return None; 6114 } 6115 6116 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6117 if (DeallocKind != (*Alloc)->getKind()) { 6118 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6119 << DeallocKind << (*Alloc)->getKind() << AllocType; 6120 NoteLValueLocation(Info, Pointer.Base); 6121 return None; 6122 } 6123 6124 bool Subobject = false; 6125 if (DeallocKind == DynAlloc::New) { 6126 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6127 Pointer.Designator.isOnePastTheEnd(); 6128 } else { 6129 Subobject = Pointer.Designator.Entries.size() != 1 || 6130 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6131 } 6132 if (Subobject) { 6133 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6134 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6135 return None; 6136 } 6137 6138 return Alloc; 6139 } 6140 6141 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6142 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6143 if (Info.checkingPotentialConstantExpression() || 6144 Info.SpeculativeEvaluationDepth) 6145 return false; 6146 6147 // This is permitted only within a call to std::allocator<T>::deallocate. 6148 if (!Info.getStdAllocatorCaller("deallocate")) { 6149 Info.FFDiag(E->getExprLoc()); 6150 return true; 6151 } 6152 6153 LValue Pointer; 6154 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6155 return false; 6156 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6157 EvaluateIgnoredValue(Info, E->getArg(I)); 6158 6159 if (Pointer.Designator.Invalid) 6160 return false; 6161 6162 // Deleting a null pointer has no effect. 6163 if (Pointer.isNullPointer()) 6164 return true; 6165 6166 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6167 return false; 6168 6169 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6170 return true; 6171 } 6172 6173 //===----------------------------------------------------------------------===// 6174 // Generic Evaluation 6175 //===----------------------------------------------------------------------===// 6176 namespace { 6177 6178 class BitCastBuffer { 6179 // FIXME: We're going to need bit-level granularity when we support 6180 // bit-fields. 6181 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6182 // we don't support a host or target where that is the case. Still, we should 6183 // use a more generic type in case we ever do. 6184 SmallVector<Optional<unsigned char>, 32> Bytes; 6185 6186 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6187 "Need at least 8 bit unsigned char"); 6188 6189 bool TargetIsLittleEndian; 6190 6191 public: 6192 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6193 : Bytes(Width.getQuantity()), 6194 TargetIsLittleEndian(TargetIsLittleEndian) {} 6195 6196 LLVM_NODISCARD 6197 bool readObject(CharUnits Offset, CharUnits Width, 6198 SmallVectorImpl<unsigned char> &Output) const { 6199 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6200 // If a byte of an integer is uninitialized, then the whole integer is 6201 // uninitalized. 6202 if (!Bytes[I.getQuantity()]) 6203 return false; 6204 Output.push_back(*Bytes[I.getQuantity()]); 6205 } 6206 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6207 std::reverse(Output.begin(), Output.end()); 6208 return true; 6209 } 6210 6211 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6212 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6213 std::reverse(Input.begin(), Input.end()); 6214 6215 size_t Index = 0; 6216 for (unsigned char Byte : Input) { 6217 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6218 Bytes[Offset.getQuantity() + Index] = Byte; 6219 ++Index; 6220 } 6221 } 6222 6223 size_t size() { return Bytes.size(); } 6224 }; 6225 6226 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6227 /// target would represent the value at runtime. 6228 class APValueToBufferConverter { 6229 EvalInfo &Info; 6230 BitCastBuffer Buffer; 6231 const CastExpr *BCE; 6232 6233 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6234 const CastExpr *BCE) 6235 : Info(Info), 6236 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6237 BCE(BCE) {} 6238 6239 bool visit(const APValue &Val, QualType Ty) { 6240 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6241 } 6242 6243 // Write out Val with type Ty into Buffer starting at Offset. 6244 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6245 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6246 6247 // As a special case, nullptr_t has an indeterminate value. 6248 if (Ty->isNullPtrType()) 6249 return true; 6250 6251 // Dig through Src to find the byte at SrcOffset. 6252 switch (Val.getKind()) { 6253 case APValue::Indeterminate: 6254 case APValue::None: 6255 return true; 6256 6257 case APValue::Int: 6258 return visitInt(Val.getInt(), Ty, Offset); 6259 case APValue::Float: 6260 return visitFloat(Val.getFloat(), Ty, Offset); 6261 case APValue::Array: 6262 return visitArray(Val, Ty, Offset); 6263 case APValue::Struct: 6264 return visitRecord(Val, Ty, Offset); 6265 6266 case APValue::ComplexInt: 6267 case APValue::ComplexFloat: 6268 case APValue::Vector: 6269 case APValue::FixedPoint: 6270 // FIXME: We should support these. 6271 6272 case APValue::Union: 6273 case APValue::MemberPointer: 6274 case APValue::AddrLabelDiff: { 6275 Info.FFDiag(BCE->getBeginLoc(), 6276 diag::note_constexpr_bit_cast_unsupported_type) 6277 << Ty; 6278 return false; 6279 } 6280 6281 case APValue::LValue: 6282 llvm_unreachable("LValue subobject in bit_cast?"); 6283 } 6284 llvm_unreachable("Unhandled APValue::ValueKind"); 6285 } 6286 6287 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6288 const RecordDecl *RD = Ty->getAsRecordDecl(); 6289 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6290 6291 // Visit the base classes. 6292 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6293 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6294 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6295 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6296 6297 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6298 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6299 return false; 6300 } 6301 } 6302 6303 // Visit the fields. 6304 unsigned FieldIdx = 0; 6305 for (FieldDecl *FD : RD->fields()) { 6306 if (FD->isBitField()) { 6307 Info.FFDiag(BCE->getBeginLoc(), 6308 diag::note_constexpr_bit_cast_unsupported_bitfield); 6309 return false; 6310 } 6311 6312 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6313 6314 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6315 "only bit-fields can have sub-char alignment"); 6316 CharUnits FieldOffset = 6317 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6318 QualType FieldTy = FD->getType(); 6319 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6320 return false; 6321 ++FieldIdx; 6322 } 6323 6324 return true; 6325 } 6326 6327 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6328 const auto *CAT = 6329 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6330 if (!CAT) 6331 return false; 6332 6333 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6334 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6335 unsigned ArraySize = Val.getArraySize(); 6336 // First, initialize the initialized elements. 6337 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6338 const APValue &SubObj = Val.getArrayInitializedElt(I); 6339 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6340 return false; 6341 } 6342 6343 // Next, initialize the rest of the array using the filler. 6344 if (Val.hasArrayFiller()) { 6345 const APValue &Filler = Val.getArrayFiller(); 6346 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6347 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6348 return false; 6349 } 6350 } 6351 6352 return true; 6353 } 6354 6355 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6356 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 6357 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 6358 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 6359 Buffer.writeObject(Offset, Bytes); 6360 return true; 6361 } 6362 6363 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6364 APSInt AsInt(Val.bitcastToAPInt()); 6365 return visitInt(AsInt, Ty, Offset); 6366 } 6367 6368 public: 6369 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6370 const CastExpr *BCE) { 6371 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6372 APValueToBufferConverter Converter(Info, DstSize, BCE); 6373 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6374 return None; 6375 return Converter.Buffer; 6376 } 6377 }; 6378 6379 /// Write an BitCastBuffer into an APValue. 6380 class BufferToAPValueConverter { 6381 EvalInfo &Info; 6382 const BitCastBuffer &Buffer; 6383 const CastExpr *BCE; 6384 6385 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6386 const CastExpr *BCE) 6387 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6388 6389 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6390 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6391 // Ideally this will be unreachable. 6392 llvm::NoneType unsupportedType(QualType Ty) { 6393 Info.FFDiag(BCE->getBeginLoc(), 6394 diag::note_constexpr_bit_cast_unsupported_type) 6395 << Ty; 6396 return None; 6397 } 6398 6399 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6400 const EnumType *EnumSugar = nullptr) { 6401 if (T->isNullPtrType()) { 6402 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6403 return APValue((Expr *)nullptr, 6404 /*Offset=*/CharUnits::fromQuantity(NullValue), 6405 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6406 } 6407 6408 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6409 SmallVector<uint8_t, 8> Bytes; 6410 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6411 // If this is std::byte or unsigned char, then its okay to store an 6412 // indeterminate value. 6413 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6414 bool IsUChar = 6415 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6416 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6417 if (!IsStdByte && !IsUChar) { 6418 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6419 Info.FFDiag(BCE->getExprLoc(), 6420 diag::note_constexpr_bit_cast_indet_dest) 6421 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6422 return None; 6423 } 6424 6425 return APValue::IndeterminateValue(); 6426 } 6427 6428 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6429 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6430 6431 if (T->isIntegralOrEnumerationType()) { 6432 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6433 return APValue(Val); 6434 } 6435 6436 if (T->isRealFloatingType()) { 6437 const llvm::fltSemantics &Semantics = 6438 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6439 return APValue(APFloat(Semantics, Val)); 6440 } 6441 6442 return unsupportedType(QualType(T, 0)); 6443 } 6444 6445 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6446 const RecordDecl *RD = RTy->getAsRecordDecl(); 6447 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6448 6449 unsigned NumBases = 0; 6450 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6451 NumBases = CXXRD->getNumBases(); 6452 6453 APValue ResultVal(APValue::UninitStruct(), NumBases, 6454 std::distance(RD->field_begin(), RD->field_end())); 6455 6456 // Visit the base classes. 6457 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6458 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6459 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6460 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6461 if (BaseDecl->isEmpty() || 6462 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6463 continue; 6464 6465 Optional<APValue> SubObj = visitType( 6466 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6467 if (!SubObj) 6468 return None; 6469 ResultVal.getStructBase(I) = *SubObj; 6470 } 6471 } 6472 6473 // Visit the fields. 6474 unsigned FieldIdx = 0; 6475 for (FieldDecl *FD : RD->fields()) { 6476 // FIXME: We don't currently support bit-fields. A lot of the logic for 6477 // this is in CodeGen, so we need to factor it around. 6478 if (FD->isBitField()) { 6479 Info.FFDiag(BCE->getBeginLoc(), 6480 diag::note_constexpr_bit_cast_unsupported_bitfield); 6481 return None; 6482 } 6483 6484 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6485 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6486 6487 CharUnits FieldOffset = 6488 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6489 Offset; 6490 QualType FieldTy = FD->getType(); 6491 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6492 if (!SubObj) 6493 return None; 6494 ResultVal.getStructField(FieldIdx) = *SubObj; 6495 ++FieldIdx; 6496 } 6497 6498 return ResultVal; 6499 } 6500 6501 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6502 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6503 assert(!RepresentationType.isNull() && 6504 "enum forward decl should be caught by Sema"); 6505 const auto *AsBuiltin = 6506 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6507 // Recurse into the underlying type. Treat std::byte transparently as 6508 // unsigned char. 6509 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6510 } 6511 6512 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6513 size_t Size = Ty->getSize().getLimitedValue(); 6514 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6515 6516 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6517 for (size_t I = 0; I != Size; ++I) { 6518 Optional<APValue> ElementValue = 6519 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6520 if (!ElementValue) 6521 return None; 6522 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6523 } 6524 6525 return ArrayValue; 6526 } 6527 6528 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6529 return unsupportedType(QualType(Ty, 0)); 6530 } 6531 6532 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6533 QualType Can = Ty.getCanonicalType(); 6534 6535 switch (Can->getTypeClass()) { 6536 #define TYPE(Class, Base) \ 6537 case Type::Class: \ 6538 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6539 #define ABSTRACT_TYPE(Class, Base) 6540 #define NON_CANONICAL_TYPE(Class, Base) \ 6541 case Type::Class: \ 6542 llvm_unreachable("non-canonical type should be impossible!"); 6543 #define DEPENDENT_TYPE(Class, Base) \ 6544 case Type::Class: \ 6545 llvm_unreachable( \ 6546 "dependent types aren't supported in the constant evaluator!"); 6547 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6548 case Type::Class: \ 6549 llvm_unreachable("either dependent or not canonical!"); 6550 #include "clang/AST/TypeNodes.inc" 6551 } 6552 llvm_unreachable("Unhandled Type::TypeClass"); 6553 } 6554 6555 public: 6556 // Pull out a full value of type DstType. 6557 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6558 const CastExpr *BCE) { 6559 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6560 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6561 } 6562 }; 6563 6564 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6565 QualType Ty, EvalInfo *Info, 6566 const ASTContext &Ctx, 6567 bool CheckingDest) { 6568 Ty = Ty.getCanonicalType(); 6569 6570 auto diag = [&](int Reason) { 6571 if (Info) 6572 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6573 << CheckingDest << (Reason == 4) << Reason; 6574 return false; 6575 }; 6576 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6577 if (Info) 6578 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6579 << NoteTy << Construct << Ty; 6580 return false; 6581 }; 6582 6583 if (Ty->isUnionType()) 6584 return diag(0); 6585 if (Ty->isPointerType()) 6586 return diag(1); 6587 if (Ty->isMemberPointerType()) 6588 return diag(2); 6589 if (Ty.isVolatileQualified()) 6590 return diag(3); 6591 6592 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6593 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6594 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6595 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6596 CheckingDest)) 6597 return note(1, BS.getType(), BS.getBeginLoc()); 6598 } 6599 for (FieldDecl *FD : Record->fields()) { 6600 if (FD->getType()->isReferenceType()) 6601 return diag(4); 6602 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6603 CheckingDest)) 6604 return note(0, FD->getType(), FD->getBeginLoc()); 6605 } 6606 } 6607 6608 if (Ty->isArrayType() && 6609 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6610 Info, Ctx, CheckingDest)) 6611 return false; 6612 6613 return true; 6614 } 6615 6616 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6617 const ASTContext &Ctx, 6618 const CastExpr *BCE) { 6619 bool DestOK = checkBitCastConstexprEligibilityType( 6620 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6621 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6622 BCE->getBeginLoc(), 6623 BCE->getSubExpr()->getType(), Info, Ctx, false); 6624 return SourceOK; 6625 } 6626 6627 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6628 APValue &SourceValue, 6629 const CastExpr *BCE) { 6630 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6631 "no host or target supports non 8-bit chars"); 6632 assert(SourceValue.isLValue() && 6633 "LValueToRValueBitcast requires an lvalue operand!"); 6634 6635 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6636 return false; 6637 6638 LValue SourceLValue; 6639 APValue SourceRValue; 6640 SourceLValue.setFrom(Info.Ctx, SourceValue); 6641 if (!handleLValueToRValueConversion( 6642 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 6643 SourceRValue, /*WantObjectRepresentation=*/true)) 6644 return false; 6645 6646 // Read out SourceValue into a char buffer. 6647 Optional<BitCastBuffer> Buffer = 6648 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 6649 if (!Buffer) 6650 return false; 6651 6652 // Write out the buffer into a new APValue. 6653 Optional<APValue> MaybeDestValue = 6654 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 6655 if (!MaybeDestValue) 6656 return false; 6657 6658 DestValue = std::move(*MaybeDestValue); 6659 return true; 6660 } 6661 6662 template <class Derived> 6663 class ExprEvaluatorBase 6664 : public ConstStmtVisitor<Derived, bool> { 6665 private: 6666 Derived &getDerived() { return static_cast<Derived&>(*this); } 6667 bool DerivedSuccess(const APValue &V, const Expr *E) { 6668 return getDerived().Success(V, E); 6669 } 6670 bool DerivedZeroInitialization(const Expr *E) { 6671 return getDerived().ZeroInitialization(E); 6672 } 6673 6674 // Check whether a conditional operator with a non-constant condition is a 6675 // potential constant expression. If neither arm is a potential constant 6676 // expression, then the conditional operator is not either. 6677 template<typename ConditionalOperator> 6678 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 6679 assert(Info.checkingPotentialConstantExpression()); 6680 6681 // Speculatively evaluate both arms. 6682 SmallVector<PartialDiagnosticAt, 8> Diag; 6683 { 6684 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6685 StmtVisitorTy::Visit(E->getFalseExpr()); 6686 if (Diag.empty()) 6687 return; 6688 } 6689 6690 { 6691 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6692 Diag.clear(); 6693 StmtVisitorTy::Visit(E->getTrueExpr()); 6694 if (Diag.empty()) 6695 return; 6696 } 6697 6698 Error(E, diag::note_constexpr_conditional_never_const); 6699 } 6700 6701 6702 template<typename ConditionalOperator> 6703 bool HandleConditionalOperator(const ConditionalOperator *E) { 6704 bool BoolResult; 6705 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 6706 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 6707 CheckPotentialConstantConditional(E); 6708 return false; 6709 } 6710 if (Info.noteFailure()) { 6711 StmtVisitorTy::Visit(E->getTrueExpr()); 6712 StmtVisitorTy::Visit(E->getFalseExpr()); 6713 } 6714 return false; 6715 } 6716 6717 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 6718 return StmtVisitorTy::Visit(EvalExpr); 6719 } 6720 6721 protected: 6722 EvalInfo &Info; 6723 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 6724 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 6725 6726 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 6727 return Info.CCEDiag(E, D); 6728 } 6729 6730 bool ZeroInitialization(const Expr *E) { return Error(E); } 6731 6732 public: 6733 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 6734 6735 EvalInfo &getEvalInfo() { return Info; } 6736 6737 /// Report an evaluation error. This should only be called when an error is 6738 /// first discovered. When propagating an error, just return false. 6739 bool Error(const Expr *E, diag::kind D) { 6740 Info.FFDiag(E, D); 6741 return false; 6742 } 6743 bool Error(const Expr *E) { 6744 return Error(E, diag::note_invalid_subexpr_in_const_expr); 6745 } 6746 6747 bool VisitStmt(const Stmt *) { 6748 llvm_unreachable("Expression evaluator should not be called on stmts"); 6749 } 6750 bool VisitExpr(const Expr *E) { 6751 return Error(E); 6752 } 6753 6754 bool VisitConstantExpr(const ConstantExpr *E) 6755 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6756 bool VisitParenExpr(const ParenExpr *E) 6757 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6758 bool VisitUnaryExtension(const UnaryOperator *E) 6759 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6760 bool VisitUnaryPlus(const UnaryOperator *E) 6761 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6762 bool VisitChooseExpr(const ChooseExpr *E) 6763 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 6764 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 6765 { return StmtVisitorTy::Visit(E->getResultExpr()); } 6766 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 6767 { return StmtVisitorTy::Visit(E->getReplacement()); } 6768 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 6769 TempVersionRAII RAII(*Info.CurrentCall); 6770 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 6771 return StmtVisitorTy::Visit(E->getExpr()); 6772 } 6773 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 6774 TempVersionRAII RAII(*Info.CurrentCall); 6775 // The initializer may not have been parsed yet, or might be erroneous. 6776 if (!E->getExpr()) 6777 return Error(E); 6778 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 6779 return StmtVisitorTy::Visit(E->getExpr()); 6780 } 6781 6782 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 6783 FullExpressionRAII Scope(Info); 6784 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 6785 } 6786 6787 // Temporaries are registered when created, so we don't care about 6788 // CXXBindTemporaryExpr. 6789 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 6790 return StmtVisitorTy::Visit(E->getSubExpr()); 6791 } 6792 6793 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 6794 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 6795 return static_cast<Derived*>(this)->VisitCastExpr(E); 6796 } 6797 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 6798 if (!Info.Ctx.getLangOpts().CPlusPlus2a) 6799 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 6800 return static_cast<Derived*>(this)->VisitCastExpr(E); 6801 } 6802 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 6803 return static_cast<Derived*>(this)->VisitCastExpr(E); 6804 } 6805 6806 bool VisitBinaryOperator(const BinaryOperator *E) { 6807 switch (E->getOpcode()) { 6808 default: 6809 return Error(E); 6810 6811 case BO_Comma: 6812 VisitIgnoredValue(E->getLHS()); 6813 return StmtVisitorTy::Visit(E->getRHS()); 6814 6815 case BO_PtrMemD: 6816 case BO_PtrMemI: { 6817 LValue Obj; 6818 if (!HandleMemberPointerAccess(Info, E, Obj)) 6819 return false; 6820 APValue Result; 6821 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 6822 return false; 6823 return DerivedSuccess(Result, E); 6824 } 6825 } 6826 } 6827 6828 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 6829 return StmtVisitorTy::Visit(E->getSemanticForm()); 6830 } 6831 6832 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 6833 // Evaluate and cache the common expression. We treat it as a temporary, 6834 // even though it's not quite the same thing. 6835 LValue CommonLV; 6836 if (!Evaluate(Info.CurrentCall->createTemporary( 6837 E->getOpaqueValue(), 6838 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 6839 CommonLV), 6840 Info, E->getCommon())) 6841 return false; 6842 6843 return HandleConditionalOperator(E); 6844 } 6845 6846 bool VisitConditionalOperator(const ConditionalOperator *E) { 6847 bool IsBcpCall = false; 6848 // If the condition (ignoring parens) is a __builtin_constant_p call, 6849 // the result is a constant expression if it can be folded without 6850 // side-effects. This is an important GNU extension. See GCC PR38377 6851 // for discussion. 6852 if (const CallExpr *CallCE = 6853 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 6854 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 6855 IsBcpCall = true; 6856 6857 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 6858 // constant expression; we can't check whether it's potentially foldable. 6859 // FIXME: We should instead treat __builtin_constant_p as non-constant if 6860 // it would return 'false' in this mode. 6861 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 6862 return false; 6863 6864 FoldConstant Fold(Info, IsBcpCall); 6865 if (!HandleConditionalOperator(E)) { 6866 Fold.keepDiagnostics(); 6867 return false; 6868 } 6869 6870 return true; 6871 } 6872 6873 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 6874 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 6875 return DerivedSuccess(*Value, E); 6876 6877 const Expr *Source = E->getSourceExpr(); 6878 if (!Source) 6879 return Error(E); 6880 if (Source == E) { // sanity checking. 6881 assert(0 && "OpaqueValueExpr recursively refers to itself"); 6882 return Error(E); 6883 } 6884 return StmtVisitorTy::Visit(Source); 6885 } 6886 6887 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 6888 for (const Expr *SemE : E->semantics()) { 6889 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 6890 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 6891 // result expression: there could be two different LValues that would 6892 // refer to the same object in that case, and we can't model that. 6893 if (SemE == E->getResultExpr()) 6894 return Error(E); 6895 6896 // Unique OVEs get evaluated if and when we encounter them when 6897 // emitting the rest of the semantic form, rather than eagerly. 6898 if (OVE->isUnique()) 6899 continue; 6900 6901 LValue LV; 6902 if (!Evaluate(Info.CurrentCall->createTemporary( 6903 OVE, getStorageType(Info.Ctx, OVE), false, LV), 6904 Info, OVE->getSourceExpr())) 6905 return false; 6906 } else if (SemE == E->getResultExpr()) { 6907 if (!StmtVisitorTy::Visit(SemE)) 6908 return false; 6909 } else { 6910 if (!EvaluateIgnoredValue(Info, SemE)) 6911 return false; 6912 } 6913 } 6914 return true; 6915 } 6916 6917 bool VisitCallExpr(const CallExpr *E) { 6918 APValue Result; 6919 if (!handleCallExpr(E, Result, nullptr)) 6920 return false; 6921 return DerivedSuccess(Result, E); 6922 } 6923 6924 bool handleCallExpr(const CallExpr *E, APValue &Result, 6925 const LValue *ResultSlot) { 6926 const Expr *Callee = E->getCallee()->IgnoreParens(); 6927 QualType CalleeType = Callee->getType(); 6928 6929 const FunctionDecl *FD = nullptr; 6930 LValue *This = nullptr, ThisVal; 6931 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6932 bool HasQualifier = false; 6933 6934 // Extract function decl and 'this' pointer from the callee. 6935 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 6936 const CXXMethodDecl *Member = nullptr; 6937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 6938 // Explicit bound member calls, such as x.f() or p->g(); 6939 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 6940 return false; 6941 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 6942 if (!Member) 6943 return Error(Callee); 6944 This = &ThisVal; 6945 HasQualifier = ME->hasQualifier(); 6946 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 6947 // Indirect bound member calls ('.*' or '->*'). 6948 const ValueDecl *D = 6949 HandleMemberPointerAccess(Info, BE, ThisVal, false); 6950 if (!D) 6951 return false; 6952 Member = dyn_cast<CXXMethodDecl>(D); 6953 if (!Member) 6954 return Error(Callee); 6955 This = &ThisVal; 6956 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 6957 if (!Info.getLangOpts().CPlusPlus2a) 6958 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 6959 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 6960 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 6961 } else 6962 return Error(Callee); 6963 FD = Member; 6964 } else if (CalleeType->isFunctionPointerType()) { 6965 LValue Call; 6966 if (!EvaluatePointer(Callee, Call, Info)) 6967 return false; 6968 6969 if (!Call.getLValueOffset().isZero()) 6970 return Error(Callee); 6971 FD = dyn_cast_or_null<FunctionDecl>( 6972 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 6973 if (!FD) 6974 return Error(Callee); 6975 // Don't call function pointers which have been cast to some other type. 6976 // Per DR (no number yet), the caller and callee can differ in noexcept. 6977 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 6978 CalleeType->getPointeeType(), FD->getType())) { 6979 return Error(E); 6980 } 6981 6982 // Overloaded operator calls to member functions are represented as normal 6983 // calls with '*this' as the first argument. 6984 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6985 if (MD && !MD->isStatic()) { 6986 // FIXME: When selecting an implicit conversion for an overloaded 6987 // operator delete, we sometimes try to evaluate calls to conversion 6988 // operators without a 'this' parameter! 6989 if (Args.empty()) 6990 return Error(E); 6991 6992 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 6993 return false; 6994 This = &ThisVal; 6995 Args = Args.slice(1); 6996 } else if (MD && MD->isLambdaStaticInvoker()) { 6997 // Map the static invoker for the lambda back to the call operator. 6998 // Conveniently, we don't have to slice out the 'this' argument (as is 6999 // being done for the non-static case), since a static member function 7000 // doesn't have an implicit argument passed in. 7001 const CXXRecordDecl *ClosureClass = MD->getParent(); 7002 assert( 7003 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7004 "Number of captures must be zero for conversion to function-ptr"); 7005 7006 const CXXMethodDecl *LambdaCallOp = 7007 ClosureClass->getLambdaCallOperator(); 7008 7009 // Set 'FD', the function that will be called below, to the call 7010 // operator. If the closure object represents a generic lambda, find 7011 // the corresponding specialization of the call operator. 7012 7013 if (ClosureClass->isGenericLambda()) { 7014 assert(MD->isFunctionTemplateSpecialization() && 7015 "A generic lambda's static-invoker function must be a " 7016 "template specialization"); 7017 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7018 FunctionTemplateDecl *CallOpTemplate = 7019 LambdaCallOp->getDescribedFunctionTemplate(); 7020 void *InsertPos = nullptr; 7021 FunctionDecl *CorrespondingCallOpSpecialization = 7022 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7023 assert(CorrespondingCallOpSpecialization && 7024 "We must always have a function call operator specialization " 7025 "that corresponds to our static invoker specialization"); 7026 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7027 } else 7028 FD = LambdaCallOp; 7029 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7030 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7031 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7032 LValue Ptr; 7033 if (!HandleOperatorNewCall(Info, E, Ptr)) 7034 return false; 7035 Ptr.moveInto(Result); 7036 return true; 7037 } else { 7038 return HandleOperatorDeleteCall(Info, E); 7039 } 7040 } 7041 } else 7042 return Error(E); 7043 7044 SmallVector<QualType, 4> CovariantAdjustmentPath; 7045 if (This) { 7046 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7047 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7048 // Perform virtual dispatch, if necessary. 7049 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7050 CovariantAdjustmentPath); 7051 if (!FD) 7052 return false; 7053 } else { 7054 // Check that the 'this' pointer points to an object of the right type. 7055 // FIXME: If this is an assignment operator call, we may need to change 7056 // the active union member before we check this. 7057 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7058 return false; 7059 } 7060 } 7061 7062 // Destructor calls are different enough that they have their own codepath. 7063 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7064 assert(This && "no 'this' pointer for destructor call"); 7065 return HandleDestruction(Info, E, *This, 7066 Info.Ctx.getRecordType(DD->getParent())); 7067 } 7068 7069 const FunctionDecl *Definition = nullptr; 7070 Stmt *Body = FD->getBody(Definition); 7071 7072 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7073 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 7074 Result, ResultSlot)) 7075 return false; 7076 7077 if (!CovariantAdjustmentPath.empty() && 7078 !HandleCovariantReturnAdjustment(Info, E, Result, 7079 CovariantAdjustmentPath)) 7080 return false; 7081 7082 return true; 7083 } 7084 7085 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7086 return StmtVisitorTy::Visit(E->getInitializer()); 7087 } 7088 bool VisitInitListExpr(const InitListExpr *E) { 7089 if (E->getNumInits() == 0) 7090 return DerivedZeroInitialization(E); 7091 if (E->getNumInits() == 1) 7092 return StmtVisitorTy::Visit(E->getInit(0)); 7093 return Error(E); 7094 } 7095 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7096 return DerivedZeroInitialization(E); 7097 } 7098 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7099 return DerivedZeroInitialization(E); 7100 } 7101 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7102 return DerivedZeroInitialization(E); 7103 } 7104 7105 /// A member expression where the object is a prvalue is itself a prvalue. 7106 bool VisitMemberExpr(const MemberExpr *E) { 7107 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7108 "missing temporary materialization conversion"); 7109 assert(!E->isArrow() && "missing call to bound member function?"); 7110 7111 APValue Val; 7112 if (!Evaluate(Val, Info, E->getBase())) 7113 return false; 7114 7115 QualType BaseTy = E->getBase()->getType(); 7116 7117 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7118 if (!FD) return Error(E); 7119 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7120 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7121 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7122 7123 // Note: there is no lvalue base here. But this case should only ever 7124 // happen in C or in C++98, where we cannot be evaluating a constexpr 7125 // constructor, which is the only case the base matters. 7126 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7127 SubobjectDesignator Designator(BaseTy); 7128 Designator.addDeclUnchecked(FD); 7129 7130 APValue Result; 7131 return extractSubobject(Info, E, Obj, Designator, Result) && 7132 DerivedSuccess(Result, E); 7133 } 7134 7135 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7136 APValue Val; 7137 if (!Evaluate(Val, Info, E->getBase())) 7138 return false; 7139 7140 if (Val.isVector()) { 7141 SmallVector<uint32_t, 4> Indices; 7142 E->getEncodedElementAccess(Indices); 7143 if (Indices.size() == 1) { 7144 // Return scalar. 7145 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7146 } else { 7147 // Construct new APValue vector. 7148 SmallVector<APValue, 4> Elts; 7149 for (unsigned I = 0; I < Indices.size(); ++I) { 7150 Elts.push_back(Val.getVectorElt(Indices[I])); 7151 } 7152 APValue VecResult(Elts.data(), Indices.size()); 7153 return DerivedSuccess(VecResult, E); 7154 } 7155 } 7156 7157 return false; 7158 } 7159 7160 bool VisitCastExpr(const CastExpr *E) { 7161 switch (E->getCastKind()) { 7162 default: 7163 break; 7164 7165 case CK_AtomicToNonAtomic: { 7166 APValue AtomicVal; 7167 // This does not need to be done in place even for class/array types: 7168 // atomic-to-non-atomic conversion implies copying the object 7169 // representation. 7170 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7171 return false; 7172 return DerivedSuccess(AtomicVal, E); 7173 } 7174 7175 case CK_NoOp: 7176 case CK_UserDefinedConversion: 7177 return StmtVisitorTy::Visit(E->getSubExpr()); 7178 7179 case CK_LValueToRValue: { 7180 LValue LVal; 7181 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7182 return false; 7183 APValue RVal; 7184 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7185 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7186 LVal, RVal)) 7187 return false; 7188 return DerivedSuccess(RVal, E); 7189 } 7190 case CK_LValueToRValueBitCast: { 7191 APValue DestValue, SourceValue; 7192 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7193 return false; 7194 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7195 return false; 7196 return DerivedSuccess(DestValue, E); 7197 } 7198 7199 case CK_AddressSpaceConversion: { 7200 APValue Value; 7201 if (!Evaluate(Value, Info, E->getSubExpr())) 7202 return false; 7203 return DerivedSuccess(Value, E); 7204 } 7205 } 7206 7207 return Error(E); 7208 } 7209 7210 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7211 return VisitUnaryPostIncDec(UO); 7212 } 7213 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7214 return VisitUnaryPostIncDec(UO); 7215 } 7216 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7217 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7218 return Error(UO); 7219 7220 LValue LVal; 7221 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7222 return false; 7223 APValue RVal; 7224 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7225 UO->isIncrementOp(), &RVal)) 7226 return false; 7227 return DerivedSuccess(RVal, UO); 7228 } 7229 7230 bool VisitStmtExpr(const StmtExpr *E) { 7231 // We will have checked the full-expressions inside the statement expression 7232 // when they were completed, and don't need to check them again now. 7233 if (Info.checkingForUndefinedBehavior()) 7234 return Error(E); 7235 7236 const CompoundStmt *CS = E->getSubStmt(); 7237 if (CS->body_empty()) 7238 return true; 7239 7240 BlockScopeRAII Scope(Info); 7241 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7242 BE = CS->body_end(); 7243 /**/; ++BI) { 7244 if (BI + 1 == BE) { 7245 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7246 if (!FinalExpr) { 7247 Info.FFDiag((*BI)->getBeginLoc(), 7248 diag::note_constexpr_stmt_expr_unsupported); 7249 return false; 7250 } 7251 return this->Visit(FinalExpr) && Scope.destroy(); 7252 } 7253 7254 APValue ReturnValue; 7255 StmtResult Result = { ReturnValue, nullptr }; 7256 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7257 if (ESR != ESR_Succeeded) { 7258 // FIXME: If the statement-expression terminated due to 'return', 7259 // 'break', or 'continue', it would be nice to propagate that to 7260 // the outer statement evaluation rather than bailing out. 7261 if (ESR != ESR_Failed) 7262 Info.FFDiag((*BI)->getBeginLoc(), 7263 diag::note_constexpr_stmt_expr_unsupported); 7264 return false; 7265 } 7266 } 7267 7268 llvm_unreachable("Return from function from the loop above."); 7269 } 7270 7271 /// Visit a value which is evaluated, but whose value is ignored. 7272 void VisitIgnoredValue(const Expr *E) { 7273 EvaluateIgnoredValue(Info, E); 7274 } 7275 7276 /// Potentially visit a MemberExpr's base expression. 7277 void VisitIgnoredBaseExpression(const Expr *E) { 7278 // While MSVC doesn't evaluate the base expression, it does diagnose the 7279 // presence of side-effecting behavior. 7280 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7281 return; 7282 VisitIgnoredValue(E); 7283 } 7284 }; 7285 7286 } // namespace 7287 7288 //===----------------------------------------------------------------------===// 7289 // Common base class for lvalue and temporary evaluation. 7290 //===----------------------------------------------------------------------===// 7291 namespace { 7292 template<class Derived> 7293 class LValueExprEvaluatorBase 7294 : public ExprEvaluatorBase<Derived> { 7295 protected: 7296 LValue &Result; 7297 bool InvalidBaseOK; 7298 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7299 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7300 7301 bool Success(APValue::LValueBase B) { 7302 Result.set(B); 7303 return true; 7304 } 7305 7306 bool evaluatePointer(const Expr *E, LValue &Result) { 7307 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7308 } 7309 7310 public: 7311 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7312 : ExprEvaluatorBaseTy(Info), Result(Result), 7313 InvalidBaseOK(InvalidBaseOK) {} 7314 7315 bool Success(const APValue &V, const Expr *E) { 7316 Result.setFrom(this->Info.Ctx, V); 7317 return true; 7318 } 7319 7320 bool VisitMemberExpr(const MemberExpr *E) { 7321 // Handle non-static data members. 7322 QualType BaseTy; 7323 bool EvalOK; 7324 if (E->isArrow()) { 7325 EvalOK = evaluatePointer(E->getBase(), Result); 7326 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7327 } else if (E->getBase()->isRValue()) { 7328 assert(E->getBase()->getType()->isRecordType()); 7329 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7330 BaseTy = E->getBase()->getType(); 7331 } else { 7332 EvalOK = this->Visit(E->getBase()); 7333 BaseTy = E->getBase()->getType(); 7334 } 7335 if (!EvalOK) { 7336 if (!InvalidBaseOK) 7337 return false; 7338 Result.setInvalid(E); 7339 return true; 7340 } 7341 7342 const ValueDecl *MD = E->getMemberDecl(); 7343 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7344 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7345 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7346 (void)BaseTy; 7347 if (!HandleLValueMember(this->Info, E, Result, FD)) 7348 return false; 7349 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7350 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7351 return false; 7352 } else 7353 return this->Error(E); 7354 7355 if (MD->getType()->isReferenceType()) { 7356 APValue RefValue; 7357 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7358 RefValue)) 7359 return false; 7360 return Success(RefValue, E); 7361 } 7362 return true; 7363 } 7364 7365 bool VisitBinaryOperator(const BinaryOperator *E) { 7366 switch (E->getOpcode()) { 7367 default: 7368 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7369 7370 case BO_PtrMemD: 7371 case BO_PtrMemI: 7372 return HandleMemberPointerAccess(this->Info, E, Result); 7373 } 7374 } 7375 7376 bool VisitCastExpr(const CastExpr *E) { 7377 switch (E->getCastKind()) { 7378 default: 7379 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7380 7381 case CK_DerivedToBase: 7382 case CK_UncheckedDerivedToBase: 7383 if (!this->Visit(E->getSubExpr())) 7384 return false; 7385 7386 // Now figure out the necessary offset to add to the base LV to get from 7387 // the derived class to the base class. 7388 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7389 Result); 7390 } 7391 } 7392 }; 7393 } 7394 7395 //===----------------------------------------------------------------------===// 7396 // LValue Evaluation 7397 // 7398 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7399 // function designators (in C), decl references to void objects (in C), and 7400 // temporaries (if building with -Wno-address-of-temporary). 7401 // 7402 // LValue evaluation produces values comprising a base expression of one of the 7403 // following types: 7404 // - Declarations 7405 // * VarDecl 7406 // * FunctionDecl 7407 // - Literals 7408 // * CompoundLiteralExpr in C (and in global scope in C++) 7409 // * StringLiteral 7410 // * PredefinedExpr 7411 // * ObjCStringLiteralExpr 7412 // * ObjCEncodeExpr 7413 // * AddrLabelExpr 7414 // * BlockExpr 7415 // * CallExpr for a MakeStringConstant builtin 7416 // - typeid(T) expressions, as TypeInfoLValues 7417 // - Locals and temporaries 7418 // * MaterializeTemporaryExpr 7419 // * Any Expr, with a CallIndex indicating the function in which the temporary 7420 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7421 // from the AST (FIXME). 7422 // * A MaterializeTemporaryExpr that has static storage duration, with no 7423 // CallIndex, for a lifetime-extended temporary. 7424 // * The ConstantExpr that is currently being evaluated during evaluation of an 7425 // immediate invocation. 7426 // plus an offset in bytes. 7427 //===----------------------------------------------------------------------===// 7428 namespace { 7429 class LValueExprEvaluator 7430 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7431 public: 7432 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7433 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7434 7435 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7436 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7437 7438 bool VisitDeclRefExpr(const DeclRefExpr *E); 7439 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7440 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7441 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7442 bool VisitMemberExpr(const MemberExpr *E); 7443 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7444 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7445 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7446 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7447 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7448 bool VisitUnaryDeref(const UnaryOperator *E); 7449 bool VisitUnaryReal(const UnaryOperator *E); 7450 bool VisitUnaryImag(const UnaryOperator *E); 7451 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7452 return VisitUnaryPreIncDec(UO); 7453 } 7454 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7455 return VisitUnaryPreIncDec(UO); 7456 } 7457 bool VisitBinAssign(const BinaryOperator *BO); 7458 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7459 7460 bool VisitCastExpr(const CastExpr *E) { 7461 switch (E->getCastKind()) { 7462 default: 7463 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7464 7465 case CK_LValueBitCast: 7466 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7467 if (!Visit(E->getSubExpr())) 7468 return false; 7469 Result.Designator.setInvalid(); 7470 return true; 7471 7472 case CK_BaseToDerived: 7473 if (!Visit(E->getSubExpr())) 7474 return false; 7475 return HandleBaseToDerivedCast(Info, E, Result); 7476 7477 case CK_Dynamic: 7478 if (!Visit(E->getSubExpr())) 7479 return false; 7480 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7481 } 7482 } 7483 }; 7484 } // end anonymous namespace 7485 7486 /// Evaluate an expression as an lvalue. This can be legitimately called on 7487 /// expressions which are not glvalues, in three cases: 7488 /// * function designators in C, and 7489 /// * "extern void" objects 7490 /// * @selector() expressions in Objective-C 7491 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7492 bool InvalidBaseOK) { 7493 assert(E->isGLValue() || E->getType()->isFunctionType() || 7494 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7495 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7496 } 7497 7498 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7500 return Success(FD); 7501 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7502 return VisitVarDecl(E, VD); 7503 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7504 return Visit(BD->getBinding()); 7505 return Error(E); 7506 } 7507 7508 7509 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7510 7511 // If we are within a lambda's call operator, check whether the 'VD' referred 7512 // to within 'E' actually represents a lambda-capture that maps to a 7513 // data-member/field within the closure object, and if so, evaluate to the 7514 // field or what the field refers to. 7515 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7516 isa<DeclRefExpr>(E) && 7517 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7518 // We don't always have a complete capture-map when checking or inferring if 7519 // the function call operator meets the requirements of a constexpr function 7520 // - but we don't need to evaluate the captures to determine constexprness 7521 // (dcl.constexpr C++17). 7522 if (Info.checkingPotentialConstantExpression()) 7523 return false; 7524 7525 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7526 // Start with 'Result' referring to the complete closure object... 7527 Result = *Info.CurrentCall->This; 7528 // ... then update it to refer to the field of the closure object 7529 // that represents the capture. 7530 if (!HandleLValueMember(Info, E, Result, FD)) 7531 return false; 7532 // And if the field is of reference type, update 'Result' to refer to what 7533 // the field refers to. 7534 if (FD->getType()->isReferenceType()) { 7535 APValue RVal; 7536 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7537 RVal)) 7538 return false; 7539 Result.setFrom(Info.Ctx, RVal); 7540 } 7541 return true; 7542 } 7543 } 7544 CallStackFrame *Frame = nullptr; 7545 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7546 // Only if a local variable was declared in the function currently being 7547 // evaluated, do we expect to be able to find its value in the current 7548 // frame. (Otherwise it was likely declared in an enclosing context and 7549 // could either have a valid evaluatable value (for e.g. a constexpr 7550 // variable) or be ill-formed (and trigger an appropriate evaluation 7551 // diagnostic)). 7552 if (Info.CurrentCall->Callee && 7553 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7554 Frame = Info.CurrentCall; 7555 } 7556 } 7557 7558 if (!VD->getType()->isReferenceType()) { 7559 if (Frame) { 7560 Result.set({VD, Frame->Index, 7561 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7562 return true; 7563 } 7564 return Success(VD); 7565 } 7566 7567 APValue *V; 7568 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7569 return false; 7570 if (!V->hasValue()) { 7571 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7572 // adjust the diagnostic to say that. 7573 if (!Info.checkingPotentialConstantExpression()) 7574 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7575 return false; 7576 } 7577 return Success(*V, E); 7578 } 7579 7580 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7581 const MaterializeTemporaryExpr *E) { 7582 // Walk through the expression to find the materialized temporary itself. 7583 SmallVector<const Expr *, 2> CommaLHSs; 7584 SmallVector<SubobjectAdjustment, 2> Adjustments; 7585 const Expr *Inner = 7586 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7587 7588 // If we passed any comma operators, evaluate their LHSs. 7589 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7590 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7591 return false; 7592 7593 // A materialized temporary with static storage duration can appear within the 7594 // result of a constant expression evaluation, so we need to preserve its 7595 // value for use outside this evaluation. 7596 APValue *Value; 7597 if (E->getStorageDuration() == SD_Static) { 7598 Value = E->getOrCreateValue(true); 7599 *Value = APValue(); 7600 Result.set(E); 7601 } else { 7602 Value = &Info.CurrentCall->createTemporary( 7603 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7604 } 7605 7606 QualType Type = Inner->getType(); 7607 7608 // Materialize the temporary itself. 7609 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7610 *Value = APValue(); 7611 return false; 7612 } 7613 7614 // Adjust our lvalue to refer to the desired subobject. 7615 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7616 --I; 7617 switch (Adjustments[I].Kind) { 7618 case SubobjectAdjustment::DerivedToBaseAdjustment: 7619 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7620 Type, Result)) 7621 return false; 7622 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7623 break; 7624 7625 case SubobjectAdjustment::FieldAdjustment: 7626 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7627 return false; 7628 Type = Adjustments[I].Field->getType(); 7629 break; 7630 7631 case SubobjectAdjustment::MemberPointerAdjustment: 7632 if (!HandleMemberPointerAccess(this->Info, Type, Result, 7633 Adjustments[I].Ptr.RHS)) 7634 return false; 7635 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 7636 break; 7637 } 7638 } 7639 7640 return true; 7641 } 7642 7643 bool 7644 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7645 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 7646 "lvalue compound literal in c++?"); 7647 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 7648 // only see this when folding in C, so there's no standard to follow here. 7649 return Success(E); 7650 } 7651 7652 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 7653 TypeInfoLValue TypeInfo; 7654 7655 if (!E->isPotentiallyEvaluated()) { 7656 if (E->isTypeOperand()) 7657 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 7658 else 7659 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 7660 } else { 7661 if (!Info.Ctx.getLangOpts().CPlusPlus2a) { 7662 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 7663 << E->getExprOperand()->getType() 7664 << E->getExprOperand()->getSourceRange(); 7665 } 7666 7667 if (!Visit(E->getExprOperand())) 7668 return false; 7669 7670 Optional<DynamicType> DynType = 7671 ComputeDynamicType(Info, E, Result, AK_TypeId); 7672 if (!DynType) 7673 return false; 7674 7675 TypeInfo = 7676 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 7677 } 7678 7679 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 7680 } 7681 7682 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 7683 return Success(E); 7684 } 7685 7686 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 7687 // Handle static data members. 7688 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 7689 VisitIgnoredBaseExpression(E->getBase()); 7690 return VisitVarDecl(E, VD); 7691 } 7692 7693 // Handle static member functions. 7694 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 7695 if (MD->isStatic()) { 7696 VisitIgnoredBaseExpression(E->getBase()); 7697 return Success(MD); 7698 } 7699 } 7700 7701 // Handle non-static data members. 7702 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 7703 } 7704 7705 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 7706 // FIXME: Deal with vectors as array subscript bases. 7707 if (E->getBase()->getType()->isVectorType()) 7708 return Error(E); 7709 7710 bool Success = true; 7711 if (!evaluatePointer(E->getBase(), Result)) { 7712 if (!Info.noteFailure()) 7713 return false; 7714 Success = false; 7715 } 7716 7717 APSInt Index; 7718 if (!EvaluateInteger(E->getIdx(), Index, Info)) 7719 return false; 7720 7721 return Success && 7722 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 7723 } 7724 7725 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 7726 return evaluatePointer(E->getSubExpr(), Result); 7727 } 7728 7729 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 7730 if (!Visit(E->getSubExpr())) 7731 return false; 7732 // __real is a no-op on scalar lvalues. 7733 if (E->getSubExpr()->getType()->isAnyComplexType()) 7734 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 7735 return true; 7736 } 7737 7738 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7739 assert(E->getSubExpr()->getType()->isAnyComplexType() && 7740 "lvalue __imag__ on scalar?"); 7741 if (!Visit(E->getSubExpr())) 7742 return false; 7743 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 7744 return true; 7745 } 7746 7747 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 7748 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7749 return Error(UO); 7750 7751 if (!this->Visit(UO->getSubExpr())) 7752 return false; 7753 7754 return handleIncDec( 7755 this->Info, UO, Result, UO->getSubExpr()->getType(), 7756 UO->isIncrementOp(), nullptr); 7757 } 7758 7759 bool LValueExprEvaluator::VisitCompoundAssignOperator( 7760 const CompoundAssignOperator *CAO) { 7761 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7762 return Error(CAO); 7763 7764 APValue RHS; 7765 7766 // The overall lvalue result is the result of evaluating the LHS. 7767 if (!this->Visit(CAO->getLHS())) { 7768 if (Info.noteFailure()) 7769 Evaluate(RHS, this->Info, CAO->getRHS()); 7770 return false; 7771 } 7772 7773 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 7774 return false; 7775 7776 return handleCompoundAssignment( 7777 this->Info, CAO, 7778 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 7779 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 7780 } 7781 7782 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 7783 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7784 return Error(E); 7785 7786 APValue NewVal; 7787 7788 if (!this->Visit(E->getLHS())) { 7789 if (Info.noteFailure()) 7790 Evaluate(NewVal, this->Info, E->getRHS()); 7791 return false; 7792 } 7793 7794 if (!Evaluate(NewVal, this->Info, E->getRHS())) 7795 return false; 7796 7797 if (Info.getLangOpts().CPlusPlus2a && 7798 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 7799 return false; 7800 7801 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 7802 NewVal); 7803 } 7804 7805 //===----------------------------------------------------------------------===// 7806 // Pointer Evaluation 7807 //===----------------------------------------------------------------------===// 7808 7809 /// Attempts to compute the number of bytes available at the pointer 7810 /// returned by a function with the alloc_size attribute. Returns true if we 7811 /// were successful. Places an unsigned number into `Result`. 7812 /// 7813 /// This expects the given CallExpr to be a call to a function with an 7814 /// alloc_size attribute. 7815 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 7816 const CallExpr *Call, 7817 llvm::APInt &Result) { 7818 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 7819 7820 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 7821 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 7822 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 7823 if (Call->getNumArgs() <= SizeArgNo) 7824 return false; 7825 7826 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 7827 Expr::EvalResult ExprResult; 7828 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 7829 return false; 7830 Into = ExprResult.Val.getInt(); 7831 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 7832 return false; 7833 Into = Into.zextOrSelf(BitsInSizeT); 7834 return true; 7835 }; 7836 7837 APSInt SizeOfElem; 7838 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 7839 return false; 7840 7841 if (!AllocSize->getNumElemsParam().isValid()) { 7842 Result = std::move(SizeOfElem); 7843 return true; 7844 } 7845 7846 APSInt NumberOfElems; 7847 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 7848 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 7849 return false; 7850 7851 bool Overflow; 7852 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 7853 if (Overflow) 7854 return false; 7855 7856 Result = std::move(BytesAvailable); 7857 return true; 7858 } 7859 7860 /// Convenience function. LVal's base must be a call to an alloc_size 7861 /// function. 7862 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 7863 const LValue &LVal, 7864 llvm::APInt &Result) { 7865 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7866 "Can't get the size of a non alloc_size function"); 7867 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 7868 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 7869 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 7870 } 7871 7872 /// Attempts to evaluate the given LValueBase as the result of a call to 7873 /// a function with the alloc_size attribute. If it was possible to do so, this 7874 /// function will return true, make Result's Base point to said function call, 7875 /// and mark Result's Base as invalid. 7876 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 7877 LValue &Result) { 7878 if (Base.isNull()) 7879 return false; 7880 7881 // Because we do no form of static analysis, we only support const variables. 7882 // 7883 // Additionally, we can't support parameters, nor can we support static 7884 // variables (in the latter case, use-before-assign isn't UB; in the former, 7885 // we have no clue what they'll be assigned to). 7886 const auto *VD = 7887 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 7888 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 7889 return false; 7890 7891 const Expr *Init = VD->getAnyInitializer(); 7892 if (!Init) 7893 return false; 7894 7895 const Expr *E = Init->IgnoreParens(); 7896 if (!tryUnwrapAllocSizeCall(E)) 7897 return false; 7898 7899 // Store E instead of E unwrapped so that the type of the LValue's base is 7900 // what the user wanted. 7901 Result.setInvalid(E); 7902 7903 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 7904 Result.addUnsizedArray(Info, E, Pointee); 7905 return true; 7906 } 7907 7908 namespace { 7909 class PointerExprEvaluator 7910 : public ExprEvaluatorBase<PointerExprEvaluator> { 7911 LValue &Result; 7912 bool InvalidBaseOK; 7913 7914 bool Success(const Expr *E) { 7915 Result.set(E); 7916 return true; 7917 } 7918 7919 bool evaluateLValue(const Expr *E, LValue &Result) { 7920 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 7921 } 7922 7923 bool evaluatePointer(const Expr *E, LValue &Result) { 7924 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 7925 } 7926 7927 bool visitNonBuiltinCallExpr(const CallExpr *E); 7928 public: 7929 7930 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 7931 : ExprEvaluatorBaseTy(info), Result(Result), 7932 InvalidBaseOK(InvalidBaseOK) {} 7933 7934 bool Success(const APValue &V, const Expr *E) { 7935 Result.setFrom(Info.Ctx, V); 7936 return true; 7937 } 7938 bool ZeroInitialization(const Expr *E) { 7939 Result.setNull(Info.Ctx, E->getType()); 7940 return true; 7941 } 7942 7943 bool VisitBinaryOperator(const BinaryOperator *E); 7944 bool VisitCastExpr(const CastExpr* E); 7945 bool VisitUnaryAddrOf(const UnaryOperator *E); 7946 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 7947 { return Success(E); } 7948 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 7949 if (E->isExpressibleAsConstantInitializer()) 7950 return Success(E); 7951 if (Info.noteFailure()) 7952 EvaluateIgnoredValue(Info, E->getSubExpr()); 7953 return Error(E); 7954 } 7955 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 7956 { return Success(E); } 7957 bool VisitCallExpr(const CallExpr *E); 7958 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7959 bool VisitBlockExpr(const BlockExpr *E) { 7960 if (!E->getBlockDecl()->hasCaptures()) 7961 return Success(E); 7962 return Error(E); 7963 } 7964 bool VisitCXXThisExpr(const CXXThisExpr *E) { 7965 // Can't look at 'this' when checking a potential constant expression. 7966 if (Info.checkingPotentialConstantExpression()) 7967 return false; 7968 if (!Info.CurrentCall->This) { 7969 if (Info.getLangOpts().CPlusPlus11) 7970 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 7971 else 7972 Info.FFDiag(E); 7973 return false; 7974 } 7975 Result = *Info.CurrentCall->This; 7976 // If we are inside a lambda's call operator, the 'this' expression refers 7977 // to the enclosing '*this' object (either by value or reference) which is 7978 // either copied into the closure object's field that represents the '*this' 7979 // or refers to '*this'. 7980 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 7981 // Ensure we actually have captured 'this'. (an error will have 7982 // been previously reported if not). 7983 if (!Info.CurrentCall->LambdaThisCaptureField) 7984 return false; 7985 7986 // Update 'Result' to refer to the data member/field of the closure object 7987 // that represents the '*this' capture. 7988 if (!HandleLValueMember(Info, E, Result, 7989 Info.CurrentCall->LambdaThisCaptureField)) 7990 return false; 7991 // If we captured '*this' by reference, replace the field with its referent. 7992 if (Info.CurrentCall->LambdaThisCaptureField->getType() 7993 ->isPointerType()) { 7994 APValue RVal; 7995 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 7996 RVal)) 7997 return false; 7998 7999 Result.setFrom(Info.Ctx, RVal); 8000 } 8001 } 8002 return true; 8003 } 8004 8005 bool VisitCXXNewExpr(const CXXNewExpr *E); 8006 8007 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8008 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8009 APValue LValResult = E->EvaluateInContext( 8010 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8011 Result.setFrom(Info.Ctx, LValResult); 8012 return true; 8013 } 8014 8015 // FIXME: Missing: @protocol, @selector 8016 }; 8017 } // end anonymous namespace 8018 8019 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8020 bool InvalidBaseOK) { 8021 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8022 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8023 } 8024 8025 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8026 if (E->getOpcode() != BO_Add && 8027 E->getOpcode() != BO_Sub) 8028 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8029 8030 const Expr *PExp = E->getLHS(); 8031 const Expr *IExp = E->getRHS(); 8032 if (IExp->getType()->isPointerType()) 8033 std::swap(PExp, IExp); 8034 8035 bool EvalPtrOK = evaluatePointer(PExp, Result); 8036 if (!EvalPtrOK && !Info.noteFailure()) 8037 return false; 8038 8039 llvm::APSInt Offset; 8040 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8041 return false; 8042 8043 if (E->getOpcode() == BO_Sub) 8044 negateAsSigned(Offset); 8045 8046 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8047 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8048 } 8049 8050 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8051 return evaluateLValue(E->getSubExpr(), Result); 8052 } 8053 8054 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8055 const Expr *SubExpr = E->getSubExpr(); 8056 8057 switch (E->getCastKind()) { 8058 default: 8059 break; 8060 case CK_BitCast: 8061 case CK_CPointerToObjCPointerCast: 8062 case CK_BlockPointerToObjCPointerCast: 8063 case CK_AnyPointerToBlockPointerCast: 8064 case CK_AddressSpaceConversion: 8065 if (!Visit(SubExpr)) 8066 return false; 8067 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8068 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8069 // also static_casts, but we disallow them as a resolution to DR1312. 8070 if (!E->getType()->isVoidPointerType()) { 8071 if (!Result.InvalidBase && !Result.Designator.Invalid && 8072 !Result.IsNullPtr && 8073 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8074 E->getType()->getPointeeType()) && 8075 Info.getStdAllocatorCaller("allocate")) { 8076 // Inside a call to std::allocator::allocate and friends, we permit 8077 // casting from void* back to cv1 T* for a pointer that points to a 8078 // cv2 T. 8079 } else { 8080 Result.Designator.setInvalid(); 8081 if (SubExpr->getType()->isVoidPointerType()) 8082 CCEDiag(E, diag::note_constexpr_invalid_cast) 8083 << 3 << SubExpr->getType(); 8084 else 8085 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8086 } 8087 } 8088 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8089 ZeroInitialization(E); 8090 return true; 8091 8092 case CK_DerivedToBase: 8093 case CK_UncheckedDerivedToBase: 8094 if (!evaluatePointer(E->getSubExpr(), Result)) 8095 return false; 8096 if (!Result.Base && Result.Offset.isZero()) 8097 return true; 8098 8099 // Now figure out the necessary offset to add to the base LV to get from 8100 // the derived class to the base class. 8101 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8102 castAs<PointerType>()->getPointeeType(), 8103 Result); 8104 8105 case CK_BaseToDerived: 8106 if (!Visit(E->getSubExpr())) 8107 return false; 8108 if (!Result.Base && Result.Offset.isZero()) 8109 return true; 8110 return HandleBaseToDerivedCast(Info, E, Result); 8111 8112 case CK_Dynamic: 8113 if (!Visit(E->getSubExpr())) 8114 return false; 8115 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8116 8117 case CK_NullToPointer: 8118 VisitIgnoredValue(E->getSubExpr()); 8119 return ZeroInitialization(E); 8120 8121 case CK_IntegralToPointer: { 8122 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8123 8124 APValue Value; 8125 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8126 break; 8127 8128 if (Value.isInt()) { 8129 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8130 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8131 Result.Base = (Expr*)nullptr; 8132 Result.InvalidBase = false; 8133 Result.Offset = CharUnits::fromQuantity(N); 8134 Result.Designator.setInvalid(); 8135 Result.IsNullPtr = false; 8136 return true; 8137 } else { 8138 // Cast is of an lvalue, no need to change value. 8139 Result.setFrom(Info.Ctx, Value); 8140 return true; 8141 } 8142 } 8143 8144 case CK_ArrayToPointerDecay: { 8145 if (SubExpr->isGLValue()) { 8146 if (!evaluateLValue(SubExpr, Result)) 8147 return false; 8148 } else { 8149 APValue &Value = Info.CurrentCall->createTemporary( 8150 SubExpr, SubExpr->getType(), false, Result); 8151 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8152 return false; 8153 } 8154 // The result is a pointer to the first element of the array. 8155 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8156 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8157 Result.addArray(Info, E, CAT); 8158 else 8159 Result.addUnsizedArray(Info, E, AT->getElementType()); 8160 return true; 8161 } 8162 8163 case CK_FunctionToPointerDecay: 8164 return evaluateLValue(SubExpr, Result); 8165 8166 case CK_LValueToRValue: { 8167 LValue LVal; 8168 if (!evaluateLValue(E->getSubExpr(), LVal)) 8169 return false; 8170 8171 APValue RVal; 8172 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8173 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8174 LVal, RVal)) 8175 return InvalidBaseOK && 8176 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8177 return Success(RVal, E); 8178 } 8179 } 8180 8181 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8182 } 8183 8184 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8185 UnaryExprOrTypeTrait ExprKind) { 8186 // C++ [expr.alignof]p3: 8187 // When alignof is applied to a reference type, the result is the 8188 // alignment of the referenced type. 8189 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8190 T = Ref->getPointeeType(); 8191 8192 if (T.getQualifiers().hasUnaligned()) 8193 return CharUnits::One(); 8194 8195 const bool AlignOfReturnsPreferred = 8196 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8197 8198 // __alignof is defined to return the preferred alignment. 8199 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8200 // as well. 8201 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8202 return Info.Ctx.toCharUnitsFromBits( 8203 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8204 // alignof and _Alignof are defined to return the ABI alignment. 8205 else if (ExprKind == UETT_AlignOf) 8206 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8207 else 8208 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8209 } 8210 8211 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8212 UnaryExprOrTypeTrait ExprKind) { 8213 E = E->IgnoreParens(); 8214 8215 // The kinds of expressions that we have special-case logic here for 8216 // should be kept up to date with the special checks for those 8217 // expressions in Sema. 8218 8219 // alignof decl is always accepted, even if it doesn't make sense: we default 8220 // to 1 in those cases. 8221 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8222 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8223 /*RefAsPointee*/true); 8224 8225 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8226 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8227 /*RefAsPointee*/true); 8228 8229 return GetAlignOfType(Info, E->getType(), ExprKind); 8230 } 8231 8232 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8233 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8234 return Info.Ctx.getDeclAlign(VD); 8235 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8236 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8237 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8238 } 8239 8240 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8241 /// __builtin_is_aligned and __builtin_assume_aligned. 8242 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8243 EvalInfo &Info, APSInt &Alignment) { 8244 if (!EvaluateInteger(E, Alignment, Info)) 8245 return false; 8246 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8247 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8248 return false; 8249 } 8250 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8251 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8252 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8253 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8254 << MaxValue << ForType << Alignment; 8255 return false; 8256 } 8257 // Ensure both alignment and source value have the same bit width so that we 8258 // don't assert when computing the resulting value. 8259 APSInt ExtAlignment = 8260 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8261 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8262 "Alignment should not be changed by ext/trunc"); 8263 Alignment = ExtAlignment; 8264 assert(Alignment.getBitWidth() == SrcWidth); 8265 return true; 8266 } 8267 8268 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8269 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8270 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8271 return true; 8272 8273 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8274 return false; 8275 8276 Result.setInvalid(E); 8277 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8278 Result.addUnsizedArray(Info, E, PointeeTy); 8279 return true; 8280 } 8281 8282 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8283 if (IsStringLiteralCall(E)) 8284 return Success(E); 8285 8286 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8287 return VisitBuiltinCallExpr(E, BuiltinOp); 8288 8289 return visitNonBuiltinCallExpr(E); 8290 } 8291 8292 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8293 unsigned BuiltinOp) { 8294 switch (BuiltinOp) { 8295 case Builtin::BI__builtin_addressof: 8296 return evaluateLValue(E->getArg(0), Result); 8297 case Builtin::BI__builtin_assume_aligned: { 8298 // We need to be very careful here because: if the pointer does not have the 8299 // asserted alignment, then the behavior is undefined, and undefined 8300 // behavior is non-constant. 8301 if (!evaluatePointer(E->getArg(0), Result)) 8302 return false; 8303 8304 LValue OffsetResult(Result); 8305 APSInt Alignment; 8306 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8307 Alignment)) 8308 return false; 8309 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8310 8311 if (E->getNumArgs() > 2) { 8312 APSInt Offset; 8313 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8314 return false; 8315 8316 int64_t AdditionalOffset = -Offset.getZExtValue(); 8317 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8318 } 8319 8320 // If there is a base object, then it must have the correct alignment. 8321 if (OffsetResult.Base) { 8322 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8323 8324 if (BaseAlignment < Align) { 8325 Result.Designator.setInvalid(); 8326 // FIXME: Add support to Diagnostic for long / long long. 8327 CCEDiag(E->getArg(0), 8328 diag::note_constexpr_baa_insufficient_alignment) << 0 8329 << (unsigned)BaseAlignment.getQuantity() 8330 << (unsigned)Align.getQuantity(); 8331 return false; 8332 } 8333 } 8334 8335 // The offset must also have the correct alignment. 8336 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8337 Result.Designator.setInvalid(); 8338 8339 (OffsetResult.Base 8340 ? CCEDiag(E->getArg(0), 8341 diag::note_constexpr_baa_insufficient_alignment) << 1 8342 : CCEDiag(E->getArg(0), 8343 diag::note_constexpr_baa_value_insufficient_alignment)) 8344 << (int)OffsetResult.Offset.getQuantity() 8345 << (unsigned)Align.getQuantity(); 8346 return false; 8347 } 8348 8349 return true; 8350 } 8351 case Builtin::BI__builtin_align_up: 8352 case Builtin::BI__builtin_align_down: { 8353 if (!evaluatePointer(E->getArg(0), Result)) 8354 return false; 8355 APSInt Alignment; 8356 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8357 Alignment)) 8358 return false; 8359 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8360 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8361 // For align_up/align_down, we can return the same value if the alignment 8362 // is known to be greater or equal to the requested value. 8363 if (PtrAlign.getQuantity() >= Alignment) 8364 return true; 8365 8366 // The alignment could be greater than the minimum at run-time, so we cannot 8367 // infer much about the resulting pointer value. One case is possible: 8368 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8369 // can infer the correct index if the requested alignment is smaller than 8370 // the base alignment so we can perform the computation on the offset. 8371 if (BaseAlignment.getQuantity() >= Alignment) { 8372 assert(Alignment.getBitWidth() <= 64 && 8373 "Cannot handle > 64-bit address-space"); 8374 uint64_t Alignment64 = Alignment.getZExtValue(); 8375 CharUnits NewOffset = CharUnits::fromQuantity( 8376 BuiltinOp == Builtin::BI__builtin_align_down 8377 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8378 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8379 Result.adjustOffset(NewOffset - Result.Offset); 8380 // TODO: diagnose out-of-bounds values/only allow for arrays? 8381 return true; 8382 } 8383 // Otherwise, we cannot constant-evaluate the result. 8384 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8385 << Alignment; 8386 return false; 8387 } 8388 case Builtin::BI__builtin_operator_new: 8389 return HandleOperatorNewCall(Info, E, Result); 8390 case Builtin::BI__builtin_launder: 8391 return evaluatePointer(E->getArg(0), Result); 8392 case Builtin::BIstrchr: 8393 case Builtin::BIwcschr: 8394 case Builtin::BImemchr: 8395 case Builtin::BIwmemchr: 8396 if (Info.getLangOpts().CPlusPlus11) 8397 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8398 << /*isConstexpr*/0 << /*isConstructor*/0 8399 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8400 else 8401 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8402 LLVM_FALLTHROUGH; 8403 case Builtin::BI__builtin_strchr: 8404 case Builtin::BI__builtin_wcschr: 8405 case Builtin::BI__builtin_memchr: 8406 case Builtin::BI__builtin_char_memchr: 8407 case Builtin::BI__builtin_wmemchr: { 8408 if (!Visit(E->getArg(0))) 8409 return false; 8410 APSInt Desired; 8411 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8412 return false; 8413 uint64_t MaxLength = uint64_t(-1); 8414 if (BuiltinOp != Builtin::BIstrchr && 8415 BuiltinOp != Builtin::BIwcschr && 8416 BuiltinOp != Builtin::BI__builtin_strchr && 8417 BuiltinOp != Builtin::BI__builtin_wcschr) { 8418 APSInt N; 8419 if (!EvaluateInteger(E->getArg(2), N, Info)) 8420 return false; 8421 MaxLength = N.getExtValue(); 8422 } 8423 // We cannot find the value if there are no candidates to match against. 8424 if (MaxLength == 0u) 8425 return ZeroInitialization(E); 8426 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8427 Result.Designator.Invalid) 8428 return false; 8429 QualType CharTy = Result.Designator.getType(Info.Ctx); 8430 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8431 BuiltinOp == Builtin::BI__builtin_memchr; 8432 assert(IsRawByte || 8433 Info.Ctx.hasSameUnqualifiedType( 8434 CharTy, E->getArg(0)->getType()->getPointeeType())); 8435 // Pointers to const void may point to objects of incomplete type. 8436 if (IsRawByte && CharTy->isIncompleteType()) { 8437 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8438 return false; 8439 } 8440 // Give up on byte-oriented matching against multibyte elements. 8441 // FIXME: We can compare the bytes in the correct order. 8442 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) 8443 return false; 8444 // Figure out what value we're actually looking for (after converting to 8445 // the corresponding unsigned type if necessary). 8446 uint64_t DesiredVal; 8447 bool StopAtNull = false; 8448 switch (BuiltinOp) { 8449 case Builtin::BIstrchr: 8450 case Builtin::BI__builtin_strchr: 8451 // strchr compares directly to the passed integer, and therefore 8452 // always fails if given an int that is not a char. 8453 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8454 E->getArg(1)->getType(), 8455 Desired), 8456 Desired)) 8457 return ZeroInitialization(E); 8458 StopAtNull = true; 8459 LLVM_FALLTHROUGH; 8460 case Builtin::BImemchr: 8461 case Builtin::BI__builtin_memchr: 8462 case Builtin::BI__builtin_char_memchr: 8463 // memchr compares by converting both sides to unsigned char. That's also 8464 // correct for strchr if we get this far (to cope with plain char being 8465 // unsigned in the strchr case). 8466 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8467 break; 8468 8469 case Builtin::BIwcschr: 8470 case Builtin::BI__builtin_wcschr: 8471 StopAtNull = true; 8472 LLVM_FALLTHROUGH; 8473 case Builtin::BIwmemchr: 8474 case Builtin::BI__builtin_wmemchr: 8475 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8476 DesiredVal = Desired.getZExtValue(); 8477 break; 8478 } 8479 8480 for (; MaxLength; --MaxLength) { 8481 APValue Char; 8482 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8483 !Char.isInt()) 8484 return false; 8485 if (Char.getInt().getZExtValue() == DesiredVal) 8486 return true; 8487 if (StopAtNull && !Char.getInt()) 8488 break; 8489 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8490 return false; 8491 } 8492 // Not found: return nullptr. 8493 return ZeroInitialization(E); 8494 } 8495 8496 case Builtin::BImemcpy: 8497 case Builtin::BImemmove: 8498 case Builtin::BIwmemcpy: 8499 case Builtin::BIwmemmove: 8500 if (Info.getLangOpts().CPlusPlus11) 8501 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8502 << /*isConstexpr*/0 << /*isConstructor*/0 8503 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8504 else 8505 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8506 LLVM_FALLTHROUGH; 8507 case Builtin::BI__builtin_memcpy: 8508 case Builtin::BI__builtin_memmove: 8509 case Builtin::BI__builtin_wmemcpy: 8510 case Builtin::BI__builtin_wmemmove: { 8511 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8512 BuiltinOp == Builtin::BIwmemmove || 8513 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8514 BuiltinOp == Builtin::BI__builtin_wmemmove; 8515 bool Move = BuiltinOp == Builtin::BImemmove || 8516 BuiltinOp == Builtin::BIwmemmove || 8517 BuiltinOp == Builtin::BI__builtin_memmove || 8518 BuiltinOp == Builtin::BI__builtin_wmemmove; 8519 8520 // The result of mem* is the first argument. 8521 if (!Visit(E->getArg(0))) 8522 return false; 8523 LValue Dest = Result; 8524 8525 LValue Src; 8526 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8527 return false; 8528 8529 APSInt N; 8530 if (!EvaluateInteger(E->getArg(2), N, Info)) 8531 return false; 8532 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8533 8534 // If the size is zero, we treat this as always being a valid no-op. 8535 // (Even if one of the src and dest pointers is null.) 8536 if (!N) 8537 return true; 8538 8539 // Otherwise, if either of the operands is null, we can't proceed. Don't 8540 // try to determine the type of the copied objects, because there aren't 8541 // any. 8542 if (!Src.Base || !Dest.Base) { 8543 APValue Val; 8544 (!Src.Base ? Src : Dest).moveInto(Val); 8545 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8546 << Move << WChar << !!Src.Base 8547 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8548 return false; 8549 } 8550 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8551 return false; 8552 8553 // We require that Src and Dest are both pointers to arrays of 8554 // trivially-copyable type. (For the wide version, the designator will be 8555 // invalid if the designated object is not a wchar_t.) 8556 QualType T = Dest.Designator.getType(Info.Ctx); 8557 QualType SrcT = Src.Designator.getType(Info.Ctx); 8558 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8559 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8560 return false; 8561 } 8562 if (T->isIncompleteType()) { 8563 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8564 return false; 8565 } 8566 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8567 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8568 return false; 8569 } 8570 8571 // Figure out how many T's we're copying. 8572 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8573 if (!WChar) { 8574 uint64_t Remainder; 8575 llvm::APInt OrigN = N; 8576 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8577 if (Remainder) { 8578 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8579 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8580 << (unsigned)TSize; 8581 return false; 8582 } 8583 } 8584 8585 // Check that the copying will remain within the arrays, just so that we 8586 // can give a more meaningful diagnostic. This implicitly also checks that 8587 // N fits into 64 bits. 8588 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8589 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8590 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8591 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8592 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8593 << N.toString(10, /*Signed*/false); 8594 return false; 8595 } 8596 uint64_t NElems = N.getZExtValue(); 8597 uint64_t NBytes = NElems * TSize; 8598 8599 // Check for overlap. 8600 int Direction = 1; 8601 if (HasSameBase(Src, Dest)) { 8602 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8603 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8604 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8605 // Dest is inside the source region. 8606 if (!Move) { 8607 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8608 return false; 8609 } 8610 // For memmove and friends, copy backwards. 8611 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8612 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8613 return false; 8614 Direction = -1; 8615 } else if (!Move && SrcOffset >= DestOffset && 8616 SrcOffset - DestOffset < NBytes) { 8617 // Src is inside the destination region for memcpy: invalid. 8618 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8619 return false; 8620 } 8621 } 8622 8623 while (true) { 8624 APValue Val; 8625 // FIXME: Set WantObjectRepresentation to true if we're copying a 8626 // char-like type? 8627 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 8628 !handleAssignment(Info, E, Dest, T, Val)) 8629 return false; 8630 // Do not iterate past the last element; if we're copying backwards, that 8631 // might take us off the start of the array. 8632 if (--NElems == 0) 8633 return true; 8634 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 8635 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 8636 return false; 8637 } 8638 } 8639 8640 default: 8641 break; 8642 } 8643 8644 return visitNonBuiltinCallExpr(E); 8645 } 8646 8647 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 8648 APValue &Result, const InitListExpr *ILE, 8649 QualType AllocType); 8650 8651 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 8652 if (!Info.getLangOpts().CPlusPlus2a) 8653 Info.CCEDiag(E, diag::note_constexpr_new); 8654 8655 // We cannot speculatively evaluate a delete expression. 8656 if (Info.SpeculativeEvaluationDepth) 8657 return false; 8658 8659 FunctionDecl *OperatorNew = E->getOperatorNew(); 8660 8661 bool IsNothrow = false; 8662 bool IsPlacement = false; 8663 if (OperatorNew->isReservedGlobalPlacementOperator() && 8664 Info.CurrentCall->isStdFunction() && !E->isArray()) { 8665 // FIXME Support array placement new. 8666 assert(E->getNumPlacementArgs() == 1); 8667 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 8668 return false; 8669 if (Result.Designator.Invalid) 8670 return false; 8671 IsPlacement = true; 8672 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 8673 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 8674 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 8675 return false; 8676 } else if (E->getNumPlacementArgs()) { 8677 // The only new-placement list we support is of the form (std::nothrow). 8678 // 8679 // FIXME: There is no restriction on this, but it's not clear that any 8680 // other form makes any sense. We get here for cases such as: 8681 // 8682 // new (std::align_val_t{N}) X(int) 8683 // 8684 // (which should presumably be valid only if N is a multiple of 8685 // alignof(int), and in any case can't be deallocated unless N is 8686 // alignof(X) and X has new-extended alignment). 8687 if (E->getNumPlacementArgs() != 1 || 8688 !E->getPlacementArg(0)->getType()->isNothrowT()) 8689 return Error(E, diag::note_constexpr_new_placement); 8690 8691 LValue Nothrow; 8692 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 8693 return false; 8694 IsNothrow = true; 8695 } 8696 8697 const Expr *Init = E->getInitializer(); 8698 const InitListExpr *ResizedArrayILE = nullptr; 8699 8700 QualType AllocType = E->getAllocatedType(); 8701 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 8702 const Expr *Stripped = *ArraySize; 8703 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 8704 Stripped = ICE->getSubExpr()) 8705 if (ICE->getCastKind() != CK_NoOp && 8706 ICE->getCastKind() != CK_IntegralCast) 8707 break; 8708 8709 llvm::APSInt ArrayBound; 8710 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 8711 return false; 8712 8713 // C++ [expr.new]p9: 8714 // The expression is erroneous if: 8715 // -- [...] its value before converting to size_t [or] applying the 8716 // second standard conversion sequence is less than zero 8717 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 8718 if (IsNothrow) 8719 return ZeroInitialization(E); 8720 8721 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 8722 << ArrayBound << (*ArraySize)->getSourceRange(); 8723 return false; 8724 } 8725 8726 // -- its value is such that the size of the allocated object would 8727 // exceed the implementation-defined limit 8728 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 8729 ArrayBound) > 8730 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 8731 if (IsNothrow) 8732 return ZeroInitialization(E); 8733 8734 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 8735 << ArrayBound << (*ArraySize)->getSourceRange(); 8736 return false; 8737 } 8738 8739 // -- the new-initializer is a braced-init-list and the number of 8740 // array elements for which initializers are provided [...] 8741 // exceeds the number of elements to initialize 8742 if (Init) { 8743 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 8744 assert(CAT && "unexpected type for array initializer"); 8745 8746 unsigned Bits = 8747 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 8748 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 8749 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 8750 if (InitBound.ugt(AllocBound)) { 8751 if (IsNothrow) 8752 return ZeroInitialization(E); 8753 8754 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 8755 << AllocBound.toString(10, /*Signed=*/false) 8756 << InitBound.toString(10, /*Signed=*/false) 8757 << (*ArraySize)->getSourceRange(); 8758 return false; 8759 } 8760 8761 // If the sizes differ, we must have an initializer list, and we need 8762 // special handling for this case when we initialize. 8763 if (InitBound != AllocBound) 8764 ResizedArrayILE = cast<InitListExpr>(Init); 8765 } 8766 8767 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 8768 ArrayType::Normal, 0); 8769 } else { 8770 assert(!AllocType->isArrayType() && 8771 "array allocation with non-array new"); 8772 } 8773 8774 APValue *Val; 8775 if (IsPlacement) { 8776 AccessKinds AK = AK_Construct; 8777 struct FindObjectHandler { 8778 EvalInfo &Info; 8779 const Expr *E; 8780 QualType AllocType; 8781 const AccessKinds AccessKind; 8782 APValue *Value; 8783 8784 typedef bool result_type; 8785 bool failed() { return false; } 8786 bool found(APValue &Subobj, QualType SubobjType) { 8787 // FIXME: Reject the cases where [basic.life]p8 would not permit the 8788 // old name of the object to be used to name the new object. 8789 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 8790 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 8791 SubobjType << AllocType; 8792 return false; 8793 } 8794 Value = &Subobj; 8795 return true; 8796 } 8797 bool found(APSInt &Value, QualType SubobjType) { 8798 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 8799 return false; 8800 } 8801 bool found(APFloat &Value, QualType SubobjType) { 8802 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 8803 return false; 8804 } 8805 } Handler = {Info, E, AllocType, AK, nullptr}; 8806 8807 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 8808 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 8809 return false; 8810 8811 Val = Handler.Value; 8812 8813 // [basic.life]p1: 8814 // The lifetime of an object o of type T ends when [...] the storage 8815 // which the object occupies is [...] reused by an object that is not 8816 // nested within o (6.6.2). 8817 *Val = APValue(); 8818 } else { 8819 // Perform the allocation and obtain a pointer to the resulting object. 8820 Val = Info.createHeapAlloc(E, AllocType, Result); 8821 if (!Val) 8822 return false; 8823 } 8824 8825 if (ResizedArrayILE) { 8826 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 8827 AllocType)) 8828 return false; 8829 } else if (Init) { 8830 if (!EvaluateInPlace(*Val, Info, Result, Init)) 8831 return false; 8832 } else { 8833 *Val = getDefaultInitValue(AllocType); 8834 } 8835 8836 // Array new returns a pointer to the first element, not a pointer to the 8837 // array. 8838 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 8839 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 8840 8841 return true; 8842 } 8843 //===----------------------------------------------------------------------===// 8844 // Member Pointer Evaluation 8845 //===----------------------------------------------------------------------===// 8846 8847 namespace { 8848 class MemberPointerExprEvaluator 8849 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 8850 MemberPtr &Result; 8851 8852 bool Success(const ValueDecl *D) { 8853 Result = MemberPtr(D); 8854 return true; 8855 } 8856 public: 8857 8858 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 8859 : ExprEvaluatorBaseTy(Info), Result(Result) {} 8860 8861 bool Success(const APValue &V, const Expr *E) { 8862 Result.setFrom(V); 8863 return true; 8864 } 8865 bool ZeroInitialization(const Expr *E) { 8866 return Success((const ValueDecl*)nullptr); 8867 } 8868 8869 bool VisitCastExpr(const CastExpr *E); 8870 bool VisitUnaryAddrOf(const UnaryOperator *E); 8871 }; 8872 } // end anonymous namespace 8873 8874 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 8875 EvalInfo &Info) { 8876 assert(E->isRValue() && E->getType()->isMemberPointerType()); 8877 return MemberPointerExprEvaluator(Info, Result).Visit(E); 8878 } 8879 8880 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8881 switch (E->getCastKind()) { 8882 default: 8883 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8884 8885 case CK_NullToMemberPointer: 8886 VisitIgnoredValue(E->getSubExpr()); 8887 return ZeroInitialization(E); 8888 8889 case CK_BaseToDerivedMemberPointer: { 8890 if (!Visit(E->getSubExpr())) 8891 return false; 8892 if (E->path_empty()) 8893 return true; 8894 // Base-to-derived member pointer casts store the path in derived-to-base 8895 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 8896 // the wrong end of the derived->base arc, so stagger the path by one class. 8897 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 8898 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 8899 PathI != PathE; ++PathI) { 8900 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 8901 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 8902 if (!Result.castToDerived(Derived)) 8903 return Error(E); 8904 } 8905 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 8906 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 8907 return Error(E); 8908 return true; 8909 } 8910 8911 case CK_DerivedToBaseMemberPointer: 8912 if (!Visit(E->getSubExpr())) 8913 return false; 8914 for (CastExpr::path_const_iterator PathI = E->path_begin(), 8915 PathE = E->path_end(); PathI != PathE; ++PathI) { 8916 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 8917 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 8918 if (!Result.castToBase(Base)) 8919 return Error(E); 8920 } 8921 return true; 8922 } 8923 } 8924 8925 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8926 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 8927 // member can be formed. 8928 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 8929 } 8930 8931 //===----------------------------------------------------------------------===// 8932 // Record Evaluation 8933 //===----------------------------------------------------------------------===// 8934 8935 namespace { 8936 class RecordExprEvaluator 8937 : public ExprEvaluatorBase<RecordExprEvaluator> { 8938 const LValue &This; 8939 APValue &Result; 8940 public: 8941 8942 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 8943 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 8944 8945 bool Success(const APValue &V, const Expr *E) { 8946 Result = V; 8947 return true; 8948 } 8949 bool ZeroInitialization(const Expr *E) { 8950 return ZeroInitialization(E, E->getType()); 8951 } 8952 bool ZeroInitialization(const Expr *E, QualType T); 8953 8954 bool VisitCallExpr(const CallExpr *E) { 8955 return handleCallExpr(E, Result, &This); 8956 } 8957 bool VisitCastExpr(const CastExpr *E); 8958 bool VisitInitListExpr(const InitListExpr *E); 8959 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 8960 return VisitCXXConstructExpr(E, E->getType()); 8961 } 8962 bool VisitLambdaExpr(const LambdaExpr *E); 8963 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 8964 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 8965 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 8966 bool VisitBinCmp(const BinaryOperator *E); 8967 }; 8968 } 8969 8970 /// Perform zero-initialization on an object of non-union class type. 8971 /// C++11 [dcl.init]p5: 8972 /// To zero-initialize an object or reference of type T means: 8973 /// [...] 8974 /// -- if T is a (possibly cv-qualified) non-union class type, 8975 /// each non-static data member and each base-class subobject is 8976 /// zero-initialized 8977 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 8978 const RecordDecl *RD, 8979 const LValue &This, APValue &Result) { 8980 assert(!RD->isUnion() && "Expected non-union class type"); 8981 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 8982 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 8983 std::distance(RD->field_begin(), RD->field_end())); 8984 8985 if (RD->isInvalidDecl()) return false; 8986 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 8987 8988 if (CD) { 8989 unsigned Index = 0; 8990 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 8991 End = CD->bases_end(); I != End; ++I, ++Index) { 8992 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 8993 LValue Subobject = This; 8994 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 8995 return false; 8996 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 8997 Result.getStructBase(Index))) 8998 return false; 8999 } 9000 } 9001 9002 for (const auto *I : RD->fields()) { 9003 // -- if T is a reference type, no initialization is performed. 9004 if (I->getType()->isReferenceType()) 9005 continue; 9006 9007 LValue Subobject = This; 9008 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9009 return false; 9010 9011 ImplicitValueInitExpr VIE(I->getType()); 9012 if (!EvaluateInPlace( 9013 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9014 return false; 9015 } 9016 9017 return true; 9018 } 9019 9020 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9021 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9022 if (RD->isInvalidDecl()) return false; 9023 if (RD->isUnion()) { 9024 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9025 // object's first non-static named data member is zero-initialized 9026 RecordDecl::field_iterator I = RD->field_begin(); 9027 if (I == RD->field_end()) { 9028 Result = APValue((const FieldDecl*)nullptr); 9029 return true; 9030 } 9031 9032 LValue Subobject = This; 9033 if (!HandleLValueMember(Info, E, Subobject, *I)) 9034 return false; 9035 Result = APValue(*I); 9036 ImplicitValueInitExpr VIE(I->getType()); 9037 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9038 } 9039 9040 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9041 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9042 return false; 9043 } 9044 9045 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9046 } 9047 9048 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9049 switch (E->getCastKind()) { 9050 default: 9051 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9052 9053 case CK_ConstructorConversion: 9054 return Visit(E->getSubExpr()); 9055 9056 case CK_DerivedToBase: 9057 case CK_UncheckedDerivedToBase: { 9058 APValue DerivedObject; 9059 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9060 return false; 9061 if (!DerivedObject.isStruct()) 9062 return Error(E->getSubExpr()); 9063 9064 // Derived-to-base rvalue conversion: just slice off the derived part. 9065 APValue *Value = &DerivedObject; 9066 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9067 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9068 PathE = E->path_end(); PathI != PathE; ++PathI) { 9069 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9070 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9071 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9072 RD = Base; 9073 } 9074 Result = *Value; 9075 return true; 9076 } 9077 } 9078 } 9079 9080 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9081 if (E->isTransparent()) 9082 return Visit(E->getInit(0)); 9083 9084 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9085 if (RD->isInvalidDecl()) return false; 9086 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9087 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9088 9089 EvalInfo::EvaluatingConstructorRAII EvalObj( 9090 Info, 9091 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9092 CXXRD && CXXRD->getNumBases()); 9093 9094 if (RD->isUnion()) { 9095 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9096 Result = APValue(Field); 9097 if (!Field) 9098 return true; 9099 9100 // If the initializer list for a union does not contain any elements, the 9101 // first element of the union is value-initialized. 9102 // FIXME: The element should be initialized from an initializer list. 9103 // Is this difference ever observable for initializer lists which 9104 // we don't build? 9105 ImplicitValueInitExpr VIE(Field->getType()); 9106 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9107 9108 LValue Subobject = This; 9109 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9110 return false; 9111 9112 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9113 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9114 isa<CXXDefaultInitExpr>(InitExpr)); 9115 9116 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9117 } 9118 9119 if (!Result.hasValue()) 9120 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9121 std::distance(RD->field_begin(), RD->field_end())); 9122 unsigned ElementNo = 0; 9123 bool Success = true; 9124 9125 // Initialize base classes. 9126 if (CXXRD && CXXRD->getNumBases()) { 9127 for (const auto &Base : CXXRD->bases()) { 9128 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9129 const Expr *Init = E->getInit(ElementNo); 9130 9131 LValue Subobject = This; 9132 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9133 return false; 9134 9135 APValue &FieldVal = Result.getStructBase(ElementNo); 9136 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9137 if (!Info.noteFailure()) 9138 return false; 9139 Success = false; 9140 } 9141 ++ElementNo; 9142 } 9143 9144 EvalObj.finishedConstructingBases(); 9145 } 9146 9147 // Initialize members. 9148 for (const auto *Field : RD->fields()) { 9149 // Anonymous bit-fields are not considered members of the class for 9150 // purposes of aggregate initialization. 9151 if (Field->isUnnamedBitfield()) 9152 continue; 9153 9154 LValue Subobject = This; 9155 9156 bool HaveInit = ElementNo < E->getNumInits(); 9157 9158 // FIXME: Diagnostics here should point to the end of the initializer 9159 // list, not the start. 9160 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9161 Subobject, Field, &Layout)) 9162 return false; 9163 9164 // Perform an implicit value-initialization for members beyond the end of 9165 // the initializer list. 9166 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9167 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9168 9169 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9170 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9171 isa<CXXDefaultInitExpr>(Init)); 9172 9173 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9174 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9175 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9176 FieldVal, Field))) { 9177 if (!Info.noteFailure()) 9178 return false; 9179 Success = false; 9180 } 9181 } 9182 9183 return Success; 9184 } 9185 9186 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9187 QualType T) { 9188 // Note that E's type is not necessarily the type of our class here; we might 9189 // be initializing an array element instead. 9190 const CXXConstructorDecl *FD = E->getConstructor(); 9191 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9192 9193 bool ZeroInit = E->requiresZeroInitialization(); 9194 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9195 // If we've already performed zero-initialization, we're already done. 9196 if (Result.hasValue()) 9197 return true; 9198 9199 if (ZeroInit) 9200 return ZeroInitialization(E, T); 9201 9202 Result = getDefaultInitValue(T); 9203 return true; 9204 } 9205 9206 const FunctionDecl *Definition = nullptr; 9207 auto Body = FD->getBody(Definition); 9208 9209 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9210 return false; 9211 9212 // Avoid materializing a temporary for an elidable copy/move constructor. 9213 if (E->isElidable() && !ZeroInit) 9214 if (const MaterializeTemporaryExpr *ME 9215 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9216 return Visit(ME->getSubExpr()); 9217 9218 if (ZeroInit && !ZeroInitialization(E, T)) 9219 return false; 9220 9221 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9222 return HandleConstructorCall(E, This, Args, 9223 cast<CXXConstructorDecl>(Definition), Info, 9224 Result); 9225 } 9226 9227 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9228 const CXXInheritedCtorInitExpr *E) { 9229 if (!Info.CurrentCall) { 9230 assert(Info.checkingPotentialConstantExpression()); 9231 return false; 9232 } 9233 9234 const CXXConstructorDecl *FD = E->getConstructor(); 9235 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9236 return false; 9237 9238 const FunctionDecl *Definition = nullptr; 9239 auto Body = FD->getBody(Definition); 9240 9241 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9242 return false; 9243 9244 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9245 cast<CXXConstructorDecl>(Definition), Info, 9246 Result); 9247 } 9248 9249 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9250 const CXXStdInitializerListExpr *E) { 9251 const ConstantArrayType *ArrayType = 9252 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9253 9254 LValue Array; 9255 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9256 return false; 9257 9258 // Get a pointer to the first element of the array. 9259 Array.addArray(Info, E, ArrayType); 9260 9261 // FIXME: Perform the checks on the field types in SemaInit. 9262 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9263 RecordDecl::field_iterator Field = Record->field_begin(); 9264 if (Field == Record->field_end()) 9265 return Error(E); 9266 9267 // Start pointer. 9268 if (!Field->getType()->isPointerType() || 9269 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9270 ArrayType->getElementType())) 9271 return Error(E); 9272 9273 // FIXME: What if the initializer_list type has base classes, etc? 9274 Result = APValue(APValue::UninitStruct(), 0, 2); 9275 Array.moveInto(Result.getStructField(0)); 9276 9277 if (++Field == Record->field_end()) 9278 return Error(E); 9279 9280 if (Field->getType()->isPointerType() && 9281 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9282 ArrayType->getElementType())) { 9283 // End pointer. 9284 if (!HandleLValueArrayAdjustment(Info, E, Array, 9285 ArrayType->getElementType(), 9286 ArrayType->getSize().getZExtValue())) 9287 return false; 9288 Array.moveInto(Result.getStructField(1)); 9289 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9290 // Length. 9291 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9292 else 9293 return Error(E); 9294 9295 if (++Field != Record->field_end()) 9296 return Error(E); 9297 9298 return true; 9299 } 9300 9301 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9302 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9303 if (ClosureClass->isInvalidDecl()) 9304 return false; 9305 9306 const size_t NumFields = 9307 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9308 9309 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9310 E->capture_init_end()) && 9311 "The number of lambda capture initializers should equal the number of " 9312 "fields within the closure type"); 9313 9314 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9315 // Iterate through all the lambda's closure object's fields and initialize 9316 // them. 9317 auto *CaptureInitIt = E->capture_init_begin(); 9318 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9319 bool Success = true; 9320 for (const auto *Field : ClosureClass->fields()) { 9321 assert(CaptureInitIt != E->capture_init_end()); 9322 // Get the initializer for this field 9323 Expr *const CurFieldInit = *CaptureInitIt++; 9324 9325 // If there is no initializer, either this is a VLA or an error has 9326 // occurred. 9327 if (!CurFieldInit) 9328 return Error(E); 9329 9330 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9331 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9332 if (!Info.keepEvaluatingAfterFailure()) 9333 return false; 9334 Success = false; 9335 } 9336 ++CaptureIt; 9337 } 9338 return Success; 9339 } 9340 9341 static bool EvaluateRecord(const Expr *E, const LValue &This, 9342 APValue &Result, EvalInfo &Info) { 9343 assert(E->isRValue() && E->getType()->isRecordType() && 9344 "can't evaluate expression as a record rvalue"); 9345 return RecordExprEvaluator(Info, This, Result).Visit(E); 9346 } 9347 9348 //===----------------------------------------------------------------------===// 9349 // Temporary Evaluation 9350 // 9351 // Temporaries are represented in the AST as rvalues, but generally behave like 9352 // lvalues. The full-object of which the temporary is a subobject is implicitly 9353 // materialized so that a reference can bind to it. 9354 //===----------------------------------------------------------------------===// 9355 namespace { 9356 class TemporaryExprEvaluator 9357 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9358 public: 9359 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9360 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9361 9362 /// Visit an expression which constructs the value of this temporary. 9363 bool VisitConstructExpr(const Expr *E) { 9364 APValue &Value = 9365 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9366 return EvaluateInPlace(Value, Info, Result, E); 9367 } 9368 9369 bool VisitCastExpr(const CastExpr *E) { 9370 switch (E->getCastKind()) { 9371 default: 9372 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9373 9374 case CK_ConstructorConversion: 9375 return VisitConstructExpr(E->getSubExpr()); 9376 } 9377 } 9378 bool VisitInitListExpr(const InitListExpr *E) { 9379 return VisitConstructExpr(E); 9380 } 9381 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9382 return VisitConstructExpr(E); 9383 } 9384 bool VisitCallExpr(const CallExpr *E) { 9385 return VisitConstructExpr(E); 9386 } 9387 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9388 return VisitConstructExpr(E); 9389 } 9390 bool VisitLambdaExpr(const LambdaExpr *E) { 9391 return VisitConstructExpr(E); 9392 } 9393 }; 9394 } // end anonymous namespace 9395 9396 /// Evaluate an expression of record type as a temporary. 9397 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9398 assert(E->isRValue() && E->getType()->isRecordType()); 9399 return TemporaryExprEvaluator(Info, Result).Visit(E); 9400 } 9401 9402 //===----------------------------------------------------------------------===// 9403 // Vector Evaluation 9404 //===----------------------------------------------------------------------===// 9405 9406 namespace { 9407 class VectorExprEvaluator 9408 : public ExprEvaluatorBase<VectorExprEvaluator> { 9409 APValue &Result; 9410 public: 9411 9412 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9413 : ExprEvaluatorBaseTy(info), Result(Result) {} 9414 9415 bool Success(ArrayRef<APValue> V, const Expr *E) { 9416 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9417 // FIXME: remove this APValue copy. 9418 Result = APValue(V.data(), V.size()); 9419 return true; 9420 } 9421 bool Success(const APValue &V, const Expr *E) { 9422 assert(V.isVector()); 9423 Result = V; 9424 return true; 9425 } 9426 bool ZeroInitialization(const Expr *E); 9427 9428 bool VisitUnaryReal(const UnaryOperator *E) 9429 { return Visit(E->getSubExpr()); } 9430 bool VisitCastExpr(const CastExpr* E); 9431 bool VisitInitListExpr(const InitListExpr *E); 9432 bool VisitUnaryImag(const UnaryOperator *E); 9433 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 9434 // binary comparisons, binary and/or/xor, 9435 // conditional operator (for GNU conditional select), 9436 // shufflevector, ExtVectorElementExpr 9437 }; 9438 } // end anonymous namespace 9439 9440 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9441 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9442 return VectorExprEvaluator(Info, Result).Visit(E); 9443 } 9444 9445 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9446 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9447 unsigned NElts = VTy->getNumElements(); 9448 9449 const Expr *SE = E->getSubExpr(); 9450 QualType SETy = SE->getType(); 9451 9452 switch (E->getCastKind()) { 9453 case CK_VectorSplat: { 9454 APValue Val = APValue(); 9455 if (SETy->isIntegerType()) { 9456 APSInt IntResult; 9457 if (!EvaluateInteger(SE, IntResult, Info)) 9458 return false; 9459 Val = APValue(std::move(IntResult)); 9460 } else if (SETy->isRealFloatingType()) { 9461 APFloat FloatResult(0.0); 9462 if (!EvaluateFloat(SE, FloatResult, Info)) 9463 return false; 9464 Val = APValue(std::move(FloatResult)); 9465 } else { 9466 return Error(E); 9467 } 9468 9469 // Splat and create vector APValue. 9470 SmallVector<APValue, 4> Elts(NElts, Val); 9471 return Success(Elts, E); 9472 } 9473 case CK_BitCast: { 9474 // Evaluate the operand into an APInt we can extract from. 9475 llvm::APInt SValInt; 9476 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9477 return false; 9478 // Extract the elements 9479 QualType EltTy = VTy->getElementType(); 9480 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9481 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9482 SmallVector<APValue, 4> Elts; 9483 if (EltTy->isRealFloatingType()) { 9484 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9485 unsigned FloatEltSize = EltSize; 9486 if (&Sem == &APFloat::x87DoubleExtended()) 9487 FloatEltSize = 80; 9488 for (unsigned i = 0; i < NElts; i++) { 9489 llvm::APInt Elt; 9490 if (BigEndian) 9491 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9492 else 9493 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9494 Elts.push_back(APValue(APFloat(Sem, Elt))); 9495 } 9496 } else if (EltTy->isIntegerType()) { 9497 for (unsigned i = 0; i < NElts; i++) { 9498 llvm::APInt Elt; 9499 if (BigEndian) 9500 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9501 else 9502 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9503 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9504 } 9505 } else { 9506 return Error(E); 9507 } 9508 return Success(Elts, E); 9509 } 9510 default: 9511 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9512 } 9513 } 9514 9515 bool 9516 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9517 const VectorType *VT = E->getType()->castAs<VectorType>(); 9518 unsigned NumInits = E->getNumInits(); 9519 unsigned NumElements = VT->getNumElements(); 9520 9521 QualType EltTy = VT->getElementType(); 9522 SmallVector<APValue, 4> Elements; 9523 9524 // The number of initializers can be less than the number of 9525 // vector elements. For OpenCL, this can be due to nested vector 9526 // initialization. For GCC compatibility, missing trailing elements 9527 // should be initialized with zeroes. 9528 unsigned CountInits = 0, CountElts = 0; 9529 while (CountElts < NumElements) { 9530 // Handle nested vector initialization. 9531 if (CountInits < NumInits 9532 && E->getInit(CountInits)->getType()->isVectorType()) { 9533 APValue v; 9534 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9535 return Error(E); 9536 unsigned vlen = v.getVectorLength(); 9537 for (unsigned j = 0; j < vlen; j++) 9538 Elements.push_back(v.getVectorElt(j)); 9539 CountElts += vlen; 9540 } else if (EltTy->isIntegerType()) { 9541 llvm::APSInt sInt(32); 9542 if (CountInits < NumInits) { 9543 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9544 return false; 9545 } else // trailing integer zero. 9546 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9547 Elements.push_back(APValue(sInt)); 9548 CountElts++; 9549 } else { 9550 llvm::APFloat f(0.0); 9551 if (CountInits < NumInits) { 9552 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9553 return false; 9554 } else // trailing float zero. 9555 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9556 Elements.push_back(APValue(f)); 9557 CountElts++; 9558 } 9559 CountInits++; 9560 } 9561 return Success(Elements, E); 9562 } 9563 9564 bool 9565 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9566 const auto *VT = E->getType()->castAs<VectorType>(); 9567 QualType EltTy = VT->getElementType(); 9568 APValue ZeroElement; 9569 if (EltTy->isIntegerType()) 9570 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9571 else 9572 ZeroElement = 9573 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9574 9575 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9576 return Success(Elements, E); 9577 } 9578 9579 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9580 VisitIgnoredValue(E->getSubExpr()); 9581 return ZeroInitialization(E); 9582 } 9583 9584 //===----------------------------------------------------------------------===// 9585 // Array Evaluation 9586 //===----------------------------------------------------------------------===// 9587 9588 namespace { 9589 class ArrayExprEvaluator 9590 : public ExprEvaluatorBase<ArrayExprEvaluator> { 9591 const LValue &This; 9592 APValue &Result; 9593 public: 9594 9595 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 9596 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9597 9598 bool Success(const APValue &V, const Expr *E) { 9599 assert(V.isArray() && "expected array"); 9600 Result = V; 9601 return true; 9602 } 9603 9604 bool ZeroInitialization(const Expr *E) { 9605 const ConstantArrayType *CAT = 9606 Info.Ctx.getAsConstantArrayType(E->getType()); 9607 if (!CAT) 9608 return Error(E); 9609 9610 Result = APValue(APValue::UninitArray(), 0, 9611 CAT->getSize().getZExtValue()); 9612 if (!Result.hasArrayFiller()) return true; 9613 9614 // Zero-initialize all elements. 9615 LValue Subobject = This; 9616 Subobject.addArray(Info, E, CAT); 9617 ImplicitValueInitExpr VIE(CAT->getElementType()); 9618 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 9619 } 9620 9621 bool VisitCallExpr(const CallExpr *E) { 9622 return handleCallExpr(E, Result, &This); 9623 } 9624 bool VisitInitListExpr(const InitListExpr *E, 9625 QualType AllocType = QualType()); 9626 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 9627 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 9628 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 9629 const LValue &Subobject, 9630 APValue *Value, QualType Type); 9631 bool VisitStringLiteral(const StringLiteral *E, 9632 QualType AllocType = QualType()) { 9633 expandStringLiteral(Info, E, Result, AllocType); 9634 return true; 9635 } 9636 }; 9637 } // end anonymous namespace 9638 9639 static bool EvaluateArray(const Expr *E, const LValue &This, 9640 APValue &Result, EvalInfo &Info) { 9641 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 9642 return ArrayExprEvaluator(Info, This, Result).Visit(E); 9643 } 9644 9645 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9646 APValue &Result, const InitListExpr *ILE, 9647 QualType AllocType) { 9648 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 9649 "not an array rvalue"); 9650 return ArrayExprEvaluator(Info, This, Result) 9651 .VisitInitListExpr(ILE, AllocType); 9652 } 9653 9654 // Return true iff the given array filler may depend on the element index. 9655 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 9656 // For now, just whitelist non-class value-initialization and initialization 9657 // lists comprised of them. 9658 if (isa<ImplicitValueInitExpr>(FillerExpr)) 9659 return false; 9660 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 9661 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 9662 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 9663 return true; 9664 } 9665 return false; 9666 } 9667 return true; 9668 } 9669 9670 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 9671 QualType AllocType) { 9672 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 9673 AllocType.isNull() ? E->getType() : AllocType); 9674 if (!CAT) 9675 return Error(E); 9676 9677 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 9678 // an appropriately-typed string literal enclosed in braces. 9679 if (E->isStringLiteralInit()) { 9680 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 9681 // FIXME: Support ObjCEncodeExpr here once we support it in 9682 // ArrayExprEvaluator generally. 9683 if (!SL) 9684 return Error(E); 9685 return VisitStringLiteral(SL, AllocType); 9686 } 9687 9688 bool Success = true; 9689 9690 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 9691 "zero-initialized array shouldn't have any initialized elts"); 9692 APValue Filler; 9693 if (Result.isArray() && Result.hasArrayFiller()) 9694 Filler = Result.getArrayFiller(); 9695 9696 unsigned NumEltsToInit = E->getNumInits(); 9697 unsigned NumElts = CAT->getSize().getZExtValue(); 9698 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 9699 9700 // If the initializer might depend on the array index, run it for each 9701 // array element. 9702 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 9703 NumEltsToInit = NumElts; 9704 9705 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 9706 << NumEltsToInit << ".\n"); 9707 9708 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 9709 9710 // If the array was previously zero-initialized, preserve the 9711 // zero-initialized values. 9712 if (Filler.hasValue()) { 9713 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 9714 Result.getArrayInitializedElt(I) = Filler; 9715 if (Result.hasArrayFiller()) 9716 Result.getArrayFiller() = Filler; 9717 } 9718 9719 LValue Subobject = This; 9720 Subobject.addArray(Info, E, CAT); 9721 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 9722 const Expr *Init = 9723 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 9724 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 9725 Info, Subobject, Init) || 9726 !HandleLValueArrayAdjustment(Info, Init, Subobject, 9727 CAT->getElementType(), 1)) { 9728 if (!Info.noteFailure()) 9729 return false; 9730 Success = false; 9731 } 9732 } 9733 9734 if (!Result.hasArrayFiller()) 9735 return Success; 9736 9737 // If we get here, we have a trivial filler, which we can just evaluate 9738 // once and splat over the rest of the array elements. 9739 assert(FillerExpr && "no array filler for incomplete init list"); 9740 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 9741 FillerExpr) && Success; 9742 } 9743 9744 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 9745 LValue CommonLV; 9746 if (E->getCommonExpr() && 9747 !Evaluate(Info.CurrentCall->createTemporary( 9748 E->getCommonExpr(), 9749 getStorageType(Info.Ctx, E->getCommonExpr()), false, 9750 CommonLV), 9751 Info, E->getCommonExpr()->getSourceExpr())) 9752 return false; 9753 9754 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 9755 9756 uint64_t Elements = CAT->getSize().getZExtValue(); 9757 Result = APValue(APValue::UninitArray(), Elements, Elements); 9758 9759 LValue Subobject = This; 9760 Subobject.addArray(Info, E, CAT); 9761 9762 bool Success = true; 9763 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 9764 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 9765 Info, Subobject, E->getSubExpr()) || 9766 !HandleLValueArrayAdjustment(Info, E, Subobject, 9767 CAT->getElementType(), 1)) { 9768 if (!Info.noteFailure()) 9769 return false; 9770 Success = false; 9771 } 9772 } 9773 9774 return Success; 9775 } 9776 9777 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 9778 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 9779 } 9780 9781 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9782 const LValue &Subobject, 9783 APValue *Value, 9784 QualType Type) { 9785 bool HadZeroInit = Value->hasValue(); 9786 9787 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 9788 unsigned N = CAT->getSize().getZExtValue(); 9789 9790 // Preserve the array filler if we had prior zero-initialization. 9791 APValue Filler = 9792 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 9793 : APValue(); 9794 9795 *Value = APValue(APValue::UninitArray(), N, N); 9796 9797 if (HadZeroInit) 9798 for (unsigned I = 0; I != N; ++I) 9799 Value->getArrayInitializedElt(I) = Filler; 9800 9801 // Initialize the elements. 9802 LValue ArrayElt = Subobject; 9803 ArrayElt.addArray(Info, E, CAT); 9804 for (unsigned I = 0; I != N; ++I) 9805 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 9806 CAT->getElementType()) || 9807 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 9808 CAT->getElementType(), 1)) 9809 return false; 9810 9811 return true; 9812 } 9813 9814 if (!Type->isRecordType()) 9815 return Error(E); 9816 9817 return RecordExprEvaluator(Info, Subobject, *Value) 9818 .VisitCXXConstructExpr(E, Type); 9819 } 9820 9821 //===----------------------------------------------------------------------===// 9822 // Integer Evaluation 9823 // 9824 // As a GNU extension, we support casting pointers to sufficiently-wide integer 9825 // types and back in constant folding. Integer values are thus represented 9826 // either as an integer-valued APValue, or as an lvalue-valued APValue. 9827 //===----------------------------------------------------------------------===// 9828 9829 namespace { 9830 class IntExprEvaluator 9831 : public ExprEvaluatorBase<IntExprEvaluator> { 9832 APValue &Result; 9833 public: 9834 IntExprEvaluator(EvalInfo &info, APValue &result) 9835 : ExprEvaluatorBaseTy(info), Result(result) {} 9836 9837 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 9838 assert(E->getType()->isIntegralOrEnumerationType() && 9839 "Invalid evaluation result."); 9840 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 9841 "Invalid evaluation result."); 9842 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 9843 "Invalid evaluation result."); 9844 Result = APValue(SI); 9845 return true; 9846 } 9847 bool Success(const llvm::APSInt &SI, const Expr *E) { 9848 return Success(SI, E, Result); 9849 } 9850 9851 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 9852 assert(E->getType()->isIntegralOrEnumerationType() && 9853 "Invalid evaluation result."); 9854 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 9855 "Invalid evaluation result."); 9856 Result = APValue(APSInt(I)); 9857 Result.getInt().setIsUnsigned( 9858 E->getType()->isUnsignedIntegerOrEnumerationType()); 9859 return true; 9860 } 9861 bool Success(const llvm::APInt &I, const Expr *E) { 9862 return Success(I, E, Result); 9863 } 9864 9865 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 9866 assert(E->getType()->isIntegralOrEnumerationType() && 9867 "Invalid evaluation result."); 9868 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 9869 return true; 9870 } 9871 bool Success(uint64_t Value, const Expr *E) { 9872 return Success(Value, E, Result); 9873 } 9874 9875 bool Success(CharUnits Size, const Expr *E) { 9876 return Success(Size.getQuantity(), E); 9877 } 9878 9879 bool Success(const APValue &V, const Expr *E) { 9880 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 9881 Result = V; 9882 return true; 9883 } 9884 return Success(V.getInt(), E); 9885 } 9886 9887 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 9888 9889 //===--------------------------------------------------------------------===// 9890 // Visitor Methods 9891 //===--------------------------------------------------------------------===// 9892 9893 bool VisitConstantExpr(const ConstantExpr *E); 9894 9895 bool VisitIntegerLiteral(const IntegerLiteral *E) { 9896 return Success(E->getValue(), E); 9897 } 9898 bool VisitCharacterLiteral(const CharacterLiteral *E) { 9899 return Success(E->getValue(), E); 9900 } 9901 9902 bool CheckReferencedDecl(const Expr *E, const Decl *D); 9903 bool VisitDeclRefExpr(const DeclRefExpr *E) { 9904 if (CheckReferencedDecl(E, E->getDecl())) 9905 return true; 9906 9907 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 9908 } 9909 bool VisitMemberExpr(const MemberExpr *E) { 9910 if (CheckReferencedDecl(E, E->getMemberDecl())) { 9911 VisitIgnoredBaseExpression(E->getBase()); 9912 return true; 9913 } 9914 9915 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 9916 } 9917 9918 bool VisitCallExpr(const CallExpr *E); 9919 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 9920 bool VisitBinaryOperator(const BinaryOperator *E); 9921 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 9922 bool VisitUnaryOperator(const UnaryOperator *E); 9923 9924 bool VisitCastExpr(const CastExpr* E); 9925 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 9926 9927 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 9928 return Success(E->getValue(), E); 9929 } 9930 9931 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 9932 return Success(E->getValue(), E); 9933 } 9934 9935 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 9936 if (Info.ArrayInitIndex == uint64_t(-1)) { 9937 // We were asked to evaluate this subexpression independent of the 9938 // enclosing ArrayInitLoopExpr. We can't do that. 9939 Info.FFDiag(E); 9940 return false; 9941 } 9942 return Success(Info.ArrayInitIndex, E); 9943 } 9944 9945 // Note, GNU defines __null as an integer, not a pointer. 9946 bool VisitGNUNullExpr(const GNUNullExpr *E) { 9947 return ZeroInitialization(E); 9948 } 9949 9950 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 9951 return Success(E->getValue(), E); 9952 } 9953 9954 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 9955 return Success(E->getValue(), E); 9956 } 9957 9958 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 9959 return Success(E->getValue(), E); 9960 } 9961 9962 bool VisitUnaryReal(const UnaryOperator *E); 9963 bool VisitUnaryImag(const UnaryOperator *E); 9964 9965 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 9966 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 9967 bool VisitSourceLocExpr(const SourceLocExpr *E); 9968 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 9969 bool VisitRequiresExpr(const RequiresExpr *E); 9970 // FIXME: Missing: array subscript of vector, member of vector 9971 }; 9972 9973 class FixedPointExprEvaluator 9974 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 9975 APValue &Result; 9976 9977 public: 9978 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 9979 : ExprEvaluatorBaseTy(info), Result(result) {} 9980 9981 bool Success(const llvm::APInt &I, const Expr *E) { 9982 return Success( 9983 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 9984 } 9985 9986 bool Success(uint64_t Value, const Expr *E) { 9987 return Success( 9988 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 9989 } 9990 9991 bool Success(const APValue &V, const Expr *E) { 9992 return Success(V.getFixedPoint(), E); 9993 } 9994 9995 bool Success(const APFixedPoint &V, const Expr *E) { 9996 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 9997 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 9998 "Invalid evaluation result."); 9999 Result = APValue(V); 10000 return true; 10001 } 10002 10003 //===--------------------------------------------------------------------===// 10004 // Visitor Methods 10005 //===--------------------------------------------------------------------===// 10006 10007 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10008 return Success(E->getValue(), E); 10009 } 10010 10011 bool VisitCastExpr(const CastExpr *E); 10012 bool VisitUnaryOperator(const UnaryOperator *E); 10013 bool VisitBinaryOperator(const BinaryOperator *E); 10014 }; 10015 } // end anonymous namespace 10016 10017 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10018 /// produce either the integer value or a pointer. 10019 /// 10020 /// GCC has a heinous extension which folds casts between pointer types and 10021 /// pointer-sized integral types. We support this by allowing the evaluation of 10022 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10023 /// Some simple arithmetic on such values is supported (they are treated much 10024 /// like char*). 10025 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10026 EvalInfo &Info) { 10027 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10028 return IntExprEvaluator(Info, Result).Visit(E); 10029 } 10030 10031 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10032 APValue Val; 10033 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10034 return false; 10035 if (!Val.isInt()) { 10036 // FIXME: It would be better to produce the diagnostic for casting 10037 // a pointer to an integer. 10038 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10039 return false; 10040 } 10041 Result = Val.getInt(); 10042 return true; 10043 } 10044 10045 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10046 APValue Evaluated = E->EvaluateInContext( 10047 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10048 return Success(Evaluated, E); 10049 } 10050 10051 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10052 EvalInfo &Info) { 10053 if (E->getType()->isFixedPointType()) { 10054 APValue Val; 10055 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10056 return false; 10057 if (!Val.isFixedPoint()) 10058 return false; 10059 10060 Result = Val.getFixedPoint(); 10061 return true; 10062 } 10063 return false; 10064 } 10065 10066 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10067 EvalInfo &Info) { 10068 if (E->getType()->isIntegerType()) { 10069 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10070 APSInt Val; 10071 if (!EvaluateInteger(E, Val, Info)) 10072 return false; 10073 Result = APFixedPoint(Val, FXSema); 10074 return true; 10075 } else if (E->getType()->isFixedPointType()) { 10076 return EvaluateFixedPoint(E, Result, Info); 10077 } 10078 return false; 10079 } 10080 10081 /// Check whether the given declaration can be directly converted to an integral 10082 /// rvalue. If not, no diagnostic is produced; there are other things we can 10083 /// try. 10084 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10085 // Enums are integer constant exprs. 10086 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10087 // Check for signedness/width mismatches between E type and ECD value. 10088 bool SameSign = (ECD->getInitVal().isSigned() 10089 == E->getType()->isSignedIntegerOrEnumerationType()); 10090 bool SameWidth = (ECD->getInitVal().getBitWidth() 10091 == Info.Ctx.getIntWidth(E->getType())); 10092 if (SameSign && SameWidth) 10093 return Success(ECD->getInitVal(), E); 10094 else { 10095 // Get rid of mismatch (otherwise Success assertions will fail) 10096 // by computing a new value matching the type of E. 10097 llvm::APSInt Val = ECD->getInitVal(); 10098 if (!SameSign) 10099 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10100 if (!SameWidth) 10101 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10102 return Success(Val, E); 10103 } 10104 } 10105 return false; 10106 } 10107 10108 /// Values returned by __builtin_classify_type, chosen to match the values 10109 /// produced by GCC's builtin. 10110 enum class GCCTypeClass { 10111 None = -1, 10112 Void = 0, 10113 Integer = 1, 10114 // GCC reserves 2 for character types, but instead classifies them as 10115 // integers. 10116 Enum = 3, 10117 Bool = 4, 10118 Pointer = 5, 10119 // GCC reserves 6 for references, but appears to never use it (because 10120 // expressions never have reference type, presumably). 10121 PointerToDataMember = 7, 10122 RealFloat = 8, 10123 Complex = 9, 10124 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10125 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10126 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10127 // uses 12 for that purpose, same as for a class or struct. Maybe it 10128 // internally implements a pointer to member as a struct? Who knows. 10129 PointerToMemberFunction = 12, // Not a bug, see above. 10130 ClassOrStruct = 12, 10131 Union = 13, 10132 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10133 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10134 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10135 // literals. 10136 }; 10137 10138 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10139 /// as GCC. 10140 static GCCTypeClass 10141 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10142 assert(!T->isDependentType() && "unexpected dependent type"); 10143 10144 QualType CanTy = T.getCanonicalType(); 10145 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10146 10147 switch (CanTy->getTypeClass()) { 10148 #define TYPE(ID, BASE) 10149 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10150 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10151 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10152 #include "clang/AST/TypeNodes.inc" 10153 case Type::Auto: 10154 case Type::DeducedTemplateSpecialization: 10155 llvm_unreachable("unexpected non-canonical or dependent type"); 10156 10157 case Type::Builtin: 10158 switch (BT->getKind()) { 10159 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10160 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10161 case BuiltinType::ID: return GCCTypeClass::Integer; 10162 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10163 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10164 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10165 case BuiltinType::ID: break; 10166 #include "clang/AST/BuiltinTypes.def" 10167 case BuiltinType::Void: 10168 return GCCTypeClass::Void; 10169 10170 case BuiltinType::Bool: 10171 return GCCTypeClass::Bool; 10172 10173 case BuiltinType::Char_U: 10174 case BuiltinType::UChar: 10175 case BuiltinType::WChar_U: 10176 case BuiltinType::Char8: 10177 case BuiltinType::Char16: 10178 case BuiltinType::Char32: 10179 case BuiltinType::UShort: 10180 case BuiltinType::UInt: 10181 case BuiltinType::ULong: 10182 case BuiltinType::ULongLong: 10183 case BuiltinType::UInt128: 10184 return GCCTypeClass::Integer; 10185 10186 case BuiltinType::UShortAccum: 10187 case BuiltinType::UAccum: 10188 case BuiltinType::ULongAccum: 10189 case BuiltinType::UShortFract: 10190 case BuiltinType::UFract: 10191 case BuiltinType::ULongFract: 10192 case BuiltinType::SatUShortAccum: 10193 case BuiltinType::SatUAccum: 10194 case BuiltinType::SatULongAccum: 10195 case BuiltinType::SatUShortFract: 10196 case BuiltinType::SatUFract: 10197 case BuiltinType::SatULongFract: 10198 return GCCTypeClass::None; 10199 10200 case BuiltinType::NullPtr: 10201 10202 case BuiltinType::ObjCId: 10203 case BuiltinType::ObjCClass: 10204 case BuiltinType::ObjCSel: 10205 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10206 case BuiltinType::Id: 10207 #include "clang/Basic/OpenCLImageTypes.def" 10208 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10209 case BuiltinType::Id: 10210 #include "clang/Basic/OpenCLExtensionTypes.def" 10211 case BuiltinType::OCLSampler: 10212 case BuiltinType::OCLEvent: 10213 case BuiltinType::OCLClkEvent: 10214 case BuiltinType::OCLQueue: 10215 case BuiltinType::OCLReserveID: 10216 #define SVE_TYPE(Name, Id, SingletonId) \ 10217 case BuiltinType::Id: 10218 #include "clang/Basic/AArch64SVEACLETypes.def" 10219 return GCCTypeClass::None; 10220 10221 case BuiltinType::Dependent: 10222 llvm_unreachable("unexpected dependent type"); 10223 }; 10224 llvm_unreachable("unexpected placeholder type"); 10225 10226 case Type::Enum: 10227 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10228 10229 case Type::Pointer: 10230 case Type::ConstantArray: 10231 case Type::VariableArray: 10232 case Type::IncompleteArray: 10233 case Type::FunctionNoProto: 10234 case Type::FunctionProto: 10235 return GCCTypeClass::Pointer; 10236 10237 case Type::MemberPointer: 10238 return CanTy->isMemberDataPointerType() 10239 ? GCCTypeClass::PointerToDataMember 10240 : GCCTypeClass::PointerToMemberFunction; 10241 10242 case Type::Complex: 10243 return GCCTypeClass::Complex; 10244 10245 case Type::Record: 10246 return CanTy->isUnionType() ? GCCTypeClass::Union 10247 : GCCTypeClass::ClassOrStruct; 10248 10249 case Type::Atomic: 10250 // GCC classifies _Atomic T the same as T. 10251 return EvaluateBuiltinClassifyType( 10252 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10253 10254 case Type::BlockPointer: 10255 case Type::Vector: 10256 case Type::ExtVector: 10257 case Type::ObjCObject: 10258 case Type::ObjCInterface: 10259 case Type::ObjCObjectPointer: 10260 case Type::Pipe: 10261 // GCC classifies vectors as None. We follow its lead and classify all 10262 // other types that don't fit into the regular classification the same way. 10263 return GCCTypeClass::None; 10264 10265 case Type::LValueReference: 10266 case Type::RValueReference: 10267 llvm_unreachable("invalid type for expression"); 10268 } 10269 10270 llvm_unreachable("unexpected type class"); 10271 } 10272 10273 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10274 /// as GCC. 10275 static GCCTypeClass 10276 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10277 // If no argument was supplied, default to None. This isn't 10278 // ideal, however it is what gcc does. 10279 if (E->getNumArgs() == 0) 10280 return GCCTypeClass::None; 10281 10282 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10283 // being an ICE, but still folds it to a constant using the type of the first 10284 // argument. 10285 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10286 } 10287 10288 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10289 /// __builtin_constant_p when applied to the given pointer. 10290 /// 10291 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10292 /// or it points to the first character of a string literal. 10293 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10294 APValue::LValueBase Base = LV.getLValueBase(); 10295 if (Base.isNull()) { 10296 // A null base is acceptable. 10297 return true; 10298 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10299 if (!isa<StringLiteral>(E)) 10300 return false; 10301 return LV.getLValueOffset().isZero(); 10302 } else if (Base.is<TypeInfoLValue>()) { 10303 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10304 // evaluate to true. 10305 return true; 10306 } else { 10307 // Any other base is not constant enough for GCC. 10308 return false; 10309 } 10310 } 10311 10312 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10313 /// GCC as we can manage. 10314 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10315 // This evaluation is not permitted to have side-effects, so evaluate it in 10316 // a speculative evaluation context. 10317 SpeculativeEvaluationRAII SpeculativeEval(Info); 10318 10319 // Constant-folding is always enabled for the operand of __builtin_constant_p 10320 // (even when the enclosing evaluation context otherwise requires a strict 10321 // language-specific constant expression). 10322 FoldConstant Fold(Info, true); 10323 10324 QualType ArgType = Arg->getType(); 10325 10326 // __builtin_constant_p always has one operand. The rules which gcc follows 10327 // are not precisely documented, but are as follows: 10328 // 10329 // - If the operand is of integral, floating, complex or enumeration type, 10330 // and can be folded to a known value of that type, it returns 1. 10331 // - If the operand can be folded to a pointer to the first character 10332 // of a string literal (or such a pointer cast to an integral type) 10333 // or to a null pointer or an integer cast to a pointer, it returns 1. 10334 // 10335 // Otherwise, it returns 0. 10336 // 10337 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10338 // its support for this did not work prior to GCC 9 and is not yet well 10339 // understood. 10340 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10341 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10342 ArgType->isNullPtrType()) { 10343 APValue V; 10344 if (!::EvaluateAsRValue(Info, Arg, V)) { 10345 Fold.keepDiagnostics(); 10346 return false; 10347 } 10348 10349 // For a pointer (possibly cast to integer), there are special rules. 10350 if (V.getKind() == APValue::LValue) 10351 return EvaluateBuiltinConstantPForLValue(V); 10352 10353 // Otherwise, any constant value is good enough. 10354 return V.hasValue(); 10355 } 10356 10357 // Anything else isn't considered to be sufficiently constant. 10358 return false; 10359 } 10360 10361 /// Retrieves the "underlying object type" of the given expression, 10362 /// as used by __builtin_object_size. 10363 static QualType getObjectType(APValue::LValueBase B) { 10364 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10365 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10366 return VD->getType(); 10367 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10368 if (isa<CompoundLiteralExpr>(E)) 10369 return E->getType(); 10370 } else if (B.is<TypeInfoLValue>()) { 10371 return B.getTypeInfoType(); 10372 } else if (B.is<DynamicAllocLValue>()) { 10373 return B.getDynamicAllocType(); 10374 } 10375 10376 return QualType(); 10377 } 10378 10379 /// A more selective version of E->IgnoreParenCasts for 10380 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10381 /// to change the type of E. 10382 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10383 /// 10384 /// Always returns an RValue with a pointer representation. 10385 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10386 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10387 10388 auto *NoParens = E->IgnoreParens(); 10389 auto *Cast = dyn_cast<CastExpr>(NoParens); 10390 if (Cast == nullptr) 10391 return NoParens; 10392 10393 // We only conservatively allow a few kinds of casts, because this code is 10394 // inherently a simple solution that seeks to support the common case. 10395 auto CastKind = Cast->getCastKind(); 10396 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10397 CastKind != CK_AddressSpaceConversion) 10398 return NoParens; 10399 10400 auto *SubExpr = Cast->getSubExpr(); 10401 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10402 return NoParens; 10403 return ignorePointerCastsAndParens(SubExpr); 10404 } 10405 10406 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10407 /// record layout. e.g. 10408 /// struct { struct { int a, b; } fst, snd; } obj; 10409 /// obj.fst // no 10410 /// obj.snd // yes 10411 /// obj.fst.a // no 10412 /// obj.fst.b // no 10413 /// obj.snd.a // no 10414 /// obj.snd.b // yes 10415 /// 10416 /// Please note: this function is specialized for how __builtin_object_size 10417 /// views "objects". 10418 /// 10419 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10420 /// correct result, it will always return true. 10421 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10422 assert(!LVal.Designator.Invalid); 10423 10424 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10425 const RecordDecl *Parent = FD->getParent(); 10426 Invalid = Parent->isInvalidDecl(); 10427 if (Invalid || Parent->isUnion()) 10428 return true; 10429 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10430 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10431 }; 10432 10433 auto &Base = LVal.getLValueBase(); 10434 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10435 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10436 bool Invalid; 10437 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10438 return Invalid; 10439 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10440 for (auto *FD : IFD->chain()) { 10441 bool Invalid; 10442 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10443 return Invalid; 10444 } 10445 } 10446 } 10447 10448 unsigned I = 0; 10449 QualType BaseType = getType(Base); 10450 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10451 // If we don't know the array bound, conservatively assume we're looking at 10452 // the final array element. 10453 ++I; 10454 if (BaseType->isIncompleteArrayType()) 10455 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10456 else 10457 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10458 } 10459 10460 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10461 const auto &Entry = LVal.Designator.Entries[I]; 10462 if (BaseType->isArrayType()) { 10463 // Because __builtin_object_size treats arrays as objects, we can ignore 10464 // the index iff this is the last array in the Designator. 10465 if (I + 1 == E) 10466 return true; 10467 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10468 uint64_t Index = Entry.getAsArrayIndex(); 10469 if (Index + 1 != CAT->getSize()) 10470 return false; 10471 BaseType = CAT->getElementType(); 10472 } else if (BaseType->isAnyComplexType()) { 10473 const auto *CT = BaseType->castAs<ComplexType>(); 10474 uint64_t Index = Entry.getAsArrayIndex(); 10475 if (Index != 1) 10476 return false; 10477 BaseType = CT->getElementType(); 10478 } else if (auto *FD = getAsField(Entry)) { 10479 bool Invalid; 10480 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10481 return Invalid; 10482 BaseType = FD->getType(); 10483 } else { 10484 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10485 return false; 10486 } 10487 } 10488 return true; 10489 } 10490 10491 /// Tests to see if the LValue has a user-specified designator (that isn't 10492 /// necessarily valid). Note that this always returns 'true' if the LValue has 10493 /// an unsized array as its first designator entry, because there's currently no 10494 /// way to tell if the user typed *foo or foo[0]. 10495 static bool refersToCompleteObject(const LValue &LVal) { 10496 if (LVal.Designator.Invalid) 10497 return false; 10498 10499 if (!LVal.Designator.Entries.empty()) 10500 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10501 10502 if (!LVal.InvalidBase) 10503 return true; 10504 10505 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10506 // the LValueBase. 10507 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10508 return !E || !isa<MemberExpr>(E); 10509 } 10510 10511 /// Attempts to detect a user writing into a piece of memory that's impossible 10512 /// to figure out the size of by just using types. 10513 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10514 const SubobjectDesignator &Designator = LVal.Designator; 10515 // Notes: 10516 // - Users can only write off of the end when we have an invalid base. Invalid 10517 // bases imply we don't know where the memory came from. 10518 // - We used to be a bit more aggressive here; we'd only be conservative if 10519 // the array at the end was flexible, or if it had 0 or 1 elements. This 10520 // broke some common standard library extensions (PR30346), but was 10521 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10522 // with some sort of whitelist. OTOH, it seems that GCC is always 10523 // conservative with the last element in structs (if it's an array), so our 10524 // current behavior is more compatible than a whitelisting approach would 10525 // be. 10526 return LVal.InvalidBase && 10527 Designator.Entries.size() == Designator.MostDerivedPathLength && 10528 Designator.MostDerivedIsArrayElement && 10529 isDesignatorAtObjectEnd(Ctx, LVal); 10530 } 10531 10532 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10533 /// Fails if the conversion would cause loss of precision. 10534 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10535 CharUnits &Result) { 10536 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10537 if (Int.ugt(CharUnitsMax)) 10538 return false; 10539 Result = CharUnits::fromQuantity(Int.getZExtValue()); 10540 return true; 10541 } 10542 10543 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 10544 /// determine how many bytes exist from the beginning of the object to either 10545 /// the end of the current subobject, or the end of the object itself, depending 10546 /// on what the LValue looks like + the value of Type. 10547 /// 10548 /// If this returns false, the value of Result is undefined. 10549 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 10550 unsigned Type, const LValue &LVal, 10551 CharUnits &EndOffset) { 10552 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 10553 10554 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 10555 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 10556 return false; 10557 return HandleSizeof(Info, ExprLoc, Ty, Result); 10558 }; 10559 10560 // We want to evaluate the size of the entire object. This is a valid fallback 10561 // for when Type=1 and the designator is invalid, because we're asked for an 10562 // upper-bound. 10563 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 10564 // Type=3 wants a lower bound, so we can't fall back to this. 10565 if (Type == 3 && !DetermineForCompleteObject) 10566 return false; 10567 10568 llvm::APInt APEndOffset; 10569 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10570 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10571 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10572 10573 if (LVal.InvalidBase) 10574 return false; 10575 10576 QualType BaseTy = getObjectType(LVal.getLValueBase()); 10577 return CheckedHandleSizeof(BaseTy, EndOffset); 10578 } 10579 10580 // We want to evaluate the size of a subobject. 10581 const SubobjectDesignator &Designator = LVal.Designator; 10582 10583 // The following is a moderately common idiom in C: 10584 // 10585 // struct Foo { int a; char c[1]; }; 10586 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 10587 // strcpy(&F->c[0], Bar); 10588 // 10589 // In order to not break too much legacy code, we need to support it. 10590 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 10591 // If we can resolve this to an alloc_size call, we can hand that back, 10592 // because we know for certain how many bytes there are to write to. 10593 llvm::APInt APEndOffset; 10594 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10595 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10596 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10597 10598 // If we cannot determine the size of the initial allocation, then we can't 10599 // given an accurate upper-bound. However, we are still able to give 10600 // conservative lower-bounds for Type=3. 10601 if (Type == 1) 10602 return false; 10603 } 10604 10605 CharUnits BytesPerElem; 10606 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 10607 return false; 10608 10609 // According to the GCC documentation, we want the size of the subobject 10610 // denoted by the pointer. But that's not quite right -- what we actually 10611 // want is the size of the immediately-enclosing array, if there is one. 10612 int64_t ElemsRemaining; 10613 if (Designator.MostDerivedIsArrayElement && 10614 Designator.Entries.size() == Designator.MostDerivedPathLength) { 10615 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 10616 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 10617 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 10618 } else { 10619 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 10620 } 10621 10622 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 10623 return true; 10624 } 10625 10626 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 10627 /// returns true and stores the result in @p Size. 10628 /// 10629 /// If @p WasError is non-null, this will report whether the failure to evaluate 10630 /// is to be treated as an Error in IntExprEvaluator. 10631 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 10632 EvalInfo &Info, uint64_t &Size) { 10633 // Determine the denoted object. 10634 LValue LVal; 10635 { 10636 // The operand of __builtin_object_size is never evaluated for side-effects. 10637 // If there are any, but we can determine the pointed-to object anyway, then 10638 // ignore the side-effects. 10639 SpeculativeEvaluationRAII SpeculativeEval(Info); 10640 IgnoreSideEffectsRAII Fold(Info); 10641 10642 if (E->isGLValue()) { 10643 // It's possible for us to be given GLValues if we're called via 10644 // Expr::tryEvaluateObjectSize. 10645 APValue RVal; 10646 if (!EvaluateAsRValue(Info, E, RVal)) 10647 return false; 10648 LVal.setFrom(Info.Ctx, RVal); 10649 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 10650 /*InvalidBaseOK=*/true)) 10651 return false; 10652 } 10653 10654 // If we point to before the start of the object, there are no accessible 10655 // bytes. 10656 if (LVal.getLValueOffset().isNegative()) { 10657 Size = 0; 10658 return true; 10659 } 10660 10661 CharUnits EndOffset; 10662 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 10663 return false; 10664 10665 // If we've fallen outside of the end offset, just pretend there's nothing to 10666 // write to/read from. 10667 if (EndOffset <= LVal.getLValueOffset()) 10668 Size = 0; 10669 else 10670 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 10671 return true; 10672 } 10673 10674 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 10675 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 10676 if (E->getResultAPValueKind() != APValue::None) 10677 return Success(E->getAPValueResult(), E); 10678 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 10679 } 10680 10681 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 10682 if (unsigned BuiltinOp = E->getBuiltinCallee()) 10683 return VisitBuiltinCallExpr(E, BuiltinOp); 10684 10685 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10686 } 10687 10688 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 10689 APValue &Val, APSInt &Alignment) { 10690 QualType SrcTy = E->getArg(0)->getType(); 10691 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 10692 return false; 10693 // Even though we are evaluating integer expressions we could get a pointer 10694 // argument for the __builtin_is_aligned() case. 10695 if (SrcTy->isPointerType()) { 10696 LValue Ptr; 10697 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 10698 return false; 10699 Ptr.moveInto(Val); 10700 } else if (!SrcTy->isIntegralOrEnumerationType()) { 10701 Info.FFDiag(E->getArg(0)); 10702 return false; 10703 } else { 10704 APSInt SrcInt; 10705 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 10706 return false; 10707 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 10708 "Bit widths must be the same"); 10709 Val = APValue(SrcInt); 10710 } 10711 assert(Val.hasValue()); 10712 return true; 10713 } 10714 10715 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 10716 unsigned BuiltinOp) { 10717 switch (BuiltinOp) { 10718 default: 10719 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10720 10721 case Builtin::BI__builtin_dynamic_object_size: 10722 case Builtin::BI__builtin_object_size: { 10723 // The type was checked when we built the expression. 10724 unsigned Type = 10725 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 10726 assert(Type <= 3 && "unexpected type"); 10727 10728 uint64_t Size; 10729 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 10730 return Success(Size, E); 10731 10732 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 10733 return Success((Type & 2) ? 0 : -1, E); 10734 10735 // Expression had no side effects, but we couldn't statically determine the 10736 // size of the referenced object. 10737 switch (Info.EvalMode) { 10738 case EvalInfo::EM_ConstantExpression: 10739 case EvalInfo::EM_ConstantFold: 10740 case EvalInfo::EM_IgnoreSideEffects: 10741 // Leave it to IR generation. 10742 return Error(E); 10743 case EvalInfo::EM_ConstantExpressionUnevaluated: 10744 // Reduce it to a constant now. 10745 return Success((Type & 2) ? 0 : -1, E); 10746 } 10747 10748 llvm_unreachable("unexpected EvalMode"); 10749 } 10750 10751 case Builtin::BI__builtin_os_log_format_buffer_size: { 10752 analyze_os_log::OSLogBufferLayout Layout; 10753 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 10754 return Success(Layout.size().getQuantity(), E); 10755 } 10756 10757 case Builtin::BI__builtin_is_aligned: { 10758 APValue Src; 10759 APSInt Alignment; 10760 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 10761 return false; 10762 if (Src.isLValue()) { 10763 // If we evaluated a pointer, check the minimum known alignment. 10764 LValue Ptr; 10765 Ptr.setFrom(Info.Ctx, Src); 10766 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 10767 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 10768 // We can return true if the known alignment at the computed offset is 10769 // greater than the requested alignment. 10770 assert(PtrAlign.isPowerOfTwo()); 10771 assert(Alignment.isPowerOf2()); 10772 if (PtrAlign.getQuantity() >= Alignment) 10773 return Success(1, E); 10774 // If the alignment is not known to be sufficient, some cases could still 10775 // be aligned at run time. However, if the requested alignment is less or 10776 // equal to the base alignment and the offset is not aligned, we know that 10777 // the run-time value can never be aligned. 10778 if (BaseAlignment.getQuantity() >= Alignment && 10779 PtrAlign.getQuantity() < Alignment) 10780 return Success(0, E); 10781 // Otherwise we can't infer whether the value is sufficiently aligned. 10782 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 10783 // in cases where we can't fully evaluate the pointer. 10784 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 10785 << Alignment; 10786 return false; 10787 } 10788 assert(Src.isInt()); 10789 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 10790 } 10791 case Builtin::BI__builtin_align_up: { 10792 APValue Src; 10793 APSInt Alignment; 10794 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 10795 return false; 10796 if (!Src.isInt()) 10797 return Error(E); 10798 APSInt AlignedVal = 10799 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 10800 Src.getInt().isUnsigned()); 10801 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 10802 return Success(AlignedVal, E); 10803 } 10804 case Builtin::BI__builtin_align_down: { 10805 APValue Src; 10806 APSInt Alignment; 10807 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 10808 return false; 10809 if (!Src.isInt()) 10810 return Error(E); 10811 APSInt AlignedVal = 10812 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 10813 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 10814 return Success(AlignedVal, E); 10815 } 10816 10817 case Builtin::BI__builtin_bswap16: 10818 case Builtin::BI__builtin_bswap32: 10819 case Builtin::BI__builtin_bswap64: { 10820 APSInt Val; 10821 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10822 return false; 10823 10824 return Success(Val.byteSwap(), E); 10825 } 10826 10827 case Builtin::BI__builtin_classify_type: 10828 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 10829 10830 case Builtin::BI__builtin_clrsb: 10831 case Builtin::BI__builtin_clrsbl: 10832 case Builtin::BI__builtin_clrsbll: { 10833 APSInt Val; 10834 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10835 return false; 10836 10837 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 10838 } 10839 10840 case Builtin::BI__builtin_clz: 10841 case Builtin::BI__builtin_clzl: 10842 case Builtin::BI__builtin_clzll: 10843 case Builtin::BI__builtin_clzs: { 10844 APSInt Val; 10845 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10846 return false; 10847 if (!Val) 10848 return Error(E); 10849 10850 return Success(Val.countLeadingZeros(), E); 10851 } 10852 10853 case Builtin::BI__builtin_constant_p: { 10854 const Expr *Arg = E->getArg(0); 10855 if (EvaluateBuiltinConstantP(Info, Arg)) 10856 return Success(true, E); 10857 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 10858 // Outside a constant context, eagerly evaluate to false in the presence 10859 // of side-effects in order to avoid -Wunsequenced false-positives in 10860 // a branch on __builtin_constant_p(expr). 10861 return Success(false, E); 10862 } 10863 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10864 return false; 10865 } 10866 10867 case Builtin::BI__builtin_is_constant_evaluated: { 10868 const auto *Callee = Info.CurrentCall->getCallee(); 10869 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 10870 (Info.CallStackDepth == 1 || 10871 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 10872 Callee->getIdentifier() && 10873 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 10874 // FIXME: Find a better way to avoid duplicated diagnostics. 10875 if (Info.EvalStatus.Diag) 10876 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 10877 : Info.CurrentCall->CallLoc, 10878 diag::warn_is_constant_evaluated_always_true_constexpr) 10879 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 10880 : "std::is_constant_evaluated"); 10881 } 10882 10883 return Success(Info.InConstantContext, E); 10884 } 10885 10886 case Builtin::BI__builtin_ctz: 10887 case Builtin::BI__builtin_ctzl: 10888 case Builtin::BI__builtin_ctzll: 10889 case Builtin::BI__builtin_ctzs: { 10890 APSInt Val; 10891 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10892 return false; 10893 if (!Val) 10894 return Error(E); 10895 10896 return Success(Val.countTrailingZeros(), E); 10897 } 10898 10899 case Builtin::BI__builtin_eh_return_data_regno: { 10900 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 10901 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 10902 return Success(Operand, E); 10903 } 10904 10905 case Builtin::BI__builtin_expect: 10906 return Visit(E->getArg(0)); 10907 10908 case Builtin::BI__builtin_ffs: 10909 case Builtin::BI__builtin_ffsl: 10910 case Builtin::BI__builtin_ffsll: { 10911 APSInt Val; 10912 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10913 return false; 10914 10915 unsigned N = Val.countTrailingZeros(); 10916 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 10917 } 10918 10919 case Builtin::BI__builtin_fpclassify: { 10920 APFloat Val(0.0); 10921 if (!EvaluateFloat(E->getArg(5), Val, Info)) 10922 return false; 10923 unsigned Arg; 10924 switch (Val.getCategory()) { 10925 case APFloat::fcNaN: Arg = 0; break; 10926 case APFloat::fcInfinity: Arg = 1; break; 10927 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 10928 case APFloat::fcZero: Arg = 4; break; 10929 } 10930 return Visit(E->getArg(Arg)); 10931 } 10932 10933 case Builtin::BI__builtin_isinf_sign: { 10934 APFloat Val(0.0); 10935 return EvaluateFloat(E->getArg(0), Val, Info) && 10936 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 10937 } 10938 10939 case Builtin::BI__builtin_isinf: { 10940 APFloat Val(0.0); 10941 return EvaluateFloat(E->getArg(0), Val, Info) && 10942 Success(Val.isInfinity() ? 1 : 0, E); 10943 } 10944 10945 case Builtin::BI__builtin_isfinite: { 10946 APFloat Val(0.0); 10947 return EvaluateFloat(E->getArg(0), Val, Info) && 10948 Success(Val.isFinite() ? 1 : 0, E); 10949 } 10950 10951 case Builtin::BI__builtin_isnan: { 10952 APFloat Val(0.0); 10953 return EvaluateFloat(E->getArg(0), Val, Info) && 10954 Success(Val.isNaN() ? 1 : 0, E); 10955 } 10956 10957 case Builtin::BI__builtin_isnormal: { 10958 APFloat Val(0.0); 10959 return EvaluateFloat(E->getArg(0), Val, Info) && 10960 Success(Val.isNormal() ? 1 : 0, E); 10961 } 10962 10963 case Builtin::BI__builtin_parity: 10964 case Builtin::BI__builtin_parityl: 10965 case Builtin::BI__builtin_parityll: { 10966 APSInt Val; 10967 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10968 return false; 10969 10970 return Success(Val.countPopulation() % 2, E); 10971 } 10972 10973 case Builtin::BI__builtin_popcount: 10974 case Builtin::BI__builtin_popcountl: 10975 case Builtin::BI__builtin_popcountll: { 10976 APSInt Val; 10977 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10978 return false; 10979 10980 return Success(Val.countPopulation(), E); 10981 } 10982 10983 case Builtin::BIstrlen: 10984 case Builtin::BIwcslen: 10985 // A call to strlen is not a constant expression. 10986 if (Info.getLangOpts().CPlusPlus11) 10987 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 10988 << /*isConstexpr*/0 << /*isConstructor*/0 10989 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 10990 else 10991 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 10992 LLVM_FALLTHROUGH; 10993 case Builtin::BI__builtin_strlen: 10994 case Builtin::BI__builtin_wcslen: { 10995 // As an extension, we support __builtin_strlen() as a constant expression, 10996 // and support folding strlen() to a constant. 10997 LValue String; 10998 if (!EvaluatePointer(E->getArg(0), String, Info)) 10999 return false; 11000 11001 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11002 11003 // Fast path: if it's a string literal, search the string value. 11004 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11005 String.getLValueBase().dyn_cast<const Expr *>())) { 11006 // The string literal may have embedded null characters. Find the first 11007 // one and truncate there. 11008 StringRef Str = S->getBytes(); 11009 int64_t Off = String.Offset.getQuantity(); 11010 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11011 S->getCharByteWidth() == 1 && 11012 // FIXME: Add fast-path for wchar_t too. 11013 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11014 Str = Str.substr(Off); 11015 11016 StringRef::size_type Pos = Str.find(0); 11017 if (Pos != StringRef::npos) 11018 Str = Str.substr(0, Pos); 11019 11020 return Success(Str.size(), E); 11021 } 11022 11023 // Fall through to slow path to issue appropriate diagnostic. 11024 } 11025 11026 // Slow path: scan the bytes of the string looking for the terminating 0. 11027 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11028 APValue Char; 11029 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11030 !Char.isInt()) 11031 return false; 11032 if (!Char.getInt()) 11033 return Success(Strlen, E); 11034 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11035 return false; 11036 } 11037 } 11038 11039 case Builtin::BIstrcmp: 11040 case Builtin::BIwcscmp: 11041 case Builtin::BIstrncmp: 11042 case Builtin::BIwcsncmp: 11043 case Builtin::BImemcmp: 11044 case Builtin::BIbcmp: 11045 case Builtin::BIwmemcmp: 11046 // A call to strlen is not a constant expression. 11047 if (Info.getLangOpts().CPlusPlus11) 11048 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11049 << /*isConstexpr*/0 << /*isConstructor*/0 11050 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11051 else 11052 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11053 LLVM_FALLTHROUGH; 11054 case Builtin::BI__builtin_strcmp: 11055 case Builtin::BI__builtin_wcscmp: 11056 case Builtin::BI__builtin_strncmp: 11057 case Builtin::BI__builtin_wcsncmp: 11058 case Builtin::BI__builtin_memcmp: 11059 case Builtin::BI__builtin_bcmp: 11060 case Builtin::BI__builtin_wmemcmp: { 11061 LValue String1, String2; 11062 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11063 !EvaluatePointer(E->getArg(1), String2, Info)) 11064 return false; 11065 11066 uint64_t MaxLength = uint64_t(-1); 11067 if (BuiltinOp != Builtin::BIstrcmp && 11068 BuiltinOp != Builtin::BIwcscmp && 11069 BuiltinOp != Builtin::BI__builtin_strcmp && 11070 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11071 APSInt N; 11072 if (!EvaluateInteger(E->getArg(2), N, Info)) 11073 return false; 11074 MaxLength = N.getExtValue(); 11075 } 11076 11077 // Empty substrings compare equal by definition. 11078 if (MaxLength == 0u) 11079 return Success(0, E); 11080 11081 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11082 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11083 String1.Designator.Invalid || String2.Designator.Invalid) 11084 return false; 11085 11086 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11087 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11088 11089 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11090 BuiltinOp == Builtin::BIbcmp || 11091 BuiltinOp == Builtin::BI__builtin_memcmp || 11092 BuiltinOp == Builtin::BI__builtin_bcmp; 11093 11094 assert(IsRawByte || 11095 (Info.Ctx.hasSameUnqualifiedType( 11096 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11097 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11098 11099 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11100 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11101 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11102 Char1.isInt() && Char2.isInt(); 11103 }; 11104 const auto &AdvanceElems = [&] { 11105 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11106 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11107 }; 11108 11109 if (IsRawByte) { 11110 uint64_t BytesRemaining = MaxLength; 11111 // Pointers to const void may point to objects of incomplete type. 11112 if (CharTy1->isIncompleteType()) { 11113 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; 11114 return false; 11115 } 11116 if (CharTy2->isIncompleteType()) { 11117 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; 11118 return false; 11119 } 11120 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; 11121 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); 11122 // Give up on comparing between elements with disparate widths. 11123 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) 11124 return false; 11125 uint64_t BytesPerElement = CharTy1Size.getQuantity(); 11126 assert(BytesRemaining && "BytesRemaining should not be zero: the " 11127 "following loop considers at least one element"); 11128 while (true) { 11129 APValue Char1, Char2; 11130 if (!ReadCurElems(Char1, Char2)) 11131 return false; 11132 // We have compatible in-memory widths, but a possible type and 11133 // (for `bool`) internal representation mismatch. 11134 // Assuming two's complement representation, including 0 for `false` and 11135 // 1 for `true`, we can check an appropriate number of elements for 11136 // equality even if they are not byte-sized. 11137 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); 11138 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); 11139 if (Char1InMem.ne(Char2InMem)) { 11140 // If the elements are byte-sized, then we can produce a three-way 11141 // comparison result in a straightforward manner. 11142 if (BytesPerElement == 1u) { 11143 // memcmp always compares unsigned chars. 11144 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); 11145 } 11146 // The result is byte-order sensitive, and we have multibyte elements. 11147 // FIXME: We can compare the remaining bytes in the correct order. 11148 return false; 11149 } 11150 if (!AdvanceElems()) 11151 return false; 11152 if (BytesRemaining <= BytesPerElement) 11153 break; 11154 BytesRemaining -= BytesPerElement; 11155 } 11156 // Enough elements are equal to account for the memcmp limit. 11157 return Success(0, E); 11158 } 11159 11160 bool StopAtNull = 11161 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11162 BuiltinOp != Builtin::BIwmemcmp && 11163 BuiltinOp != Builtin::BI__builtin_memcmp && 11164 BuiltinOp != Builtin::BI__builtin_bcmp && 11165 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11166 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11167 BuiltinOp == Builtin::BIwcsncmp || 11168 BuiltinOp == Builtin::BIwmemcmp || 11169 BuiltinOp == Builtin::BI__builtin_wcscmp || 11170 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11171 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11172 11173 for (; MaxLength; --MaxLength) { 11174 APValue Char1, Char2; 11175 if (!ReadCurElems(Char1, Char2)) 11176 return false; 11177 if (Char1.getInt() != Char2.getInt()) { 11178 if (IsWide) // wmemcmp compares with wchar_t signedness. 11179 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11180 // memcmp always compares unsigned chars. 11181 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11182 } 11183 if (StopAtNull && !Char1.getInt()) 11184 return Success(0, E); 11185 assert(!(StopAtNull && !Char2.getInt())); 11186 if (!AdvanceElems()) 11187 return false; 11188 } 11189 // We hit the strncmp / memcmp limit. 11190 return Success(0, E); 11191 } 11192 11193 case Builtin::BI__atomic_always_lock_free: 11194 case Builtin::BI__atomic_is_lock_free: 11195 case Builtin::BI__c11_atomic_is_lock_free: { 11196 APSInt SizeVal; 11197 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11198 return false; 11199 11200 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11201 // of two less than the maximum inline atomic width, we know it is 11202 // lock-free. If the size isn't a power of two, or greater than the 11203 // maximum alignment where we promote atomics, we know it is not lock-free 11204 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11205 // the answer can only be determined at runtime; for example, 16-byte 11206 // atomics have lock-free implementations on some, but not all, 11207 // x86-64 processors. 11208 11209 // Check power-of-two. 11210 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11211 if (Size.isPowerOfTwo()) { 11212 // Check against inlining width. 11213 unsigned InlineWidthBits = 11214 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11215 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11216 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11217 Size == CharUnits::One() || 11218 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11219 Expr::NPC_NeverValueDependent)) 11220 // OK, we will inline appropriately-aligned operations of this size, 11221 // and _Atomic(T) is appropriately-aligned. 11222 return Success(1, E); 11223 11224 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11225 castAs<PointerType>()->getPointeeType(); 11226 if (!PointeeType->isIncompleteType() && 11227 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11228 // OK, we will inline operations on this object. 11229 return Success(1, E); 11230 } 11231 } 11232 } 11233 11234 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11235 Success(0, E) : Error(E); 11236 } 11237 case Builtin::BIomp_is_initial_device: 11238 // We can decide statically which value the runtime would return if called. 11239 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11240 case Builtin::BI__builtin_add_overflow: 11241 case Builtin::BI__builtin_sub_overflow: 11242 case Builtin::BI__builtin_mul_overflow: 11243 case Builtin::BI__builtin_sadd_overflow: 11244 case Builtin::BI__builtin_uadd_overflow: 11245 case Builtin::BI__builtin_uaddl_overflow: 11246 case Builtin::BI__builtin_uaddll_overflow: 11247 case Builtin::BI__builtin_usub_overflow: 11248 case Builtin::BI__builtin_usubl_overflow: 11249 case Builtin::BI__builtin_usubll_overflow: 11250 case Builtin::BI__builtin_umul_overflow: 11251 case Builtin::BI__builtin_umull_overflow: 11252 case Builtin::BI__builtin_umulll_overflow: 11253 case Builtin::BI__builtin_saddl_overflow: 11254 case Builtin::BI__builtin_saddll_overflow: 11255 case Builtin::BI__builtin_ssub_overflow: 11256 case Builtin::BI__builtin_ssubl_overflow: 11257 case Builtin::BI__builtin_ssubll_overflow: 11258 case Builtin::BI__builtin_smul_overflow: 11259 case Builtin::BI__builtin_smull_overflow: 11260 case Builtin::BI__builtin_smulll_overflow: { 11261 LValue ResultLValue; 11262 APSInt LHS, RHS; 11263 11264 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11265 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11266 !EvaluateInteger(E->getArg(1), RHS, Info) || 11267 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11268 return false; 11269 11270 APSInt Result; 11271 bool DidOverflow = false; 11272 11273 // If the types don't have to match, enlarge all 3 to the largest of them. 11274 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11275 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11276 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11277 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11278 ResultType->isSignedIntegerOrEnumerationType(); 11279 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11280 ResultType->isSignedIntegerOrEnumerationType(); 11281 uint64_t LHSSize = LHS.getBitWidth(); 11282 uint64_t RHSSize = RHS.getBitWidth(); 11283 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11284 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11285 11286 // Add an additional bit if the signedness isn't uniformly agreed to. We 11287 // could do this ONLY if there is a signed and an unsigned that both have 11288 // MaxBits, but the code to check that is pretty nasty. The issue will be 11289 // caught in the shrink-to-result later anyway. 11290 if (IsSigned && !AllSigned) 11291 ++MaxBits; 11292 11293 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11294 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11295 Result = APSInt(MaxBits, !IsSigned); 11296 } 11297 11298 // Find largest int. 11299 switch (BuiltinOp) { 11300 default: 11301 llvm_unreachable("Invalid value for BuiltinOp"); 11302 case Builtin::BI__builtin_add_overflow: 11303 case Builtin::BI__builtin_sadd_overflow: 11304 case Builtin::BI__builtin_saddl_overflow: 11305 case Builtin::BI__builtin_saddll_overflow: 11306 case Builtin::BI__builtin_uadd_overflow: 11307 case Builtin::BI__builtin_uaddl_overflow: 11308 case Builtin::BI__builtin_uaddll_overflow: 11309 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11310 : LHS.uadd_ov(RHS, DidOverflow); 11311 break; 11312 case Builtin::BI__builtin_sub_overflow: 11313 case Builtin::BI__builtin_ssub_overflow: 11314 case Builtin::BI__builtin_ssubl_overflow: 11315 case Builtin::BI__builtin_ssubll_overflow: 11316 case Builtin::BI__builtin_usub_overflow: 11317 case Builtin::BI__builtin_usubl_overflow: 11318 case Builtin::BI__builtin_usubll_overflow: 11319 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11320 : LHS.usub_ov(RHS, DidOverflow); 11321 break; 11322 case Builtin::BI__builtin_mul_overflow: 11323 case Builtin::BI__builtin_smul_overflow: 11324 case Builtin::BI__builtin_smull_overflow: 11325 case Builtin::BI__builtin_smulll_overflow: 11326 case Builtin::BI__builtin_umul_overflow: 11327 case Builtin::BI__builtin_umull_overflow: 11328 case Builtin::BI__builtin_umulll_overflow: 11329 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11330 : LHS.umul_ov(RHS, DidOverflow); 11331 break; 11332 } 11333 11334 // In the case where multiple sizes are allowed, truncate and see if 11335 // the values are the same. 11336 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11337 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11338 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11339 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11340 // since it will give us the behavior of a TruncOrSelf in the case where 11341 // its parameter <= its size. We previously set Result to be at least the 11342 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11343 // will work exactly like TruncOrSelf. 11344 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11345 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11346 11347 if (!APSInt::isSameValue(Temp, Result)) 11348 DidOverflow = true; 11349 Result = Temp; 11350 } 11351 11352 APValue APV{Result}; 11353 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11354 return false; 11355 return Success(DidOverflow, E); 11356 } 11357 } 11358 } 11359 11360 /// Determine whether this is a pointer past the end of the complete 11361 /// object referred to by the lvalue. 11362 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11363 const LValue &LV) { 11364 // A null pointer can be viewed as being "past the end" but we don't 11365 // choose to look at it that way here. 11366 if (!LV.getLValueBase()) 11367 return false; 11368 11369 // If the designator is valid and refers to a subobject, we're not pointing 11370 // past the end. 11371 if (!LV.getLValueDesignator().Invalid && 11372 !LV.getLValueDesignator().isOnePastTheEnd()) 11373 return false; 11374 11375 // A pointer to an incomplete type might be past-the-end if the type's size is 11376 // zero. We cannot tell because the type is incomplete. 11377 QualType Ty = getType(LV.getLValueBase()); 11378 if (Ty->isIncompleteType()) 11379 return true; 11380 11381 // We're a past-the-end pointer if we point to the byte after the object, 11382 // no matter what our type or path is. 11383 auto Size = Ctx.getTypeSizeInChars(Ty); 11384 return LV.getLValueOffset() == Size; 11385 } 11386 11387 namespace { 11388 11389 /// Data recursive integer evaluator of certain binary operators. 11390 /// 11391 /// We use a data recursive algorithm for binary operators so that we are able 11392 /// to handle extreme cases of chained binary operators without causing stack 11393 /// overflow. 11394 class DataRecursiveIntBinOpEvaluator { 11395 struct EvalResult { 11396 APValue Val; 11397 bool Failed; 11398 11399 EvalResult() : Failed(false) { } 11400 11401 void swap(EvalResult &RHS) { 11402 Val.swap(RHS.Val); 11403 Failed = RHS.Failed; 11404 RHS.Failed = false; 11405 } 11406 }; 11407 11408 struct Job { 11409 const Expr *E; 11410 EvalResult LHSResult; // meaningful only for binary operator expression. 11411 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11412 11413 Job() = default; 11414 Job(Job &&) = default; 11415 11416 void startSpeculativeEval(EvalInfo &Info) { 11417 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11418 } 11419 11420 private: 11421 SpeculativeEvaluationRAII SpecEvalRAII; 11422 }; 11423 11424 SmallVector<Job, 16> Queue; 11425 11426 IntExprEvaluator &IntEval; 11427 EvalInfo &Info; 11428 APValue &FinalResult; 11429 11430 public: 11431 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11432 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11433 11434 /// True if \param E is a binary operator that we are going to handle 11435 /// data recursively. 11436 /// We handle binary operators that are comma, logical, or that have operands 11437 /// with integral or enumeration type. 11438 static bool shouldEnqueue(const BinaryOperator *E) { 11439 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11440 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11441 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11442 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11443 } 11444 11445 bool Traverse(const BinaryOperator *E) { 11446 enqueue(E); 11447 EvalResult PrevResult; 11448 while (!Queue.empty()) 11449 process(PrevResult); 11450 11451 if (PrevResult.Failed) return false; 11452 11453 FinalResult.swap(PrevResult.Val); 11454 return true; 11455 } 11456 11457 private: 11458 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11459 return IntEval.Success(Value, E, Result); 11460 } 11461 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11462 return IntEval.Success(Value, E, Result); 11463 } 11464 bool Error(const Expr *E) { 11465 return IntEval.Error(E); 11466 } 11467 bool Error(const Expr *E, diag::kind D) { 11468 return IntEval.Error(E, D); 11469 } 11470 11471 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11472 return Info.CCEDiag(E, D); 11473 } 11474 11475 // Returns true if visiting the RHS is necessary, false otherwise. 11476 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11477 bool &SuppressRHSDiags); 11478 11479 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11480 const BinaryOperator *E, APValue &Result); 11481 11482 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11483 Result.Failed = !Evaluate(Result.Val, Info, E); 11484 if (Result.Failed) 11485 Result.Val = APValue(); 11486 } 11487 11488 void process(EvalResult &Result); 11489 11490 void enqueue(const Expr *E) { 11491 E = E->IgnoreParens(); 11492 Queue.resize(Queue.size()+1); 11493 Queue.back().E = E; 11494 Queue.back().Kind = Job::AnyExprKind; 11495 } 11496 }; 11497 11498 } 11499 11500 bool DataRecursiveIntBinOpEvaluator:: 11501 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11502 bool &SuppressRHSDiags) { 11503 if (E->getOpcode() == BO_Comma) { 11504 // Ignore LHS but note if we could not evaluate it. 11505 if (LHSResult.Failed) 11506 return Info.noteSideEffect(); 11507 return true; 11508 } 11509 11510 if (E->isLogicalOp()) { 11511 bool LHSAsBool; 11512 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11513 // We were able to evaluate the LHS, see if we can get away with not 11514 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11515 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11516 Success(LHSAsBool, E, LHSResult.Val); 11517 return false; // Ignore RHS 11518 } 11519 } else { 11520 LHSResult.Failed = true; 11521 11522 // Since we weren't able to evaluate the left hand side, it 11523 // might have had side effects. 11524 if (!Info.noteSideEffect()) 11525 return false; 11526 11527 // We can't evaluate the LHS; however, sometimes the result 11528 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11529 // Don't ignore RHS and suppress diagnostics from this arm. 11530 SuppressRHSDiags = true; 11531 } 11532 11533 return true; 11534 } 11535 11536 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11537 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11538 11539 if (LHSResult.Failed && !Info.noteFailure()) 11540 return false; // Ignore RHS; 11541 11542 return true; 11543 } 11544 11545 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 11546 bool IsSub) { 11547 // Compute the new offset in the appropriate width, wrapping at 64 bits. 11548 // FIXME: When compiling for a 32-bit target, we should use 32-bit 11549 // offsets. 11550 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 11551 CharUnits &Offset = LVal.getLValueOffset(); 11552 uint64_t Offset64 = Offset.getQuantity(); 11553 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 11554 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 11555 : Offset64 + Index64); 11556 } 11557 11558 bool DataRecursiveIntBinOpEvaluator:: 11559 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11560 const BinaryOperator *E, APValue &Result) { 11561 if (E->getOpcode() == BO_Comma) { 11562 if (RHSResult.Failed) 11563 return false; 11564 Result = RHSResult.Val; 11565 return true; 11566 } 11567 11568 if (E->isLogicalOp()) { 11569 bool lhsResult, rhsResult; 11570 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 11571 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 11572 11573 if (LHSIsOK) { 11574 if (RHSIsOK) { 11575 if (E->getOpcode() == BO_LOr) 11576 return Success(lhsResult || rhsResult, E, Result); 11577 else 11578 return Success(lhsResult && rhsResult, E, Result); 11579 } 11580 } else { 11581 if (RHSIsOK) { 11582 // We can't evaluate the LHS; however, sometimes the result 11583 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11584 if (rhsResult == (E->getOpcode() == BO_LOr)) 11585 return Success(rhsResult, E, Result); 11586 } 11587 } 11588 11589 return false; 11590 } 11591 11592 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11593 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11594 11595 if (LHSResult.Failed || RHSResult.Failed) 11596 return false; 11597 11598 const APValue &LHSVal = LHSResult.Val; 11599 const APValue &RHSVal = RHSResult.Val; 11600 11601 // Handle cases like (unsigned long)&a + 4. 11602 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 11603 Result = LHSVal; 11604 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 11605 return true; 11606 } 11607 11608 // Handle cases like 4 + (unsigned long)&a 11609 if (E->getOpcode() == BO_Add && 11610 RHSVal.isLValue() && LHSVal.isInt()) { 11611 Result = RHSVal; 11612 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 11613 return true; 11614 } 11615 11616 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 11617 // Handle (intptr_t)&&A - (intptr_t)&&B. 11618 if (!LHSVal.getLValueOffset().isZero() || 11619 !RHSVal.getLValueOffset().isZero()) 11620 return false; 11621 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 11622 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 11623 if (!LHSExpr || !RHSExpr) 11624 return false; 11625 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11626 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11627 if (!LHSAddrExpr || !RHSAddrExpr) 11628 return false; 11629 // Make sure both labels come from the same function. 11630 if (LHSAddrExpr->getLabel()->getDeclContext() != 11631 RHSAddrExpr->getLabel()->getDeclContext()) 11632 return false; 11633 Result = APValue(LHSAddrExpr, RHSAddrExpr); 11634 return true; 11635 } 11636 11637 // All the remaining cases expect both operands to be an integer 11638 if (!LHSVal.isInt() || !RHSVal.isInt()) 11639 return Error(E); 11640 11641 // Set up the width and signedness manually, in case it can't be deduced 11642 // from the operation we're performing. 11643 // FIXME: Don't do this in the cases where we can deduce it. 11644 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 11645 E->getType()->isUnsignedIntegerOrEnumerationType()); 11646 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 11647 RHSVal.getInt(), Value)) 11648 return false; 11649 return Success(Value, E, Result); 11650 } 11651 11652 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 11653 Job &job = Queue.back(); 11654 11655 switch (job.Kind) { 11656 case Job::AnyExprKind: { 11657 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 11658 if (shouldEnqueue(Bop)) { 11659 job.Kind = Job::BinOpKind; 11660 enqueue(Bop->getLHS()); 11661 return; 11662 } 11663 } 11664 11665 EvaluateExpr(job.E, Result); 11666 Queue.pop_back(); 11667 return; 11668 } 11669 11670 case Job::BinOpKind: { 11671 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11672 bool SuppressRHSDiags = false; 11673 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 11674 Queue.pop_back(); 11675 return; 11676 } 11677 if (SuppressRHSDiags) 11678 job.startSpeculativeEval(Info); 11679 job.LHSResult.swap(Result); 11680 job.Kind = Job::BinOpVisitedLHSKind; 11681 enqueue(Bop->getRHS()); 11682 return; 11683 } 11684 11685 case Job::BinOpVisitedLHSKind: { 11686 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11687 EvalResult RHS; 11688 RHS.swap(Result); 11689 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 11690 Queue.pop_back(); 11691 return; 11692 } 11693 } 11694 11695 llvm_unreachable("Invalid Job::Kind!"); 11696 } 11697 11698 namespace { 11699 /// Used when we determine that we should fail, but can keep evaluating prior to 11700 /// noting that we had a failure. 11701 class DelayedNoteFailureRAII { 11702 EvalInfo &Info; 11703 bool NoteFailure; 11704 11705 public: 11706 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 11707 : Info(Info), NoteFailure(NoteFailure) {} 11708 ~DelayedNoteFailureRAII() { 11709 if (NoteFailure) { 11710 bool ContinueAfterFailure = Info.noteFailure(); 11711 (void)ContinueAfterFailure; 11712 assert(ContinueAfterFailure && 11713 "Shouldn't have kept evaluating on failure."); 11714 } 11715 } 11716 }; 11717 11718 enum class CmpResult { 11719 Unequal, 11720 Less, 11721 Equal, 11722 Greater, 11723 Unordered, 11724 }; 11725 } 11726 11727 template <class SuccessCB, class AfterCB> 11728 static bool 11729 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 11730 SuccessCB &&Success, AfterCB &&DoAfter) { 11731 assert(E->isComparisonOp() && "expected comparison operator"); 11732 assert((E->getOpcode() == BO_Cmp || 11733 E->getType()->isIntegralOrEnumerationType()) && 11734 "unsupported binary expression evaluation"); 11735 auto Error = [&](const Expr *E) { 11736 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11737 return false; 11738 }; 11739 11740 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 11741 bool IsEquality = E->isEqualityOp(); 11742 11743 QualType LHSTy = E->getLHS()->getType(); 11744 QualType RHSTy = E->getRHS()->getType(); 11745 11746 if (LHSTy->isIntegralOrEnumerationType() && 11747 RHSTy->isIntegralOrEnumerationType()) { 11748 APSInt LHS, RHS; 11749 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 11750 if (!LHSOK && !Info.noteFailure()) 11751 return false; 11752 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 11753 return false; 11754 if (LHS < RHS) 11755 return Success(CmpResult::Less, E); 11756 if (LHS > RHS) 11757 return Success(CmpResult::Greater, E); 11758 return Success(CmpResult::Equal, E); 11759 } 11760 11761 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 11762 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 11763 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 11764 11765 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 11766 if (!LHSOK && !Info.noteFailure()) 11767 return false; 11768 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 11769 return false; 11770 if (LHSFX < RHSFX) 11771 return Success(CmpResult::Less, E); 11772 if (LHSFX > RHSFX) 11773 return Success(CmpResult::Greater, E); 11774 return Success(CmpResult::Equal, E); 11775 } 11776 11777 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 11778 ComplexValue LHS, RHS; 11779 bool LHSOK; 11780 if (E->isAssignmentOp()) { 11781 LValue LV; 11782 EvaluateLValue(E->getLHS(), LV, Info); 11783 LHSOK = false; 11784 } else if (LHSTy->isRealFloatingType()) { 11785 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 11786 if (LHSOK) { 11787 LHS.makeComplexFloat(); 11788 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 11789 } 11790 } else { 11791 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 11792 } 11793 if (!LHSOK && !Info.noteFailure()) 11794 return false; 11795 11796 if (E->getRHS()->getType()->isRealFloatingType()) { 11797 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 11798 return false; 11799 RHS.makeComplexFloat(); 11800 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 11801 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 11802 return false; 11803 11804 if (LHS.isComplexFloat()) { 11805 APFloat::cmpResult CR_r = 11806 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 11807 APFloat::cmpResult CR_i = 11808 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 11809 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 11810 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 11811 } else { 11812 assert(IsEquality && "invalid complex comparison"); 11813 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 11814 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 11815 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 11816 } 11817 } 11818 11819 if (LHSTy->isRealFloatingType() && 11820 RHSTy->isRealFloatingType()) { 11821 APFloat RHS(0.0), LHS(0.0); 11822 11823 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 11824 if (!LHSOK && !Info.noteFailure()) 11825 return false; 11826 11827 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 11828 return false; 11829 11830 assert(E->isComparisonOp() && "Invalid binary operator!"); 11831 auto GetCmpRes = [&]() { 11832 switch (LHS.compare(RHS)) { 11833 case APFloat::cmpEqual: 11834 return CmpResult::Equal; 11835 case APFloat::cmpLessThan: 11836 return CmpResult::Less; 11837 case APFloat::cmpGreaterThan: 11838 return CmpResult::Greater; 11839 case APFloat::cmpUnordered: 11840 return CmpResult::Unordered; 11841 } 11842 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 11843 }; 11844 return Success(GetCmpRes(), E); 11845 } 11846 11847 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 11848 LValue LHSValue, RHSValue; 11849 11850 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 11851 if (!LHSOK && !Info.noteFailure()) 11852 return false; 11853 11854 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11855 return false; 11856 11857 // Reject differing bases from the normal codepath; we special-case 11858 // comparisons to null. 11859 if (!HasSameBase(LHSValue, RHSValue)) { 11860 // Inequalities and subtractions between unrelated pointers have 11861 // unspecified or undefined behavior. 11862 if (!IsEquality) { 11863 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 11864 return false; 11865 } 11866 // A constant address may compare equal to the address of a symbol. 11867 // The one exception is that address of an object cannot compare equal 11868 // to a null pointer constant. 11869 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 11870 (!RHSValue.Base && !RHSValue.Offset.isZero())) 11871 return Error(E); 11872 // It's implementation-defined whether distinct literals will have 11873 // distinct addresses. In clang, the result of such a comparison is 11874 // unspecified, so it is not a constant expression. However, we do know 11875 // that the address of a literal will be non-null. 11876 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 11877 LHSValue.Base && RHSValue.Base) 11878 return Error(E); 11879 // We can't tell whether weak symbols will end up pointing to the same 11880 // object. 11881 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 11882 return Error(E); 11883 // We can't compare the address of the start of one object with the 11884 // past-the-end address of another object, per C++ DR1652. 11885 if ((LHSValue.Base && LHSValue.Offset.isZero() && 11886 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 11887 (RHSValue.Base && RHSValue.Offset.isZero() && 11888 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 11889 return Error(E); 11890 // We can't tell whether an object is at the same address as another 11891 // zero sized object. 11892 if ((RHSValue.Base && isZeroSized(LHSValue)) || 11893 (LHSValue.Base && isZeroSized(RHSValue))) 11894 return Error(E); 11895 return Success(CmpResult::Unequal, E); 11896 } 11897 11898 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 11899 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 11900 11901 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 11902 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 11903 11904 // C++11 [expr.rel]p3: 11905 // Pointers to void (after pointer conversions) can be compared, with a 11906 // result defined as follows: If both pointers represent the same 11907 // address or are both the null pointer value, the result is true if the 11908 // operator is <= or >= and false otherwise; otherwise the result is 11909 // unspecified. 11910 // We interpret this as applying to pointers to *cv* void. 11911 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 11912 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 11913 11914 // C++11 [expr.rel]p2: 11915 // - If two pointers point to non-static data members of the same object, 11916 // or to subobjects or array elements fo such members, recursively, the 11917 // pointer to the later declared member compares greater provided the 11918 // two members have the same access control and provided their class is 11919 // not a union. 11920 // [...] 11921 // - Otherwise pointer comparisons are unspecified. 11922 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 11923 bool WasArrayIndex; 11924 unsigned Mismatch = FindDesignatorMismatch( 11925 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 11926 // At the point where the designators diverge, the comparison has a 11927 // specified value if: 11928 // - we are comparing array indices 11929 // - we are comparing fields of a union, or fields with the same access 11930 // Otherwise, the result is unspecified and thus the comparison is not a 11931 // constant expression. 11932 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 11933 Mismatch < RHSDesignator.Entries.size()) { 11934 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 11935 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 11936 if (!LF && !RF) 11937 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 11938 else if (!LF) 11939 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 11940 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 11941 << RF->getParent() << RF; 11942 else if (!RF) 11943 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 11944 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 11945 << LF->getParent() << LF; 11946 else if (!LF->getParent()->isUnion() && 11947 LF->getAccess() != RF->getAccess()) 11948 Info.CCEDiag(E, 11949 diag::note_constexpr_pointer_comparison_differing_access) 11950 << LF << LF->getAccess() << RF << RF->getAccess() 11951 << LF->getParent(); 11952 } 11953 } 11954 11955 // The comparison here must be unsigned, and performed with the same 11956 // width as the pointer. 11957 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 11958 uint64_t CompareLHS = LHSOffset.getQuantity(); 11959 uint64_t CompareRHS = RHSOffset.getQuantity(); 11960 assert(PtrSize <= 64 && "Unexpected pointer width"); 11961 uint64_t Mask = ~0ULL >> (64 - PtrSize); 11962 CompareLHS &= Mask; 11963 CompareRHS &= Mask; 11964 11965 // If there is a base and this is a relational operator, we can only 11966 // compare pointers within the object in question; otherwise, the result 11967 // depends on where the object is located in memory. 11968 if (!LHSValue.Base.isNull() && IsRelational) { 11969 QualType BaseTy = getType(LHSValue.Base); 11970 if (BaseTy->isIncompleteType()) 11971 return Error(E); 11972 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 11973 uint64_t OffsetLimit = Size.getQuantity(); 11974 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 11975 return Error(E); 11976 } 11977 11978 if (CompareLHS < CompareRHS) 11979 return Success(CmpResult::Less, E); 11980 if (CompareLHS > CompareRHS) 11981 return Success(CmpResult::Greater, E); 11982 return Success(CmpResult::Equal, E); 11983 } 11984 11985 if (LHSTy->isMemberPointerType()) { 11986 assert(IsEquality && "unexpected member pointer operation"); 11987 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 11988 11989 MemberPtr LHSValue, RHSValue; 11990 11991 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 11992 if (!LHSOK && !Info.noteFailure()) 11993 return false; 11994 11995 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11996 return false; 11997 11998 // C++11 [expr.eq]p2: 11999 // If both operands are null, they compare equal. Otherwise if only one is 12000 // null, they compare unequal. 12001 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12002 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12003 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12004 } 12005 12006 // Otherwise if either is a pointer to a virtual member function, the 12007 // result is unspecified. 12008 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12009 if (MD->isVirtual()) 12010 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12011 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12012 if (MD->isVirtual()) 12013 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12014 12015 // Otherwise they compare equal if and only if they would refer to the 12016 // same member of the same most derived object or the same subobject if 12017 // they were dereferenced with a hypothetical object of the associated 12018 // class type. 12019 bool Equal = LHSValue == RHSValue; 12020 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12021 } 12022 12023 if (LHSTy->isNullPtrType()) { 12024 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12025 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12026 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12027 // are compared, the result is true of the operator is <=, >= or ==, and 12028 // false otherwise. 12029 return Success(CmpResult::Equal, E); 12030 } 12031 12032 return DoAfter(); 12033 } 12034 12035 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12036 if (!CheckLiteralType(Info, E)) 12037 return false; 12038 12039 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12040 ComparisonCategoryResult CCR; 12041 switch (CR) { 12042 case CmpResult::Unequal: 12043 llvm_unreachable("should never produce Unequal for three-way comparison"); 12044 case CmpResult::Less: 12045 CCR = ComparisonCategoryResult::Less; 12046 break; 12047 case CmpResult::Equal: 12048 CCR = ComparisonCategoryResult::Equal; 12049 break; 12050 case CmpResult::Greater: 12051 CCR = ComparisonCategoryResult::Greater; 12052 break; 12053 case CmpResult::Unordered: 12054 CCR = ComparisonCategoryResult::Unordered; 12055 break; 12056 } 12057 // Evaluation succeeded. Lookup the information for the comparison category 12058 // type and fetch the VarDecl for the result. 12059 const ComparisonCategoryInfo &CmpInfo = 12060 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12061 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12062 // Check and evaluate the result as a constant expression. 12063 LValue LV; 12064 LV.set(VD); 12065 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12066 return false; 12067 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12068 }; 12069 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12070 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12071 }); 12072 } 12073 12074 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12075 // We don't call noteFailure immediately because the assignment happens after 12076 // we evaluate LHS and RHS. 12077 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12078 return Error(E); 12079 12080 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12081 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12082 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12083 12084 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12085 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12086 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12087 12088 if (E->isComparisonOp()) { 12089 // Evaluate builtin binary comparisons by evaluating them as three-way 12090 // comparisons and then translating the result. 12091 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12092 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12093 "should only produce Unequal for equality comparisons"); 12094 bool IsEqual = CR == CmpResult::Equal, 12095 IsLess = CR == CmpResult::Less, 12096 IsGreater = CR == CmpResult::Greater; 12097 auto Op = E->getOpcode(); 12098 switch (Op) { 12099 default: 12100 llvm_unreachable("unsupported binary operator"); 12101 case BO_EQ: 12102 case BO_NE: 12103 return Success(IsEqual == (Op == BO_EQ), E); 12104 case BO_LT: 12105 return Success(IsLess, E); 12106 case BO_GT: 12107 return Success(IsGreater, E); 12108 case BO_LE: 12109 return Success(IsEqual || IsLess, E); 12110 case BO_GE: 12111 return Success(IsEqual || IsGreater, E); 12112 } 12113 }; 12114 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12115 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12116 }); 12117 } 12118 12119 QualType LHSTy = E->getLHS()->getType(); 12120 QualType RHSTy = E->getRHS()->getType(); 12121 12122 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12123 E->getOpcode() == BO_Sub) { 12124 LValue LHSValue, RHSValue; 12125 12126 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12127 if (!LHSOK && !Info.noteFailure()) 12128 return false; 12129 12130 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12131 return false; 12132 12133 // Reject differing bases from the normal codepath; we special-case 12134 // comparisons to null. 12135 if (!HasSameBase(LHSValue, RHSValue)) { 12136 // Handle &&A - &&B. 12137 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12138 return Error(E); 12139 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12140 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12141 if (!LHSExpr || !RHSExpr) 12142 return Error(E); 12143 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12144 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12145 if (!LHSAddrExpr || !RHSAddrExpr) 12146 return Error(E); 12147 // Make sure both labels come from the same function. 12148 if (LHSAddrExpr->getLabel()->getDeclContext() != 12149 RHSAddrExpr->getLabel()->getDeclContext()) 12150 return Error(E); 12151 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12152 } 12153 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12154 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12155 12156 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12157 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12158 12159 // C++11 [expr.add]p6: 12160 // Unless both pointers point to elements of the same array object, or 12161 // one past the last element of the array object, the behavior is 12162 // undefined. 12163 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12164 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12165 RHSDesignator)) 12166 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12167 12168 QualType Type = E->getLHS()->getType(); 12169 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12170 12171 CharUnits ElementSize; 12172 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12173 return false; 12174 12175 // As an extension, a type may have zero size (empty struct or union in 12176 // C, array of zero length). Pointer subtraction in such cases has 12177 // undefined behavior, so is not constant. 12178 if (ElementSize.isZero()) { 12179 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12180 << ElementType; 12181 return false; 12182 } 12183 12184 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12185 // and produce incorrect results when it overflows. Such behavior 12186 // appears to be non-conforming, but is common, so perhaps we should 12187 // assume the standard intended for such cases to be undefined behavior 12188 // and check for them. 12189 12190 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12191 // overflow in the final conversion to ptrdiff_t. 12192 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12193 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12194 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12195 false); 12196 APSInt TrueResult = (LHS - RHS) / ElemSize; 12197 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12198 12199 if (Result.extend(65) != TrueResult && 12200 !HandleOverflow(Info, E, TrueResult, E->getType())) 12201 return false; 12202 return Success(Result, E); 12203 } 12204 12205 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12206 } 12207 12208 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12209 /// a result as the expression's type. 12210 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12211 const UnaryExprOrTypeTraitExpr *E) { 12212 switch(E->getKind()) { 12213 case UETT_PreferredAlignOf: 12214 case UETT_AlignOf: { 12215 if (E->isArgumentType()) 12216 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12217 E); 12218 else 12219 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12220 E); 12221 } 12222 12223 case UETT_VecStep: { 12224 QualType Ty = E->getTypeOfArgument(); 12225 12226 if (Ty->isVectorType()) { 12227 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12228 12229 // The vec_step built-in functions that take a 3-component 12230 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12231 if (n == 3) 12232 n = 4; 12233 12234 return Success(n, E); 12235 } else 12236 return Success(1, E); 12237 } 12238 12239 case UETT_SizeOf: { 12240 QualType SrcTy = E->getTypeOfArgument(); 12241 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12242 // the result is the size of the referenced type." 12243 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12244 SrcTy = Ref->getPointeeType(); 12245 12246 CharUnits Sizeof; 12247 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12248 return false; 12249 return Success(Sizeof, E); 12250 } 12251 case UETT_OpenMPRequiredSimdAlign: 12252 assert(E->isArgumentType()); 12253 return Success( 12254 Info.Ctx.toCharUnitsFromBits( 12255 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12256 .getQuantity(), 12257 E); 12258 } 12259 12260 llvm_unreachable("unknown expr/type trait"); 12261 } 12262 12263 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12264 CharUnits Result; 12265 unsigned n = OOE->getNumComponents(); 12266 if (n == 0) 12267 return Error(OOE); 12268 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12269 for (unsigned i = 0; i != n; ++i) { 12270 OffsetOfNode ON = OOE->getComponent(i); 12271 switch (ON.getKind()) { 12272 case OffsetOfNode::Array: { 12273 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12274 APSInt IdxResult; 12275 if (!EvaluateInteger(Idx, IdxResult, Info)) 12276 return false; 12277 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12278 if (!AT) 12279 return Error(OOE); 12280 CurrentType = AT->getElementType(); 12281 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12282 Result += IdxResult.getSExtValue() * ElementSize; 12283 break; 12284 } 12285 12286 case OffsetOfNode::Field: { 12287 FieldDecl *MemberDecl = ON.getField(); 12288 const RecordType *RT = CurrentType->getAs<RecordType>(); 12289 if (!RT) 12290 return Error(OOE); 12291 RecordDecl *RD = RT->getDecl(); 12292 if (RD->isInvalidDecl()) return false; 12293 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12294 unsigned i = MemberDecl->getFieldIndex(); 12295 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12296 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12297 CurrentType = MemberDecl->getType().getNonReferenceType(); 12298 break; 12299 } 12300 12301 case OffsetOfNode::Identifier: 12302 llvm_unreachable("dependent __builtin_offsetof"); 12303 12304 case OffsetOfNode::Base: { 12305 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12306 if (BaseSpec->isVirtual()) 12307 return Error(OOE); 12308 12309 // Find the layout of the class whose base we are looking into. 12310 const RecordType *RT = CurrentType->getAs<RecordType>(); 12311 if (!RT) 12312 return Error(OOE); 12313 RecordDecl *RD = RT->getDecl(); 12314 if (RD->isInvalidDecl()) return false; 12315 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12316 12317 // Find the base class itself. 12318 CurrentType = BaseSpec->getType(); 12319 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12320 if (!BaseRT) 12321 return Error(OOE); 12322 12323 // Add the offset to the base. 12324 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12325 break; 12326 } 12327 } 12328 } 12329 return Success(Result, OOE); 12330 } 12331 12332 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12333 switch (E->getOpcode()) { 12334 default: 12335 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12336 // See C99 6.6p3. 12337 return Error(E); 12338 case UO_Extension: 12339 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12340 // If so, we could clear the diagnostic ID. 12341 return Visit(E->getSubExpr()); 12342 case UO_Plus: 12343 // The result is just the value. 12344 return Visit(E->getSubExpr()); 12345 case UO_Minus: { 12346 if (!Visit(E->getSubExpr())) 12347 return false; 12348 if (!Result.isInt()) return Error(E); 12349 const APSInt &Value = Result.getInt(); 12350 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12351 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12352 E->getType())) 12353 return false; 12354 return Success(-Value, E); 12355 } 12356 case UO_Not: { 12357 if (!Visit(E->getSubExpr())) 12358 return false; 12359 if (!Result.isInt()) return Error(E); 12360 return Success(~Result.getInt(), E); 12361 } 12362 case UO_LNot: { 12363 bool bres; 12364 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12365 return false; 12366 return Success(!bres, E); 12367 } 12368 } 12369 } 12370 12371 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12372 /// result type is integer. 12373 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12374 const Expr *SubExpr = E->getSubExpr(); 12375 QualType DestType = E->getType(); 12376 QualType SrcType = SubExpr->getType(); 12377 12378 switch (E->getCastKind()) { 12379 case CK_BaseToDerived: 12380 case CK_DerivedToBase: 12381 case CK_UncheckedDerivedToBase: 12382 case CK_Dynamic: 12383 case CK_ToUnion: 12384 case CK_ArrayToPointerDecay: 12385 case CK_FunctionToPointerDecay: 12386 case CK_NullToPointer: 12387 case CK_NullToMemberPointer: 12388 case CK_BaseToDerivedMemberPointer: 12389 case CK_DerivedToBaseMemberPointer: 12390 case CK_ReinterpretMemberPointer: 12391 case CK_ConstructorConversion: 12392 case CK_IntegralToPointer: 12393 case CK_ToVoid: 12394 case CK_VectorSplat: 12395 case CK_IntegralToFloating: 12396 case CK_FloatingCast: 12397 case CK_CPointerToObjCPointerCast: 12398 case CK_BlockPointerToObjCPointerCast: 12399 case CK_AnyPointerToBlockPointerCast: 12400 case CK_ObjCObjectLValueCast: 12401 case CK_FloatingRealToComplex: 12402 case CK_FloatingComplexToReal: 12403 case CK_FloatingComplexCast: 12404 case CK_FloatingComplexToIntegralComplex: 12405 case CK_IntegralRealToComplex: 12406 case CK_IntegralComplexCast: 12407 case CK_IntegralComplexToFloatingComplex: 12408 case CK_BuiltinFnToFnPtr: 12409 case CK_ZeroToOCLOpaqueType: 12410 case CK_NonAtomicToAtomic: 12411 case CK_AddressSpaceConversion: 12412 case CK_IntToOCLSampler: 12413 case CK_FixedPointCast: 12414 case CK_IntegralToFixedPoint: 12415 llvm_unreachable("invalid cast kind for integral value"); 12416 12417 case CK_BitCast: 12418 case CK_Dependent: 12419 case CK_LValueBitCast: 12420 case CK_ARCProduceObject: 12421 case CK_ARCConsumeObject: 12422 case CK_ARCReclaimReturnedObject: 12423 case CK_ARCExtendBlockObject: 12424 case CK_CopyAndAutoreleaseBlockObject: 12425 return Error(E); 12426 12427 case CK_UserDefinedConversion: 12428 case CK_LValueToRValue: 12429 case CK_AtomicToNonAtomic: 12430 case CK_NoOp: 12431 case CK_LValueToRValueBitCast: 12432 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12433 12434 case CK_MemberPointerToBoolean: 12435 case CK_PointerToBoolean: 12436 case CK_IntegralToBoolean: 12437 case CK_FloatingToBoolean: 12438 case CK_BooleanToSignedIntegral: 12439 case CK_FloatingComplexToBoolean: 12440 case CK_IntegralComplexToBoolean: { 12441 bool BoolResult; 12442 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12443 return false; 12444 uint64_t IntResult = BoolResult; 12445 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12446 IntResult = (uint64_t)-1; 12447 return Success(IntResult, E); 12448 } 12449 12450 case CK_FixedPointToIntegral: { 12451 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12452 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12453 return false; 12454 bool Overflowed; 12455 llvm::APSInt Result = Src.convertToInt( 12456 Info.Ctx.getIntWidth(DestType), 12457 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12458 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12459 return false; 12460 return Success(Result, E); 12461 } 12462 12463 case CK_FixedPointToBoolean: { 12464 // Unsigned padding does not affect this. 12465 APValue Val; 12466 if (!Evaluate(Val, Info, SubExpr)) 12467 return false; 12468 return Success(Val.getFixedPoint().getBoolValue(), E); 12469 } 12470 12471 case CK_IntegralCast: { 12472 if (!Visit(SubExpr)) 12473 return false; 12474 12475 if (!Result.isInt()) { 12476 // Allow casts of address-of-label differences if they are no-ops 12477 // or narrowing. (The narrowing case isn't actually guaranteed to 12478 // be constant-evaluatable except in some narrow cases which are hard 12479 // to detect here. We let it through on the assumption the user knows 12480 // what they are doing.) 12481 if (Result.isAddrLabelDiff()) 12482 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12483 // Only allow casts of lvalues if they are lossless. 12484 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12485 } 12486 12487 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12488 Result.getInt()), E); 12489 } 12490 12491 case CK_PointerToIntegral: { 12492 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12493 12494 LValue LV; 12495 if (!EvaluatePointer(SubExpr, LV, Info)) 12496 return false; 12497 12498 if (LV.getLValueBase()) { 12499 // Only allow based lvalue casts if they are lossless. 12500 // FIXME: Allow a larger integer size than the pointer size, and allow 12501 // narrowing back down to pointer width in subsequent integral casts. 12502 // FIXME: Check integer type's active bits, not its type size. 12503 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12504 return Error(E); 12505 12506 LV.Designator.setInvalid(); 12507 LV.moveInto(Result); 12508 return true; 12509 } 12510 12511 APSInt AsInt; 12512 APValue V; 12513 LV.moveInto(V); 12514 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12515 llvm_unreachable("Can't cast this!"); 12516 12517 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 12518 } 12519 12520 case CK_IntegralComplexToReal: { 12521 ComplexValue C; 12522 if (!EvaluateComplex(SubExpr, C, Info)) 12523 return false; 12524 return Success(C.getComplexIntReal(), E); 12525 } 12526 12527 case CK_FloatingToIntegral: { 12528 APFloat F(0.0); 12529 if (!EvaluateFloat(SubExpr, F, Info)) 12530 return false; 12531 12532 APSInt Value; 12533 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 12534 return false; 12535 return Success(Value, E); 12536 } 12537 } 12538 12539 llvm_unreachable("unknown cast resulting in integral value"); 12540 } 12541 12542 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12543 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12544 ComplexValue LV; 12545 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12546 return false; 12547 if (!LV.isComplexInt()) 12548 return Error(E); 12549 return Success(LV.getComplexIntReal(), E); 12550 } 12551 12552 return Visit(E->getSubExpr()); 12553 } 12554 12555 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12556 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 12557 ComplexValue LV; 12558 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12559 return false; 12560 if (!LV.isComplexInt()) 12561 return Error(E); 12562 return Success(LV.getComplexIntImag(), E); 12563 } 12564 12565 VisitIgnoredValue(E->getSubExpr()); 12566 return Success(0, E); 12567 } 12568 12569 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 12570 return Success(E->getPackLength(), E); 12571 } 12572 12573 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 12574 return Success(E->getValue(), E); 12575 } 12576 12577 bool IntExprEvaluator::VisitConceptSpecializationExpr( 12578 const ConceptSpecializationExpr *E) { 12579 return Success(E->isSatisfied(), E); 12580 } 12581 12582 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 12583 return Success(E->isSatisfied(), E); 12584 } 12585 12586 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12587 switch (E->getOpcode()) { 12588 default: 12589 // Invalid unary operators 12590 return Error(E); 12591 case UO_Plus: 12592 // The result is just the value. 12593 return Visit(E->getSubExpr()); 12594 case UO_Minus: { 12595 if (!Visit(E->getSubExpr())) return false; 12596 if (!Result.isFixedPoint()) 12597 return Error(E); 12598 bool Overflowed; 12599 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 12600 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 12601 return false; 12602 return Success(Negated, E); 12603 } 12604 case UO_LNot: { 12605 bool bres; 12606 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12607 return false; 12608 return Success(!bres, E); 12609 } 12610 } 12611 } 12612 12613 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 12614 const Expr *SubExpr = E->getSubExpr(); 12615 QualType DestType = E->getType(); 12616 assert(DestType->isFixedPointType() && 12617 "Expected destination type to be a fixed point type"); 12618 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 12619 12620 switch (E->getCastKind()) { 12621 case CK_FixedPointCast: { 12622 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 12623 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12624 return false; 12625 bool Overflowed; 12626 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 12627 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12628 return false; 12629 return Success(Result, E); 12630 } 12631 case CK_IntegralToFixedPoint: { 12632 APSInt Src; 12633 if (!EvaluateInteger(SubExpr, Src, Info)) 12634 return false; 12635 12636 bool Overflowed; 12637 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 12638 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 12639 12640 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) 12641 return false; 12642 12643 return Success(IntResult, E); 12644 } 12645 case CK_NoOp: 12646 case CK_LValueToRValue: 12647 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12648 default: 12649 return Error(E); 12650 } 12651 } 12652 12653 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12654 const Expr *LHS = E->getLHS(); 12655 const Expr *RHS = E->getRHS(); 12656 FixedPointSemantics ResultFXSema = 12657 Info.Ctx.getFixedPointSemantics(E->getType()); 12658 12659 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 12660 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 12661 return false; 12662 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 12663 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 12664 return false; 12665 12666 switch (E->getOpcode()) { 12667 case BO_Add: { 12668 bool AddOverflow, ConversionOverflow; 12669 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) 12670 .convert(ResultFXSema, &ConversionOverflow); 12671 if ((AddOverflow || ConversionOverflow) && 12672 !HandleOverflow(Info, E, Result, E->getType())) 12673 return false; 12674 return Success(Result, E); 12675 } 12676 default: 12677 return false; 12678 } 12679 llvm_unreachable("Should've exited before this"); 12680 } 12681 12682 //===----------------------------------------------------------------------===// 12683 // Float Evaluation 12684 //===----------------------------------------------------------------------===// 12685 12686 namespace { 12687 class FloatExprEvaluator 12688 : public ExprEvaluatorBase<FloatExprEvaluator> { 12689 APFloat &Result; 12690 public: 12691 FloatExprEvaluator(EvalInfo &info, APFloat &result) 12692 : ExprEvaluatorBaseTy(info), Result(result) {} 12693 12694 bool Success(const APValue &V, const Expr *e) { 12695 Result = V.getFloat(); 12696 return true; 12697 } 12698 12699 bool ZeroInitialization(const Expr *E) { 12700 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 12701 return true; 12702 } 12703 12704 bool VisitCallExpr(const CallExpr *E); 12705 12706 bool VisitUnaryOperator(const UnaryOperator *E); 12707 bool VisitBinaryOperator(const BinaryOperator *E); 12708 bool VisitFloatingLiteral(const FloatingLiteral *E); 12709 bool VisitCastExpr(const CastExpr *E); 12710 12711 bool VisitUnaryReal(const UnaryOperator *E); 12712 bool VisitUnaryImag(const UnaryOperator *E); 12713 12714 // FIXME: Missing: array subscript of vector, member of vector 12715 }; 12716 } // end anonymous namespace 12717 12718 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 12719 assert(E->isRValue() && E->getType()->isRealFloatingType()); 12720 return FloatExprEvaluator(Info, Result).Visit(E); 12721 } 12722 12723 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 12724 QualType ResultTy, 12725 const Expr *Arg, 12726 bool SNaN, 12727 llvm::APFloat &Result) { 12728 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 12729 if (!S) return false; 12730 12731 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 12732 12733 llvm::APInt fill; 12734 12735 // Treat empty strings as if they were zero. 12736 if (S->getString().empty()) 12737 fill = llvm::APInt(32, 0); 12738 else if (S->getString().getAsInteger(0, fill)) 12739 return false; 12740 12741 if (Context.getTargetInfo().isNan2008()) { 12742 if (SNaN) 12743 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 12744 else 12745 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 12746 } else { 12747 // Prior to IEEE 754-2008, architectures were allowed to choose whether 12748 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 12749 // a different encoding to what became a standard in 2008, and for pre- 12750 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 12751 // sNaN. This is now known as "legacy NaN" encoding. 12752 if (SNaN) 12753 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 12754 else 12755 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 12756 } 12757 12758 return true; 12759 } 12760 12761 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 12762 switch (E->getBuiltinCallee()) { 12763 default: 12764 return ExprEvaluatorBaseTy::VisitCallExpr(E); 12765 12766 case Builtin::BI__builtin_huge_val: 12767 case Builtin::BI__builtin_huge_valf: 12768 case Builtin::BI__builtin_huge_vall: 12769 case Builtin::BI__builtin_huge_valf128: 12770 case Builtin::BI__builtin_inf: 12771 case Builtin::BI__builtin_inff: 12772 case Builtin::BI__builtin_infl: 12773 case Builtin::BI__builtin_inff128: { 12774 const llvm::fltSemantics &Sem = 12775 Info.Ctx.getFloatTypeSemantics(E->getType()); 12776 Result = llvm::APFloat::getInf(Sem); 12777 return true; 12778 } 12779 12780 case Builtin::BI__builtin_nans: 12781 case Builtin::BI__builtin_nansf: 12782 case Builtin::BI__builtin_nansl: 12783 case Builtin::BI__builtin_nansf128: 12784 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 12785 true, Result)) 12786 return Error(E); 12787 return true; 12788 12789 case Builtin::BI__builtin_nan: 12790 case Builtin::BI__builtin_nanf: 12791 case Builtin::BI__builtin_nanl: 12792 case Builtin::BI__builtin_nanf128: 12793 // If this is __builtin_nan() turn this into a nan, otherwise we 12794 // can't constant fold it. 12795 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 12796 false, Result)) 12797 return Error(E); 12798 return true; 12799 12800 case Builtin::BI__builtin_fabs: 12801 case Builtin::BI__builtin_fabsf: 12802 case Builtin::BI__builtin_fabsl: 12803 case Builtin::BI__builtin_fabsf128: 12804 if (!EvaluateFloat(E->getArg(0), Result, Info)) 12805 return false; 12806 12807 if (Result.isNegative()) 12808 Result.changeSign(); 12809 return true; 12810 12811 // FIXME: Builtin::BI__builtin_powi 12812 // FIXME: Builtin::BI__builtin_powif 12813 // FIXME: Builtin::BI__builtin_powil 12814 12815 case Builtin::BI__builtin_copysign: 12816 case Builtin::BI__builtin_copysignf: 12817 case Builtin::BI__builtin_copysignl: 12818 case Builtin::BI__builtin_copysignf128: { 12819 APFloat RHS(0.); 12820 if (!EvaluateFloat(E->getArg(0), Result, Info) || 12821 !EvaluateFloat(E->getArg(1), RHS, Info)) 12822 return false; 12823 Result.copySign(RHS); 12824 return true; 12825 } 12826 } 12827 } 12828 12829 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12830 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12831 ComplexValue CV; 12832 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 12833 return false; 12834 Result = CV.FloatReal; 12835 return true; 12836 } 12837 12838 return Visit(E->getSubExpr()); 12839 } 12840 12841 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12842 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12843 ComplexValue CV; 12844 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 12845 return false; 12846 Result = CV.FloatImag; 12847 return true; 12848 } 12849 12850 VisitIgnoredValue(E->getSubExpr()); 12851 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 12852 Result = llvm::APFloat::getZero(Sem); 12853 return true; 12854 } 12855 12856 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12857 switch (E->getOpcode()) { 12858 default: return Error(E); 12859 case UO_Plus: 12860 return EvaluateFloat(E->getSubExpr(), Result, Info); 12861 case UO_Minus: 12862 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 12863 return false; 12864 Result.changeSign(); 12865 return true; 12866 } 12867 } 12868 12869 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12870 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12871 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12872 12873 APFloat RHS(0.0); 12874 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 12875 if (!LHSOK && !Info.noteFailure()) 12876 return false; 12877 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 12878 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 12879 } 12880 12881 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 12882 Result = E->getValue(); 12883 return true; 12884 } 12885 12886 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 12887 const Expr* SubExpr = E->getSubExpr(); 12888 12889 switch (E->getCastKind()) { 12890 default: 12891 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12892 12893 case CK_IntegralToFloating: { 12894 APSInt IntResult; 12895 return EvaluateInteger(SubExpr, IntResult, Info) && 12896 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 12897 E->getType(), Result); 12898 } 12899 12900 case CK_FloatingCast: { 12901 if (!Visit(SubExpr)) 12902 return false; 12903 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 12904 Result); 12905 } 12906 12907 case CK_FloatingComplexToReal: { 12908 ComplexValue V; 12909 if (!EvaluateComplex(SubExpr, V, Info)) 12910 return false; 12911 Result = V.getComplexFloatReal(); 12912 return true; 12913 } 12914 } 12915 } 12916 12917 //===----------------------------------------------------------------------===// 12918 // Complex Evaluation (for float and integer) 12919 //===----------------------------------------------------------------------===// 12920 12921 namespace { 12922 class ComplexExprEvaluator 12923 : public ExprEvaluatorBase<ComplexExprEvaluator> { 12924 ComplexValue &Result; 12925 12926 public: 12927 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 12928 : ExprEvaluatorBaseTy(info), Result(Result) {} 12929 12930 bool Success(const APValue &V, const Expr *e) { 12931 Result.setFrom(V); 12932 return true; 12933 } 12934 12935 bool ZeroInitialization(const Expr *E); 12936 12937 //===--------------------------------------------------------------------===// 12938 // Visitor Methods 12939 //===--------------------------------------------------------------------===// 12940 12941 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 12942 bool VisitCastExpr(const CastExpr *E); 12943 bool VisitBinaryOperator(const BinaryOperator *E); 12944 bool VisitUnaryOperator(const UnaryOperator *E); 12945 bool VisitInitListExpr(const InitListExpr *E); 12946 }; 12947 } // end anonymous namespace 12948 12949 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 12950 EvalInfo &Info) { 12951 assert(E->isRValue() && E->getType()->isAnyComplexType()); 12952 return ComplexExprEvaluator(Info, Result).Visit(E); 12953 } 12954 12955 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 12956 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 12957 if (ElemTy->isRealFloatingType()) { 12958 Result.makeComplexFloat(); 12959 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 12960 Result.FloatReal = Zero; 12961 Result.FloatImag = Zero; 12962 } else { 12963 Result.makeComplexInt(); 12964 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 12965 Result.IntReal = Zero; 12966 Result.IntImag = Zero; 12967 } 12968 return true; 12969 } 12970 12971 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 12972 const Expr* SubExpr = E->getSubExpr(); 12973 12974 if (SubExpr->getType()->isRealFloatingType()) { 12975 Result.makeComplexFloat(); 12976 APFloat &Imag = Result.FloatImag; 12977 if (!EvaluateFloat(SubExpr, Imag, Info)) 12978 return false; 12979 12980 Result.FloatReal = APFloat(Imag.getSemantics()); 12981 return true; 12982 } else { 12983 assert(SubExpr->getType()->isIntegerType() && 12984 "Unexpected imaginary literal."); 12985 12986 Result.makeComplexInt(); 12987 APSInt &Imag = Result.IntImag; 12988 if (!EvaluateInteger(SubExpr, Imag, Info)) 12989 return false; 12990 12991 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 12992 return true; 12993 } 12994 } 12995 12996 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 12997 12998 switch (E->getCastKind()) { 12999 case CK_BitCast: 13000 case CK_BaseToDerived: 13001 case CK_DerivedToBase: 13002 case CK_UncheckedDerivedToBase: 13003 case CK_Dynamic: 13004 case CK_ToUnion: 13005 case CK_ArrayToPointerDecay: 13006 case CK_FunctionToPointerDecay: 13007 case CK_NullToPointer: 13008 case CK_NullToMemberPointer: 13009 case CK_BaseToDerivedMemberPointer: 13010 case CK_DerivedToBaseMemberPointer: 13011 case CK_MemberPointerToBoolean: 13012 case CK_ReinterpretMemberPointer: 13013 case CK_ConstructorConversion: 13014 case CK_IntegralToPointer: 13015 case CK_PointerToIntegral: 13016 case CK_PointerToBoolean: 13017 case CK_ToVoid: 13018 case CK_VectorSplat: 13019 case CK_IntegralCast: 13020 case CK_BooleanToSignedIntegral: 13021 case CK_IntegralToBoolean: 13022 case CK_IntegralToFloating: 13023 case CK_FloatingToIntegral: 13024 case CK_FloatingToBoolean: 13025 case CK_FloatingCast: 13026 case CK_CPointerToObjCPointerCast: 13027 case CK_BlockPointerToObjCPointerCast: 13028 case CK_AnyPointerToBlockPointerCast: 13029 case CK_ObjCObjectLValueCast: 13030 case CK_FloatingComplexToReal: 13031 case CK_FloatingComplexToBoolean: 13032 case CK_IntegralComplexToReal: 13033 case CK_IntegralComplexToBoolean: 13034 case CK_ARCProduceObject: 13035 case CK_ARCConsumeObject: 13036 case CK_ARCReclaimReturnedObject: 13037 case CK_ARCExtendBlockObject: 13038 case CK_CopyAndAutoreleaseBlockObject: 13039 case CK_BuiltinFnToFnPtr: 13040 case CK_ZeroToOCLOpaqueType: 13041 case CK_NonAtomicToAtomic: 13042 case CK_AddressSpaceConversion: 13043 case CK_IntToOCLSampler: 13044 case CK_FixedPointCast: 13045 case CK_FixedPointToBoolean: 13046 case CK_FixedPointToIntegral: 13047 case CK_IntegralToFixedPoint: 13048 llvm_unreachable("invalid cast kind for complex value"); 13049 13050 case CK_LValueToRValue: 13051 case CK_AtomicToNonAtomic: 13052 case CK_NoOp: 13053 case CK_LValueToRValueBitCast: 13054 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13055 13056 case CK_Dependent: 13057 case CK_LValueBitCast: 13058 case CK_UserDefinedConversion: 13059 return Error(E); 13060 13061 case CK_FloatingRealToComplex: { 13062 APFloat &Real = Result.FloatReal; 13063 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13064 return false; 13065 13066 Result.makeComplexFloat(); 13067 Result.FloatImag = APFloat(Real.getSemantics()); 13068 return true; 13069 } 13070 13071 case CK_FloatingComplexCast: { 13072 if (!Visit(E->getSubExpr())) 13073 return false; 13074 13075 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13076 QualType From 13077 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13078 13079 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13080 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13081 } 13082 13083 case CK_FloatingComplexToIntegralComplex: { 13084 if (!Visit(E->getSubExpr())) 13085 return false; 13086 13087 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13088 QualType From 13089 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13090 Result.makeComplexInt(); 13091 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13092 To, Result.IntReal) && 13093 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13094 To, Result.IntImag); 13095 } 13096 13097 case CK_IntegralRealToComplex: { 13098 APSInt &Real = Result.IntReal; 13099 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13100 return false; 13101 13102 Result.makeComplexInt(); 13103 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13104 return true; 13105 } 13106 13107 case CK_IntegralComplexCast: { 13108 if (!Visit(E->getSubExpr())) 13109 return false; 13110 13111 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13112 QualType From 13113 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13114 13115 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13116 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13117 return true; 13118 } 13119 13120 case CK_IntegralComplexToFloatingComplex: { 13121 if (!Visit(E->getSubExpr())) 13122 return false; 13123 13124 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13125 QualType From 13126 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13127 Result.makeComplexFloat(); 13128 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13129 To, Result.FloatReal) && 13130 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13131 To, Result.FloatImag); 13132 } 13133 } 13134 13135 llvm_unreachable("unknown cast resulting in complex value"); 13136 } 13137 13138 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13139 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13140 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13141 13142 // Track whether the LHS or RHS is real at the type system level. When this is 13143 // the case we can simplify our evaluation strategy. 13144 bool LHSReal = false, RHSReal = false; 13145 13146 bool LHSOK; 13147 if (E->getLHS()->getType()->isRealFloatingType()) { 13148 LHSReal = true; 13149 APFloat &Real = Result.FloatReal; 13150 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13151 if (LHSOK) { 13152 Result.makeComplexFloat(); 13153 Result.FloatImag = APFloat(Real.getSemantics()); 13154 } 13155 } else { 13156 LHSOK = Visit(E->getLHS()); 13157 } 13158 if (!LHSOK && !Info.noteFailure()) 13159 return false; 13160 13161 ComplexValue RHS; 13162 if (E->getRHS()->getType()->isRealFloatingType()) { 13163 RHSReal = true; 13164 APFloat &Real = RHS.FloatReal; 13165 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13166 return false; 13167 RHS.makeComplexFloat(); 13168 RHS.FloatImag = APFloat(Real.getSemantics()); 13169 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13170 return false; 13171 13172 assert(!(LHSReal && RHSReal) && 13173 "Cannot have both operands of a complex operation be real."); 13174 switch (E->getOpcode()) { 13175 default: return Error(E); 13176 case BO_Add: 13177 if (Result.isComplexFloat()) { 13178 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13179 APFloat::rmNearestTiesToEven); 13180 if (LHSReal) 13181 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13182 else if (!RHSReal) 13183 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13184 APFloat::rmNearestTiesToEven); 13185 } else { 13186 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13187 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13188 } 13189 break; 13190 case BO_Sub: 13191 if (Result.isComplexFloat()) { 13192 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13193 APFloat::rmNearestTiesToEven); 13194 if (LHSReal) { 13195 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13196 Result.getComplexFloatImag().changeSign(); 13197 } else if (!RHSReal) { 13198 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13199 APFloat::rmNearestTiesToEven); 13200 } 13201 } else { 13202 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13203 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13204 } 13205 break; 13206 case BO_Mul: 13207 if (Result.isComplexFloat()) { 13208 // This is an implementation of complex multiplication according to the 13209 // constraints laid out in C11 Annex G. The implementation uses the 13210 // following naming scheme: 13211 // (a + ib) * (c + id) 13212 ComplexValue LHS = Result; 13213 APFloat &A = LHS.getComplexFloatReal(); 13214 APFloat &B = LHS.getComplexFloatImag(); 13215 APFloat &C = RHS.getComplexFloatReal(); 13216 APFloat &D = RHS.getComplexFloatImag(); 13217 APFloat &ResR = Result.getComplexFloatReal(); 13218 APFloat &ResI = Result.getComplexFloatImag(); 13219 if (LHSReal) { 13220 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13221 ResR = A * C; 13222 ResI = A * D; 13223 } else if (RHSReal) { 13224 ResR = C * A; 13225 ResI = C * B; 13226 } else { 13227 // In the fully general case, we need to handle NaNs and infinities 13228 // robustly. 13229 APFloat AC = A * C; 13230 APFloat BD = B * D; 13231 APFloat AD = A * D; 13232 APFloat BC = B * C; 13233 ResR = AC - BD; 13234 ResI = AD + BC; 13235 if (ResR.isNaN() && ResI.isNaN()) { 13236 bool Recalc = false; 13237 if (A.isInfinity() || B.isInfinity()) { 13238 A = APFloat::copySign( 13239 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13240 B = APFloat::copySign( 13241 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13242 if (C.isNaN()) 13243 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13244 if (D.isNaN()) 13245 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13246 Recalc = true; 13247 } 13248 if (C.isInfinity() || D.isInfinity()) { 13249 C = APFloat::copySign( 13250 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13251 D = APFloat::copySign( 13252 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13253 if (A.isNaN()) 13254 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13255 if (B.isNaN()) 13256 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13257 Recalc = true; 13258 } 13259 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13260 AD.isInfinity() || BC.isInfinity())) { 13261 if (A.isNaN()) 13262 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13263 if (B.isNaN()) 13264 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13265 if (C.isNaN()) 13266 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13267 if (D.isNaN()) 13268 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13269 Recalc = true; 13270 } 13271 if (Recalc) { 13272 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13273 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13274 } 13275 } 13276 } 13277 } else { 13278 ComplexValue LHS = Result; 13279 Result.getComplexIntReal() = 13280 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13281 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13282 Result.getComplexIntImag() = 13283 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13284 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13285 } 13286 break; 13287 case BO_Div: 13288 if (Result.isComplexFloat()) { 13289 // This is an implementation of complex division according to the 13290 // constraints laid out in C11 Annex G. The implementation uses the 13291 // following naming scheme: 13292 // (a + ib) / (c + id) 13293 ComplexValue LHS = Result; 13294 APFloat &A = LHS.getComplexFloatReal(); 13295 APFloat &B = LHS.getComplexFloatImag(); 13296 APFloat &C = RHS.getComplexFloatReal(); 13297 APFloat &D = RHS.getComplexFloatImag(); 13298 APFloat &ResR = Result.getComplexFloatReal(); 13299 APFloat &ResI = Result.getComplexFloatImag(); 13300 if (RHSReal) { 13301 ResR = A / C; 13302 ResI = B / C; 13303 } else { 13304 if (LHSReal) { 13305 // No real optimizations we can do here, stub out with zero. 13306 B = APFloat::getZero(A.getSemantics()); 13307 } 13308 int DenomLogB = 0; 13309 APFloat MaxCD = maxnum(abs(C), abs(D)); 13310 if (MaxCD.isFinite()) { 13311 DenomLogB = ilogb(MaxCD); 13312 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13313 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13314 } 13315 APFloat Denom = C * C + D * D; 13316 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13317 APFloat::rmNearestTiesToEven); 13318 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13319 APFloat::rmNearestTiesToEven); 13320 if (ResR.isNaN() && ResI.isNaN()) { 13321 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13322 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13323 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13324 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13325 D.isFinite()) { 13326 A = APFloat::copySign( 13327 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13328 B = APFloat::copySign( 13329 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13330 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13331 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13332 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13333 C = APFloat::copySign( 13334 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13335 D = APFloat::copySign( 13336 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13337 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13338 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13339 } 13340 } 13341 } 13342 } else { 13343 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13344 return Error(E, diag::note_expr_divide_by_zero); 13345 13346 ComplexValue LHS = Result; 13347 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13348 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13349 Result.getComplexIntReal() = 13350 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13351 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13352 Result.getComplexIntImag() = 13353 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13354 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13355 } 13356 break; 13357 } 13358 13359 return true; 13360 } 13361 13362 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13363 // Get the operand value into 'Result'. 13364 if (!Visit(E->getSubExpr())) 13365 return false; 13366 13367 switch (E->getOpcode()) { 13368 default: 13369 return Error(E); 13370 case UO_Extension: 13371 return true; 13372 case UO_Plus: 13373 // The result is always just the subexpr. 13374 return true; 13375 case UO_Minus: 13376 if (Result.isComplexFloat()) { 13377 Result.getComplexFloatReal().changeSign(); 13378 Result.getComplexFloatImag().changeSign(); 13379 } 13380 else { 13381 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13382 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13383 } 13384 return true; 13385 case UO_Not: 13386 if (Result.isComplexFloat()) 13387 Result.getComplexFloatImag().changeSign(); 13388 else 13389 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13390 return true; 13391 } 13392 } 13393 13394 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13395 if (E->getNumInits() == 2) { 13396 if (E->getType()->isComplexType()) { 13397 Result.makeComplexFloat(); 13398 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13399 return false; 13400 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13401 return false; 13402 } else { 13403 Result.makeComplexInt(); 13404 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13405 return false; 13406 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13407 return false; 13408 } 13409 return true; 13410 } 13411 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13412 } 13413 13414 //===----------------------------------------------------------------------===// 13415 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13416 // implicit conversion. 13417 //===----------------------------------------------------------------------===// 13418 13419 namespace { 13420 class AtomicExprEvaluator : 13421 public ExprEvaluatorBase<AtomicExprEvaluator> { 13422 const LValue *This; 13423 APValue &Result; 13424 public: 13425 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13426 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13427 13428 bool Success(const APValue &V, const Expr *E) { 13429 Result = V; 13430 return true; 13431 } 13432 13433 bool ZeroInitialization(const Expr *E) { 13434 ImplicitValueInitExpr VIE( 13435 E->getType()->castAs<AtomicType>()->getValueType()); 13436 // For atomic-qualified class (and array) types in C++, initialize the 13437 // _Atomic-wrapped subobject directly, in-place. 13438 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 13439 : Evaluate(Result, Info, &VIE); 13440 } 13441 13442 bool VisitCastExpr(const CastExpr *E) { 13443 switch (E->getCastKind()) { 13444 default: 13445 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13446 case CK_NonAtomicToAtomic: 13447 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 13448 : Evaluate(Result, Info, E->getSubExpr()); 13449 } 13450 } 13451 }; 13452 } // end anonymous namespace 13453 13454 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 13455 EvalInfo &Info) { 13456 assert(E->isRValue() && E->getType()->isAtomicType()); 13457 return AtomicExprEvaluator(Info, This, Result).Visit(E); 13458 } 13459 13460 //===----------------------------------------------------------------------===// 13461 // Void expression evaluation, primarily for a cast to void on the LHS of a 13462 // comma operator 13463 //===----------------------------------------------------------------------===// 13464 13465 namespace { 13466 class VoidExprEvaluator 13467 : public ExprEvaluatorBase<VoidExprEvaluator> { 13468 public: 13469 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 13470 13471 bool Success(const APValue &V, const Expr *e) { return true; } 13472 13473 bool ZeroInitialization(const Expr *E) { return true; } 13474 13475 bool VisitCastExpr(const CastExpr *E) { 13476 switch (E->getCastKind()) { 13477 default: 13478 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13479 case CK_ToVoid: 13480 VisitIgnoredValue(E->getSubExpr()); 13481 return true; 13482 } 13483 } 13484 13485 bool VisitCallExpr(const CallExpr *E) { 13486 switch (E->getBuiltinCallee()) { 13487 case Builtin::BI__assume: 13488 case Builtin::BI__builtin_assume: 13489 // The argument is not evaluated! 13490 return true; 13491 13492 case Builtin::BI__builtin_operator_delete: 13493 return HandleOperatorDeleteCall(Info, E); 13494 13495 default: 13496 break; 13497 } 13498 13499 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13500 } 13501 13502 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 13503 }; 13504 } // end anonymous namespace 13505 13506 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 13507 // We cannot speculatively evaluate a delete expression. 13508 if (Info.SpeculativeEvaluationDepth) 13509 return false; 13510 13511 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 13512 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 13513 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13514 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 13515 return false; 13516 } 13517 13518 const Expr *Arg = E->getArgument(); 13519 13520 LValue Pointer; 13521 if (!EvaluatePointer(Arg, Pointer, Info)) 13522 return false; 13523 if (Pointer.Designator.Invalid) 13524 return false; 13525 13526 // Deleting a null pointer has no effect. 13527 if (Pointer.isNullPointer()) { 13528 // This is the only case where we need to produce an extension warning: 13529 // the only other way we can succeed is if we find a dynamic allocation, 13530 // and we will have warned when we allocated it in that case. 13531 if (!Info.getLangOpts().CPlusPlus2a) 13532 Info.CCEDiag(E, diag::note_constexpr_new); 13533 return true; 13534 } 13535 13536 Optional<DynAlloc *> Alloc = CheckDeleteKind( 13537 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 13538 if (!Alloc) 13539 return false; 13540 QualType AllocType = Pointer.Base.getDynamicAllocType(); 13541 13542 // For the non-array case, the designator must be empty if the static type 13543 // does not have a virtual destructor. 13544 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 13545 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 13546 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 13547 << Arg->getType()->getPointeeType() << AllocType; 13548 return false; 13549 } 13550 13551 // For a class type with a virtual destructor, the selected operator delete 13552 // is the one looked up when building the destructor. 13553 if (!E->isArrayForm() && !E->isGlobalDelete()) { 13554 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 13555 if (VirtualDelete && 13556 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 13557 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13558 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 13559 return false; 13560 } 13561 } 13562 13563 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 13564 (*Alloc)->Value, AllocType)) 13565 return false; 13566 13567 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 13568 // The element was already erased. This means the destructor call also 13569 // deleted the object. 13570 // FIXME: This probably results in undefined behavior before we get this 13571 // far, and should be diagnosed elsewhere first. 13572 Info.FFDiag(E, diag::note_constexpr_double_delete); 13573 return false; 13574 } 13575 13576 return true; 13577 } 13578 13579 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 13580 assert(E->isRValue() && E->getType()->isVoidType()); 13581 return VoidExprEvaluator(Info).Visit(E); 13582 } 13583 13584 //===----------------------------------------------------------------------===// 13585 // Top level Expr::EvaluateAsRValue method. 13586 //===----------------------------------------------------------------------===// 13587 13588 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 13589 // In C, function designators are not lvalues, but we evaluate them as if they 13590 // are. 13591 QualType T = E->getType(); 13592 if (E->isGLValue() || T->isFunctionType()) { 13593 LValue LV; 13594 if (!EvaluateLValue(E, LV, Info)) 13595 return false; 13596 LV.moveInto(Result); 13597 } else if (T->isVectorType()) { 13598 if (!EvaluateVector(E, Result, Info)) 13599 return false; 13600 } else if (T->isIntegralOrEnumerationType()) { 13601 if (!IntExprEvaluator(Info, Result).Visit(E)) 13602 return false; 13603 } else if (T->hasPointerRepresentation()) { 13604 LValue LV; 13605 if (!EvaluatePointer(E, LV, Info)) 13606 return false; 13607 LV.moveInto(Result); 13608 } else if (T->isRealFloatingType()) { 13609 llvm::APFloat F(0.0); 13610 if (!EvaluateFloat(E, F, Info)) 13611 return false; 13612 Result = APValue(F); 13613 } else if (T->isAnyComplexType()) { 13614 ComplexValue C; 13615 if (!EvaluateComplex(E, C, Info)) 13616 return false; 13617 C.moveInto(Result); 13618 } else if (T->isFixedPointType()) { 13619 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 13620 } else if (T->isMemberPointerType()) { 13621 MemberPtr P; 13622 if (!EvaluateMemberPointer(E, P, Info)) 13623 return false; 13624 P.moveInto(Result); 13625 return true; 13626 } else if (T->isArrayType()) { 13627 LValue LV; 13628 APValue &Value = 13629 Info.CurrentCall->createTemporary(E, T, false, LV); 13630 if (!EvaluateArray(E, LV, Value, Info)) 13631 return false; 13632 Result = Value; 13633 } else if (T->isRecordType()) { 13634 LValue LV; 13635 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 13636 if (!EvaluateRecord(E, LV, Value, Info)) 13637 return false; 13638 Result = Value; 13639 } else if (T->isVoidType()) { 13640 if (!Info.getLangOpts().CPlusPlus11) 13641 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 13642 << E->getType(); 13643 if (!EvaluateVoid(E, Info)) 13644 return false; 13645 } else if (T->isAtomicType()) { 13646 QualType Unqual = T.getAtomicUnqualifiedType(); 13647 if (Unqual->isArrayType() || Unqual->isRecordType()) { 13648 LValue LV; 13649 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 13650 if (!EvaluateAtomic(E, &LV, Value, Info)) 13651 return false; 13652 } else { 13653 if (!EvaluateAtomic(E, nullptr, Result, Info)) 13654 return false; 13655 } 13656 } else if (Info.getLangOpts().CPlusPlus11) { 13657 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 13658 return false; 13659 } else { 13660 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 13661 return false; 13662 } 13663 13664 return true; 13665 } 13666 13667 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 13668 /// cases, the in-place evaluation is essential, since later initializers for 13669 /// an object can indirectly refer to subobjects which were initialized earlier. 13670 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 13671 const Expr *E, bool AllowNonLiteralTypes) { 13672 assert(!E->isValueDependent()); 13673 13674 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 13675 return false; 13676 13677 if (E->isRValue()) { 13678 // Evaluate arrays and record types in-place, so that later initializers can 13679 // refer to earlier-initialized members of the object. 13680 QualType T = E->getType(); 13681 if (T->isArrayType()) 13682 return EvaluateArray(E, This, Result, Info); 13683 else if (T->isRecordType()) 13684 return EvaluateRecord(E, This, Result, Info); 13685 else if (T->isAtomicType()) { 13686 QualType Unqual = T.getAtomicUnqualifiedType(); 13687 if (Unqual->isArrayType() || Unqual->isRecordType()) 13688 return EvaluateAtomic(E, &This, Result, Info); 13689 } 13690 } 13691 13692 // For any other type, in-place evaluation is unimportant. 13693 return Evaluate(Result, Info, E); 13694 } 13695 13696 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 13697 /// lvalue-to-rvalue cast if it is an lvalue. 13698 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 13699 if (Info.EnableNewConstInterp) { 13700 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 13701 return false; 13702 } else { 13703 if (E->getType().isNull()) 13704 return false; 13705 13706 if (!CheckLiteralType(Info, E)) 13707 return false; 13708 13709 if (!::Evaluate(Result, Info, E)) 13710 return false; 13711 13712 if (E->isGLValue()) { 13713 LValue LV; 13714 LV.setFrom(Info.Ctx, Result); 13715 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13716 return false; 13717 } 13718 } 13719 13720 // Check this core constant expression is a constant expression. 13721 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 13722 CheckMemoryLeaks(Info); 13723 } 13724 13725 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 13726 const ASTContext &Ctx, bool &IsConst) { 13727 // Fast-path evaluations of integer literals, since we sometimes see files 13728 // containing vast quantities of these. 13729 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 13730 Result.Val = APValue(APSInt(L->getValue(), 13731 L->getType()->isUnsignedIntegerType())); 13732 IsConst = true; 13733 return true; 13734 } 13735 13736 // This case should be rare, but we need to check it before we check on 13737 // the type below. 13738 if (Exp->getType().isNull()) { 13739 IsConst = false; 13740 return true; 13741 } 13742 13743 // FIXME: Evaluating values of large array and record types can cause 13744 // performance problems. Only do so in C++11 for now. 13745 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 13746 Exp->getType()->isRecordType()) && 13747 !Ctx.getLangOpts().CPlusPlus11) { 13748 IsConst = false; 13749 return true; 13750 } 13751 return false; 13752 } 13753 13754 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 13755 Expr::SideEffectsKind SEK) { 13756 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 13757 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 13758 } 13759 13760 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 13761 const ASTContext &Ctx, EvalInfo &Info) { 13762 bool IsConst; 13763 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 13764 return IsConst; 13765 13766 return EvaluateAsRValue(Info, E, Result.Val); 13767 } 13768 13769 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 13770 const ASTContext &Ctx, 13771 Expr::SideEffectsKind AllowSideEffects, 13772 EvalInfo &Info) { 13773 if (!E->getType()->isIntegralOrEnumerationType()) 13774 return false; 13775 13776 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 13777 !ExprResult.Val.isInt() || 13778 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13779 return false; 13780 13781 return true; 13782 } 13783 13784 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 13785 const ASTContext &Ctx, 13786 Expr::SideEffectsKind AllowSideEffects, 13787 EvalInfo &Info) { 13788 if (!E->getType()->isFixedPointType()) 13789 return false; 13790 13791 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 13792 return false; 13793 13794 if (!ExprResult.Val.isFixedPoint() || 13795 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13796 return false; 13797 13798 return true; 13799 } 13800 13801 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 13802 /// any crazy technique (that has nothing to do with language standards) that 13803 /// we want to. If this function returns true, it returns the folded constant 13804 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 13805 /// will be applied to the result. 13806 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 13807 bool InConstantContext) const { 13808 assert(!isValueDependent() && 13809 "Expression evaluator can't be called on a dependent expression."); 13810 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13811 Info.InConstantContext = InConstantContext; 13812 return ::EvaluateAsRValue(this, Result, Ctx, Info); 13813 } 13814 13815 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 13816 bool InConstantContext) const { 13817 assert(!isValueDependent() && 13818 "Expression evaluator can't be called on a dependent expression."); 13819 EvalResult Scratch; 13820 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 13821 HandleConversionToBool(Scratch.Val, Result); 13822 } 13823 13824 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 13825 SideEffectsKind AllowSideEffects, 13826 bool InConstantContext) const { 13827 assert(!isValueDependent() && 13828 "Expression evaluator can't be called on a dependent expression."); 13829 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13830 Info.InConstantContext = InConstantContext; 13831 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 13832 } 13833 13834 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 13835 SideEffectsKind AllowSideEffects, 13836 bool InConstantContext) const { 13837 assert(!isValueDependent() && 13838 "Expression evaluator can't be called on a dependent expression."); 13839 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13840 Info.InConstantContext = InConstantContext; 13841 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 13842 } 13843 13844 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 13845 SideEffectsKind AllowSideEffects, 13846 bool InConstantContext) const { 13847 assert(!isValueDependent() && 13848 "Expression evaluator can't be called on a dependent expression."); 13849 13850 if (!getType()->isRealFloatingType()) 13851 return false; 13852 13853 EvalResult ExprResult; 13854 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 13855 !ExprResult.Val.isFloat() || 13856 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13857 return false; 13858 13859 Result = ExprResult.Val.getFloat(); 13860 return true; 13861 } 13862 13863 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 13864 bool InConstantContext) const { 13865 assert(!isValueDependent() && 13866 "Expression evaluator can't be called on a dependent expression."); 13867 13868 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 13869 Info.InConstantContext = InConstantContext; 13870 LValue LV; 13871 CheckedTemporaries CheckedTemps; 13872 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 13873 Result.HasSideEffects || 13874 !CheckLValueConstantExpression(Info, getExprLoc(), 13875 Ctx.getLValueReferenceType(getType()), LV, 13876 Expr::EvaluateForCodeGen, CheckedTemps)) 13877 return false; 13878 13879 LV.moveInto(Result.Val); 13880 return true; 13881 } 13882 13883 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 13884 const ASTContext &Ctx, bool InPlace) const { 13885 assert(!isValueDependent() && 13886 "Expression evaluator can't be called on a dependent expression."); 13887 13888 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 13889 EvalInfo Info(Ctx, Result, EM); 13890 Info.InConstantContext = true; 13891 13892 if (InPlace) { 13893 Info.setEvaluatingDecl(this, Result.Val); 13894 LValue LVal; 13895 LVal.set(this); 13896 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 13897 Result.HasSideEffects) 13898 return false; 13899 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 13900 return false; 13901 13902 if (!Info.discardCleanups()) 13903 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13904 13905 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 13906 Result.Val, Usage) && 13907 CheckMemoryLeaks(Info); 13908 } 13909 13910 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 13911 const VarDecl *VD, 13912 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 13913 assert(!isValueDependent() && 13914 "Expression evaluator can't be called on a dependent expression."); 13915 13916 // FIXME: Evaluating initializers for large array and record types can cause 13917 // performance problems. Only do so in C++11 for now. 13918 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 13919 !Ctx.getLangOpts().CPlusPlus11) 13920 return false; 13921 13922 Expr::EvalStatus EStatus; 13923 EStatus.Diag = &Notes; 13924 13925 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 13926 ? EvalInfo::EM_ConstantExpression 13927 : EvalInfo::EM_ConstantFold); 13928 Info.setEvaluatingDecl(VD, Value); 13929 Info.InConstantContext = true; 13930 13931 SourceLocation DeclLoc = VD->getLocation(); 13932 QualType DeclTy = VD->getType(); 13933 13934 if (Info.EnableNewConstInterp) { 13935 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 13936 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 13937 return false; 13938 } else { 13939 LValue LVal; 13940 LVal.set(VD); 13941 13942 if (!EvaluateInPlace(Value, Info, LVal, this, 13943 /*AllowNonLiteralTypes=*/true) || 13944 EStatus.HasSideEffects) 13945 return false; 13946 13947 // At this point, any lifetime-extended temporaries are completely 13948 // initialized. 13949 Info.performLifetimeExtension(); 13950 13951 if (!Info.discardCleanups()) 13952 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13953 } 13954 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 13955 CheckMemoryLeaks(Info); 13956 } 13957 13958 bool VarDecl::evaluateDestruction( 13959 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 13960 Expr::EvalStatus EStatus; 13961 EStatus.Diag = &Notes; 13962 13963 // Make a copy of the value for the destructor to mutate, if we know it. 13964 // Otherwise, treat the value as default-initialized; if the destructor works 13965 // anyway, then the destruction is constant (and must be essentially empty). 13966 APValue DestroyedValue = 13967 (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 13968 ? *getEvaluatedValue() 13969 : getDefaultInitValue(getType()); 13970 13971 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 13972 Info.setEvaluatingDecl(this, DestroyedValue, 13973 EvalInfo::EvaluatingDeclKind::Dtor); 13974 Info.InConstantContext = true; 13975 13976 SourceLocation DeclLoc = getLocation(); 13977 QualType DeclTy = getType(); 13978 13979 LValue LVal; 13980 LVal.set(this); 13981 13982 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 13983 EStatus.HasSideEffects) 13984 return false; 13985 13986 if (!Info.discardCleanups()) 13987 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13988 13989 ensureEvaluatedStmt()->HasConstantDestruction = true; 13990 return true; 13991 } 13992 13993 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 13994 /// constant folded, but discard the result. 13995 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 13996 assert(!isValueDependent() && 13997 "Expression evaluator can't be called on a dependent expression."); 13998 13999 EvalResult Result; 14000 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14001 !hasUnacceptableSideEffect(Result, SEK); 14002 } 14003 14004 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14005 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14006 assert(!isValueDependent() && 14007 "Expression evaluator can't be called on a dependent expression."); 14008 14009 EvalResult EVResult; 14010 EVResult.Diag = Diag; 14011 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14012 Info.InConstantContext = true; 14013 14014 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14015 (void)Result; 14016 assert(Result && "Could not evaluate expression"); 14017 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14018 14019 return EVResult.Val.getInt(); 14020 } 14021 14022 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14023 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14024 assert(!isValueDependent() && 14025 "Expression evaluator can't be called on a dependent expression."); 14026 14027 EvalResult EVResult; 14028 EVResult.Diag = Diag; 14029 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14030 Info.InConstantContext = true; 14031 Info.CheckingForUndefinedBehavior = true; 14032 14033 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14034 (void)Result; 14035 assert(Result && "Could not evaluate expression"); 14036 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14037 14038 return EVResult.Val.getInt(); 14039 } 14040 14041 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14042 assert(!isValueDependent() && 14043 "Expression evaluator can't be called on a dependent expression."); 14044 14045 bool IsConst; 14046 EvalResult EVResult; 14047 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14048 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14049 Info.CheckingForUndefinedBehavior = true; 14050 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14051 } 14052 } 14053 14054 bool Expr::EvalResult::isGlobalLValue() const { 14055 assert(Val.isLValue()); 14056 return IsGlobalLValue(Val.getLValueBase()); 14057 } 14058 14059 14060 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14061 /// an integer constant expression. 14062 14063 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14064 /// comma, etc 14065 14066 // CheckICE - This function does the fundamental ICE checking: the returned 14067 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14068 // and a (possibly null) SourceLocation indicating the location of the problem. 14069 // 14070 // Note that to reduce code duplication, this helper does no evaluation 14071 // itself; the caller checks whether the expression is evaluatable, and 14072 // in the rare cases where CheckICE actually cares about the evaluated 14073 // value, it calls into Evaluate. 14074 14075 namespace { 14076 14077 enum ICEKind { 14078 /// This expression is an ICE. 14079 IK_ICE, 14080 /// This expression is not an ICE, but if it isn't evaluated, it's 14081 /// a legal subexpression for an ICE. This return value is used to handle 14082 /// the comma operator in C99 mode, and non-constant subexpressions. 14083 IK_ICEIfUnevaluated, 14084 /// This expression is not an ICE, and is not a legal subexpression for one. 14085 IK_NotICE 14086 }; 14087 14088 struct ICEDiag { 14089 ICEKind Kind; 14090 SourceLocation Loc; 14091 14092 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14093 }; 14094 14095 } 14096 14097 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14098 14099 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14100 14101 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14102 Expr::EvalResult EVResult; 14103 Expr::EvalStatus Status; 14104 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14105 14106 Info.InConstantContext = true; 14107 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14108 !EVResult.Val.isInt()) 14109 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14110 14111 return NoDiag(); 14112 } 14113 14114 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14115 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14116 if (!E->getType()->isIntegralOrEnumerationType()) 14117 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14118 14119 switch (E->getStmtClass()) { 14120 #define ABSTRACT_STMT(Node) 14121 #define STMT(Node, Base) case Expr::Node##Class: 14122 #define EXPR(Node, Base) 14123 #include "clang/AST/StmtNodes.inc" 14124 case Expr::PredefinedExprClass: 14125 case Expr::FloatingLiteralClass: 14126 case Expr::ImaginaryLiteralClass: 14127 case Expr::StringLiteralClass: 14128 case Expr::ArraySubscriptExprClass: 14129 case Expr::OMPArraySectionExprClass: 14130 case Expr::MemberExprClass: 14131 case Expr::CompoundAssignOperatorClass: 14132 case Expr::CompoundLiteralExprClass: 14133 case Expr::ExtVectorElementExprClass: 14134 case Expr::DesignatedInitExprClass: 14135 case Expr::ArrayInitLoopExprClass: 14136 case Expr::ArrayInitIndexExprClass: 14137 case Expr::NoInitExprClass: 14138 case Expr::DesignatedInitUpdateExprClass: 14139 case Expr::ImplicitValueInitExprClass: 14140 case Expr::ParenListExprClass: 14141 case Expr::VAArgExprClass: 14142 case Expr::AddrLabelExprClass: 14143 case Expr::StmtExprClass: 14144 case Expr::CXXMemberCallExprClass: 14145 case Expr::CUDAKernelCallExprClass: 14146 case Expr::CXXDynamicCastExprClass: 14147 case Expr::CXXTypeidExprClass: 14148 case Expr::CXXUuidofExprClass: 14149 case Expr::MSPropertyRefExprClass: 14150 case Expr::MSPropertySubscriptExprClass: 14151 case Expr::CXXNullPtrLiteralExprClass: 14152 case Expr::UserDefinedLiteralClass: 14153 case Expr::CXXThisExprClass: 14154 case Expr::CXXThrowExprClass: 14155 case Expr::CXXNewExprClass: 14156 case Expr::CXXDeleteExprClass: 14157 case Expr::CXXPseudoDestructorExprClass: 14158 case Expr::UnresolvedLookupExprClass: 14159 case Expr::TypoExprClass: 14160 case Expr::DependentScopeDeclRefExprClass: 14161 case Expr::CXXConstructExprClass: 14162 case Expr::CXXInheritedCtorInitExprClass: 14163 case Expr::CXXStdInitializerListExprClass: 14164 case Expr::CXXBindTemporaryExprClass: 14165 case Expr::ExprWithCleanupsClass: 14166 case Expr::CXXTemporaryObjectExprClass: 14167 case Expr::CXXUnresolvedConstructExprClass: 14168 case Expr::CXXDependentScopeMemberExprClass: 14169 case Expr::UnresolvedMemberExprClass: 14170 case Expr::ObjCStringLiteralClass: 14171 case Expr::ObjCBoxedExprClass: 14172 case Expr::ObjCArrayLiteralClass: 14173 case Expr::ObjCDictionaryLiteralClass: 14174 case Expr::ObjCEncodeExprClass: 14175 case Expr::ObjCMessageExprClass: 14176 case Expr::ObjCSelectorExprClass: 14177 case Expr::ObjCProtocolExprClass: 14178 case Expr::ObjCIvarRefExprClass: 14179 case Expr::ObjCPropertyRefExprClass: 14180 case Expr::ObjCSubscriptRefExprClass: 14181 case Expr::ObjCIsaExprClass: 14182 case Expr::ObjCAvailabilityCheckExprClass: 14183 case Expr::ShuffleVectorExprClass: 14184 case Expr::ConvertVectorExprClass: 14185 case Expr::BlockExprClass: 14186 case Expr::NoStmtClass: 14187 case Expr::OpaqueValueExprClass: 14188 case Expr::PackExpansionExprClass: 14189 case Expr::SubstNonTypeTemplateParmPackExprClass: 14190 case Expr::FunctionParmPackExprClass: 14191 case Expr::AsTypeExprClass: 14192 case Expr::ObjCIndirectCopyRestoreExprClass: 14193 case Expr::MaterializeTemporaryExprClass: 14194 case Expr::PseudoObjectExprClass: 14195 case Expr::AtomicExprClass: 14196 case Expr::LambdaExprClass: 14197 case Expr::CXXFoldExprClass: 14198 case Expr::CoawaitExprClass: 14199 case Expr::DependentCoawaitExprClass: 14200 case Expr::CoyieldExprClass: 14201 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14202 14203 case Expr::InitListExprClass: { 14204 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14205 // form "T x = { a };" is equivalent to "T x = a;". 14206 // Unless we're initializing a reference, T is a scalar as it is known to be 14207 // of integral or enumeration type. 14208 if (E->isRValue()) 14209 if (cast<InitListExpr>(E)->getNumInits() == 1) 14210 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14211 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14212 } 14213 14214 case Expr::SizeOfPackExprClass: 14215 case Expr::GNUNullExprClass: 14216 case Expr::SourceLocExprClass: 14217 return NoDiag(); 14218 14219 case Expr::SubstNonTypeTemplateParmExprClass: 14220 return 14221 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14222 14223 case Expr::ConstantExprClass: 14224 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14225 14226 case Expr::ParenExprClass: 14227 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14228 case Expr::GenericSelectionExprClass: 14229 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14230 case Expr::IntegerLiteralClass: 14231 case Expr::FixedPointLiteralClass: 14232 case Expr::CharacterLiteralClass: 14233 case Expr::ObjCBoolLiteralExprClass: 14234 case Expr::CXXBoolLiteralExprClass: 14235 case Expr::CXXScalarValueInitExprClass: 14236 case Expr::TypeTraitExprClass: 14237 case Expr::ConceptSpecializationExprClass: 14238 case Expr::RequiresExprClass: 14239 case Expr::ArrayTypeTraitExprClass: 14240 case Expr::ExpressionTraitExprClass: 14241 case Expr::CXXNoexceptExprClass: 14242 return NoDiag(); 14243 case Expr::CallExprClass: 14244 case Expr::CXXOperatorCallExprClass: { 14245 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14246 // constant expressions, but they can never be ICEs because an ICE cannot 14247 // contain an operand of (pointer to) function type. 14248 const CallExpr *CE = cast<CallExpr>(E); 14249 if (CE->getBuiltinCallee()) 14250 return CheckEvalInICE(E, Ctx); 14251 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14252 } 14253 case Expr::CXXRewrittenBinaryOperatorClass: 14254 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14255 Ctx); 14256 case Expr::DeclRefExprClass: { 14257 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14258 return NoDiag(); 14259 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14260 if (Ctx.getLangOpts().CPlusPlus && 14261 D && IsConstNonVolatile(D->getType())) { 14262 // Parameter variables are never constants. Without this check, 14263 // getAnyInitializer() can find a default argument, which leads 14264 // to chaos. 14265 if (isa<ParmVarDecl>(D)) 14266 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14267 14268 // C++ 7.1.5.1p2 14269 // A variable of non-volatile const-qualified integral or enumeration 14270 // type initialized by an ICE can be used in ICEs. 14271 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14272 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14273 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14274 14275 const VarDecl *VD; 14276 // Look for a declaration of this variable that has an initializer, and 14277 // check whether it is an ICE. 14278 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 14279 return NoDiag(); 14280 else 14281 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14282 } 14283 } 14284 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14285 } 14286 case Expr::UnaryOperatorClass: { 14287 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14288 switch (Exp->getOpcode()) { 14289 case UO_PostInc: 14290 case UO_PostDec: 14291 case UO_PreInc: 14292 case UO_PreDec: 14293 case UO_AddrOf: 14294 case UO_Deref: 14295 case UO_Coawait: 14296 // C99 6.6/3 allows increment and decrement within unevaluated 14297 // subexpressions of constant expressions, but they can never be ICEs 14298 // because an ICE cannot contain an lvalue operand. 14299 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14300 case UO_Extension: 14301 case UO_LNot: 14302 case UO_Plus: 14303 case UO_Minus: 14304 case UO_Not: 14305 case UO_Real: 14306 case UO_Imag: 14307 return CheckICE(Exp->getSubExpr(), Ctx); 14308 } 14309 llvm_unreachable("invalid unary operator class"); 14310 } 14311 case Expr::OffsetOfExprClass: { 14312 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14313 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14314 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14315 // compliance: we should warn earlier for offsetof expressions with 14316 // array subscripts that aren't ICEs, and if the array subscripts 14317 // are ICEs, the value of the offsetof must be an integer constant. 14318 return CheckEvalInICE(E, Ctx); 14319 } 14320 case Expr::UnaryExprOrTypeTraitExprClass: { 14321 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14322 if ((Exp->getKind() == UETT_SizeOf) && 14323 Exp->getTypeOfArgument()->isVariableArrayType()) 14324 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14325 return NoDiag(); 14326 } 14327 case Expr::BinaryOperatorClass: { 14328 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14329 switch (Exp->getOpcode()) { 14330 case BO_PtrMemD: 14331 case BO_PtrMemI: 14332 case BO_Assign: 14333 case BO_MulAssign: 14334 case BO_DivAssign: 14335 case BO_RemAssign: 14336 case BO_AddAssign: 14337 case BO_SubAssign: 14338 case BO_ShlAssign: 14339 case BO_ShrAssign: 14340 case BO_AndAssign: 14341 case BO_XorAssign: 14342 case BO_OrAssign: 14343 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14344 // constant expressions, but they can never be ICEs because an ICE cannot 14345 // contain an lvalue operand. 14346 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14347 14348 case BO_Mul: 14349 case BO_Div: 14350 case BO_Rem: 14351 case BO_Add: 14352 case BO_Sub: 14353 case BO_Shl: 14354 case BO_Shr: 14355 case BO_LT: 14356 case BO_GT: 14357 case BO_LE: 14358 case BO_GE: 14359 case BO_EQ: 14360 case BO_NE: 14361 case BO_And: 14362 case BO_Xor: 14363 case BO_Or: 14364 case BO_Comma: 14365 case BO_Cmp: { 14366 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14367 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14368 if (Exp->getOpcode() == BO_Div || 14369 Exp->getOpcode() == BO_Rem) { 14370 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14371 // we don't evaluate one. 14372 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14373 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14374 if (REval == 0) 14375 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14376 if (REval.isSigned() && REval.isAllOnesValue()) { 14377 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14378 if (LEval.isMinSignedValue()) 14379 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14380 } 14381 } 14382 } 14383 if (Exp->getOpcode() == BO_Comma) { 14384 if (Ctx.getLangOpts().C99) { 14385 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14386 // if it isn't evaluated. 14387 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14388 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14389 } else { 14390 // In both C89 and C++, commas in ICEs are illegal. 14391 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14392 } 14393 } 14394 return Worst(LHSResult, RHSResult); 14395 } 14396 case BO_LAnd: 14397 case BO_LOr: { 14398 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14399 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14400 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14401 // Rare case where the RHS has a comma "side-effect"; we need 14402 // to actually check the condition to see whether the side 14403 // with the comma is evaluated. 14404 if ((Exp->getOpcode() == BO_LAnd) != 14405 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14406 return RHSResult; 14407 return NoDiag(); 14408 } 14409 14410 return Worst(LHSResult, RHSResult); 14411 } 14412 } 14413 llvm_unreachable("invalid binary operator kind"); 14414 } 14415 case Expr::ImplicitCastExprClass: 14416 case Expr::CStyleCastExprClass: 14417 case Expr::CXXFunctionalCastExprClass: 14418 case Expr::CXXStaticCastExprClass: 14419 case Expr::CXXReinterpretCastExprClass: 14420 case Expr::CXXConstCastExprClass: 14421 case Expr::ObjCBridgedCastExprClass: { 14422 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14423 if (isa<ExplicitCastExpr>(E)) { 14424 if (const FloatingLiteral *FL 14425 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14426 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14427 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14428 APSInt IgnoredVal(DestWidth, !DestSigned); 14429 bool Ignored; 14430 // If the value does not fit in the destination type, the behavior is 14431 // undefined, so we are not required to treat it as a constant 14432 // expression. 14433 if (FL->getValue().convertToInteger(IgnoredVal, 14434 llvm::APFloat::rmTowardZero, 14435 &Ignored) & APFloat::opInvalidOp) 14436 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14437 return NoDiag(); 14438 } 14439 } 14440 switch (cast<CastExpr>(E)->getCastKind()) { 14441 case CK_LValueToRValue: 14442 case CK_AtomicToNonAtomic: 14443 case CK_NonAtomicToAtomic: 14444 case CK_NoOp: 14445 case CK_IntegralToBoolean: 14446 case CK_IntegralCast: 14447 return CheckICE(SubExpr, Ctx); 14448 default: 14449 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14450 } 14451 } 14452 case Expr::BinaryConditionalOperatorClass: { 14453 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 14454 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 14455 if (CommonResult.Kind == IK_NotICE) return CommonResult; 14456 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14457 if (FalseResult.Kind == IK_NotICE) return FalseResult; 14458 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 14459 if (FalseResult.Kind == IK_ICEIfUnevaluated && 14460 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 14461 return FalseResult; 14462 } 14463 case Expr::ConditionalOperatorClass: { 14464 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 14465 // If the condition (ignoring parens) is a __builtin_constant_p call, 14466 // then only the true side is actually considered in an integer constant 14467 // expression, and it is fully evaluated. This is an important GNU 14468 // extension. See GCC PR38377 for discussion. 14469 if (const CallExpr *CallCE 14470 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 14471 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 14472 return CheckEvalInICE(E, Ctx); 14473 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 14474 if (CondResult.Kind == IK_NotICE) 14475 return CondResult; 14476 14477 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 14478 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14479 14480 if (TrueResult.Kind == IK_NotICE) 14481 return TrueResult; 14482 if (FalseResult.Kind == IK_NotICE) 14483 return FalseResult; 14484 if (CondResult.Kind == IK_ICEIfUnevaluated) 14485 return CondResult; 14486 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 14487 return NoDiag(); 14488 // Rare case where the diagnostics depend on which side is evaluated 14489 // Note that if we get here, CondResult is 0, and at least one of 14490 // TrueResult and FalseResult is non-zero. 14491 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 14492 return FalseResult; 14493 return TrueResult; 14494 } 14495 case Expr::CXXDefaultArgExprClass: 14496 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 14497 case Expr::CXXDefaultInitExprClass: 14498 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 14499 case Expr::ChooseExprClass: { 14500 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 14501 } 14502 case Expr::BuiltinBitCastExprClass: { 14503 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 14504 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14505 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 14506 } 14507 } 14508 14509 llvm_unreachable("Invalid StmtClass!"); 14510 } 14511 14512 /// Evaluate an expression as a C++11 integral constant expression. 14513 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 14514 const Expr *E, 14515 llvm::APSInt *Value, 14516 SourceLocation *Loc) { 14517 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14518 if (Loc) *Loc = E->getExprLoc(); 14519 return false; 14520 } 14521 14522 APValue Result; 14523 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 14524 return false; 14525 14526 if (!Result.isInt()) { 14527 if (Loc) *Loc = E->getExprLoc(); 14528 return false; 14529 } 14530 14531 if (Value) *Value = Result.getInt(); 14532 return true; 14533 } 14534 14535 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 14536 SourceLocation *Loc) const { 14537 assert(!isValueDependent() && 14538 "Expression evaluator can't be called on a dependent expression."); 14539 14540 if (Ctx.getLangOpts().CPlusPlus11) 14541 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 14542 14543 ICEDiag D = CheckICE(this, Ctx); 14544 if (D.Kind != IK_ICE) { 14545 if (Loc) *Loc = D.Loc; 14546 return false; 14547 } 14548 return true; 14549 } 14550 14551 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 14552 SourceLocation *Loc, bool isEvaluated) const { 14553 assert(!isValueDependent() && 14554 "Expression evaluator can't be called on a dependent expression."); 14555 14556 if (Ctx.getLangOpts().CPlusPlus11) 14557 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 14558 14559 if (!isIntegerConstantExpr(Ctx, Loc)) 14560 return false; 14561 14562 // The only possible side-effects here are due to UB discovered in the 14563 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 14564 // required to treat the expression as an ICE, so we produce the folded 14565 // value. 14566 EvalResult ExprResult; 14567 Expr::EvalStatus Status; 14568 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 14569 Info.InConstantContext = true; 14570 14571 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 14572 llvm_unreachable("ICE cannot be evaluated!"); 14573 14574 Value = ExprResult.Val.getInt(); 14575 return true; 14576 } 14577 14578 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 14579 assert(!isValueDependent() && 14580 "Expression evaluator can't be called on a dependent expression."); 14581 14582 return CheckICE(this, Ctx).Kind == IK_ICE; 14583 } 14584 14585 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 14586 SourceLocation *Loc) const { 14587 assert(!isValueDependent() && 14588 "Expression evaluator can't be called on a dependent expression."); 14589 14590 // We support this checking in C++98 mode in order to diagnose compatibility 14591 // issues. 14592 assert(Ctx.getLangOpts().CPlusPlus); 14593 14594 // Build evaluation settings. 14595 Expr::EvalStatus Status; 14596 SmallVector<PartialDiagnosticAt, 8> Diags; 14597 Status.Diag = &Diags; 14598 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14599 14600 APValue Scratch; 14601 bool IsConstExpr = 14602 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 14603 // FIXME: We don't produce a diagnostic for this, but the callers that 14604 // call us on arbitrary full-expressions should generally not care. 14605 Info.discardCleanups() && !Status.HasSideEffects; 14606 14607 if (!Diags.empty()) { 14608 IsConstExpr = false; 14609 if (Loc) *Loc = Diags[0].first; 14610 } else if (!IsConstExpr) { 14611 // FIXME: This shouldn't happen. 14612 if (Loc) *Loc = getExprLoc(); 14613 } 14614 14615 return IsConstExpr; 14616 } 14617 14618 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 14619 const FunctionDecl *Callee, 14620 ArrayRef<const Expr*> Args, 14621 const Expr *This) const { 14622 assert(!isValueDependent() && 14623 "Expression evaluator can't be called on a dependent expression."); 14624 14625 Expr::EvalStatus Status; 14626 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 14627 Info.InConstantContext = true; 14628 14629 LValue ThisVal; 14630 const LValue *ThisPtr = nullptr; 14631 if (This) { 14632 #ifndef NDEBUG 14633 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 14634 assert(MD && "Don't provide `this` for non-methods."); 14635 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 14636 #endif 14637 if (!This->isValueDependent() && 14638 EvaluateObjectArgument(Info, This, ThisVal) && 14639 !Info.EvalStatus.HasSideEffects) 14640 ThisPtr = &ThisVal; 14641 14642 // Ignore any side-effects from a failed evaluation. This is safe because 14643 // they can't interfere with any other argument evaluation. 14644 Info.EvalStatus.HasSideEffects = false; 14645 } 14646 14647 ArgVector ArgValues(Args.size()); 14648 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 14649 I != E; ++I) { 14650 if ((*I)->isValueDependent() || 14651 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 14652 Info.EvalStatus.HasSideEffects) 14653 // If evaluation fails, throw away the argument entirely. 14654 ArgValues[I - Args.begin()] = APValue(); 14655 14656 // Ignore any side-effects from a failed evaluation. This is safe because 14657 // they can't interfere with any other argument evaluation. 14658 Info.EvalStatus.HasSideEffects = false; 14659 } 14660 14661 // Parameter cleanups happen in the caller and are not part of this 14662 // evaluation. 14663 Info.discardCleanups(); 14664 Info.EvalStatus.HasSideEffects = false; 14665 14666 // Build fake call to Callee. 14667 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 14668 ArgValues.data()); 14669 // FIXME: Missing ExprWithCleanups in enable_if conditions? 14670 FullExpressionRAII Scope(Info); 14671 return Evaluate(Value, Info, this) && Scope.destroy() && 14672 !Info.EvalStatus.HasSideEffects; 14673 } 14674 14675 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 14676 SmallVectorImpl< 14677 PartialDiagnosticAt> &Diags) { 14678 // FIXME: It would be useful to check constexpr function templates, but at the 14679 // moment the constant expression evaluator cannot cope with the non-rigorous 14680 // ASTs which we build for dependent expressions. 14681 if (FD->isDependentContext()) 14682 return true; 14683 14684 Expr::EvalStatus Status; 14685 Status.Diag = &Diags; 14686 14687 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 14688 Info.InConstantContext = true; 14689 Info.CheckingPotentialConstantExpression = true; 14690 14691 // The constexpr VM attempts to compile all methods to bytecode here. 14692 if (Info.EnableNewConstInterp) { 14693 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 14694 return Diags.empty(); 14695 } 14696 14697 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 14698 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 14699 14700 // Fabricate an arbitrary expression on the stack and pretend that it 14701 // is a temporary being used as the 'this' pointer. 14702 LValue This; 14703 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 14704 This.set({&VIE, Info.CurrentCall->Index}); 14705 14706 ArrayRef<const Expr*> Args; 14707 14708 APValue Scratch; 14709 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 14710 // Evaluate the call as a constant initializer, to allow the construction 14711 // of objects of non-literal types. 14712 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 14713 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 14714 } else { 14715 SourceLocation Loc = FD->getLocation(); 14716 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 14717 Args, FD->getBody(), Info, Scratch, nullptr); 14718 } 14719 14720 return Diags.empty(); 14721 } 14722 14723 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 14724 const FunctionDecl *FD, 14725 SmallVectorImpl< 14726 PartialDiagnosticAt> &Diags) { 14727 assert(!E->isValueDependent() && 14728 "Expression evaluator can't be called on a dependent expression."); 14729 14730 Expr::EvalStatus Status; 14731 Status.Diag = &Diags; 14732 14733 EvalInfo Info(FD->getASTContext(), Status, 14734 EvalInfo::EM_ConstantExpressionUnevaluated); 14735 Info.InConstantContext = true; 14736 Info.CheckingPotentialConstantExpression = true; 14737 14738 // Fabricate a call stack frame to give the arguments a plausible cover story. 14739 ArrayRef<const Expr*> Args; 14740 ArgVector ArgValues(0); 14741 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 14742 (void)Success; 14743 assert(Success && 14744 "Failed to set up arguments for potential constant evaluation"); 14745 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 14746 14747 APValue ResultScratch; 14748 Evaluate(ResultScratch, Info, E); 14749 return Diags.empty(); 14750 } 14751 14752 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 14753 unsigned Type) const { 14754 if (!getType()->isPointerType()) 14755 return false; 14756 14757 Expr::EvalStatus Status; 14758 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 14759 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 14760 } 14761