1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 if (!B) return QualType(); 83 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 84 // FIXME: It's unclear where we're supposed to take the type from, and 85 // this actually matters for arrays of unknown bound. Eg: 86 // 87 // extern int arr[]; void f() { extern int arr[3]; }; 88 // constexpr int *p = &arr[1]; // valid? 89 // 90 // For now, we take the array bound from the most recent declaration. 91 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 92 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 93 QualType T = Redecl->getType(); 94 if (!T->isIncompleteArrayType()) 95 return T; 96 } 97 return D->getType(); 98 } 99 100 if (B.is<TypeInfoLValue>()) 101 return B.getTypeInfoType(); 102 103 if (B.is<DynamicAllocLValue>()) 104 return B.getDynamicAllocType(); 105 106 const Expr *Base = B.get<const Expr*>(); 107 108 // For a materialized temporary, the type of the temporary we materialized 109 // may not be the type of the expression. 110 if (const MaterializeTemporaryExpr *MTE = 111 dyn_cast<MaterializeTemporaryExpr>(Base)) { 112 SmallVector<const Expr *, 2> CommaLHSs; 113 SmallVector<SubobjectAdjustment, 2> Adjustments; 114 const Expr *Temp = MTE->getSubExpr(); 115 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 116 Adjustments); 117 // Keep any cv-qualifiers from the reference if we generated a temporary 118 // for it directly. Otherwise use the type after adjustment. 119 if (!Adjustments.empty()) 120 return Inner->getType(); 121 } 122 123 return Base->getType(); 124 } 125 126 /// Get an LValue path entry, which is known to not be an array index, as a 127 /// field declaration. 128 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 129 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 130 } 131 /// Get an LValue path entry, which is known to not be an array index, as a 132 /// base class declaration. 133 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 134 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 135 } 136 /// Determine whether this LValue path entry for a base class names a virtual 137 /// base class. 138 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 139 return E.getAsBaseOrMember().getInt(); 140 } 141 142 /// Given an expression, determine the type used to store the result of 143 /// evaluating that expression. 144 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 145 if (E->isRValue()) 146 return E->getType(); 147 return Ctx.getLValueReferenceType(E->getType()); 148 } 149 150 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 151 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 152 const FunctionDecl *Callee = CE->getDirectCallee(); 153 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 154 } 155 156 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 157 /// This will look through a single cast. 158 /// 159 /// Returns null if we couldn't unwrap a function with alloc_size. 160 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 161 if (!E->getType()->isPointerType()) 162 return nullptr; 163 164 E = E->IgnoreParens(); 165 // If we're doing a variable assignment from e.g. malloc(N), there will 166 // probably be a cast of some kind. In exotic cases, we might also see a 167 // top-level ExprWithCleanups. Ignore them either way. 168 if (const auto *FE = dyn_cast<FullExpr>(E)) 169 E = FE->getSubExpr()->IgnoreParens(); 170 171 if (const auto *Cast = dyn_cast<CastExpr>(E)) 172 E = Cast->getSubExpr()->IgnoreParens(); 173 174 if (const auto *CE = dyn_cast<CallExpr>(E)) 175 return getAllocSizeAttr(CE) ? CE : nullptr; 176 return nullptr; 177 } 178 179 /// Determines whether or not the given Base contains a call to a function 180 /// with the alloc_size attribute. 181 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 182 const auto *E = Base.dyn_cast<const Expr *>(); 183 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 184 } 185 186 /// The bound to claim that an array of unknown bound has. 187 /// The value in MostDerivedArraySize is undefined in this case. So, set it 188 /// to an arbitrary value that's likely to loudly break things if it's used. 189 static const uint64_t AssumedSizeForUnsizedArray = 190 std::numeric_limits<uint64_t>::max() / 2; 191 192 /// Determines if an LValue with the given LValueBase will have an unsized 193 /// array in its designator. 194 /// Find the path length and type of the most-derived subobject in the given 195 /// path, and find the size of the containing array, if any. 196 static unsigned 197 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 198 ArrayRef<APValue::LValuePathEntry> Path, 199 uint64_t &ArraySize, QualType &Type, bool &IsArray, 200 bool &FirstEntryIsUnsizedArray) { 201 // This only accepts LValueBases from APValues, and APValues don't support 202 // arrays that lack size info. 203 assert(!isBaseAnAllocSizeCall(Base) && 204 "Unsized arrays shouldn't appear here"); 205 unsigned MostDerivedLength = 0; 206 Type = getType(Base); 207 208 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 209 if (Type->isArrayType()) { 210 const ArrayType *AT = Ctx.getAsArrayType(Type); 211 Type = AT->getElementType(); 212 MostDerivedLength = I + 1; 213 IsArray = true; 214 215 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 216 ArraySize = CAT->getSize().getZExtValue(); 217 } else { 218 assert(I == 0 && "unexpected unsized array designator"); 219 FirstEntryIsUnsizedArray = true; 220 ArraySize = AssumedSizeForUnsizedArray; 221 } 222 } else if (Type->isAnyComplexType()) { 223 const ComplexType *CT = Type->castAs<ComplexType>(); 224 Type = CT->getElementType(); 225 ArraySize = 2; 226 MostDerivedLength = I + 1; 227 IsArray = true; 228 } else if (const FieldDecl *FD = getAsField(Path[I])) { 229 Type = FD->getType(); 230 ArraySize = 0; 231 MostDerivedLength = I + 1; 232 IsArray = false; 233 } else { 234 // Path[I] describes a base class. 235 ArraySize = 0; 236 IsArray = false; 237 } 238 } 239 return MostDerivedLength; 240 } 241 242 /// A path from a glvalue to a subobject of that glvalue. 243 struct SubobjectDesignator { 244 /// True if the subobject was named in a manner not supported by C++11. Such 245 /// lvalues can still be folded, but they are not core constant expressions 246 /// and we cannot perform lvalue-to-rvalue conversions on them. 247 unsigned Invalid : 1; 248 249 /// Is this a pointer one past the end of an object? 250 unsigned IsOnePastTheEnd : 1; 251 252 /// Indicator of whether the first entry is an unsized array. 253 unsigned FirstEntryIsAnUnsizedArray : 1; 254 255 /// Indicator of whether the most-derived object is an array element. 256 unsigned MostDerivedIsArrayElement : 1; 257 258 /// The length of the path to the most-derived object of which this is a 259 /// subobject. 260 unsigned MostDerivedPathLength : 28; 261 262 /// The size of the array of which the most-derived object is an element. 263 /// This will always be 0 if the most-derived object is not an array 264 /// element. 0 is not an indicator of whether or not the most-derived object 265 /// is an array, however, because 0-length arrays are allowed. 266 /// 267 /// If the current array is an unsized array, the value of this is 268 /// undefined. 269 uint64_t MostDerivedArraySize; 270 271 /// The type of the most derived object referred to by this address. 272 QualType MostDerivedType; 273 274 typedef APValue::LValuePathEntry PathEntry; 275 276 /// The entries on the path from the glvalue to the designated subobject. 277 SmallVector<PathEntry, 8> Entries; 278 279 SubobjectDesignator() : Invalid(true) {} 280 281 explicit SubobjectDesignator(QualType T) 282 : Invalid(false), IsOnePastTheEnd(false), 283 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 284 MostDerivedPathLength(0), MostDerivedArraySize(0), 285 MostDerivedType(T) {} 286 287 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 288 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 289 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 290 MostDerivedPathLength(0), MostDerivedArraySize(0) { 291 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 292 if (!Invalid) { 293 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 294 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 295 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 296 if (V.getLValueBase()) { 297 bool IsArray = false; 298 bool FirstIsUnsizedArray = false; 299 MostDerivedPathLength = findMostDerivedSubobject( 300 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 301 MostDerivedType, IsArray, FirstIsUnsizedArray); 302 MostDerivedIsArrayElement = IsArray; 303 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 304 } 305 } 306 } 307 308 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 309 unsigned NewLength) { 310 if (Invalid) 311 return; 312 313 assert(Base && "cannot truncate path for null pointer"); 314 assert(NewLength <= Entries.size() && "not a truncation"); 315 316 if (NewLength == Entries.size()) 317 return; 318 Entries.resize(NewLength); 319 320 bool IsArray = false; 321 bool FirstIsUnsizedArray = false; 322 MostDerivedPathLength = findMostDerivedSubobject( 323 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 324 FirstIsUnsizedArray); 325 MostDerivedIsArrayElement = IsArray; 326 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 327 } 328 329 void setInvalid() { 330 Invalid = true; 331 Entries.clear(); 332 } 333 334 /// Determine whether the most derived subobject is an array without a 335 /// known bound. 336 bool isMostDerivedAnUnsizedArray() const { 337 assert(!Invalid && "Calling this makes no sense on invalid designators"); 338 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 339 } 340 341 /// Determine what the most derived array's size is. Results in an assertion 342 /// failure if the most derived array lacks a size. 343 uint64_t getMostDerivedArraySize() const { 344 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 345 return MostDerivedArraySize; 346 } 347 348 /// Determine whether this is a one-past-the-end pointer. 349 bool isOnePastTheEnd() const { 350 assert(!Invalid); 351 if (IsOnePastTheEnd) 352 return true; 353 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 354 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 355 MostDerivedArraySize) 356 return true; 357 return false; 358 } 359 360 /// Get the range of valid index adjustments in the form 361 /// {maximum value that can be subtracted from this pointer, 362 /// maximum value that can be added to this pointer} 363 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 364 if (Invalid || isMostDerivedAnUnsizedArray()) 365 return {0, 0}; 366 367 // [expr.add]p4: For the purposes of these operators, a pointer to a 368 // nonarray object behaves the same as a pointer to the first element of 369 // an array of length one with the type of the object as its element type. 370 bool IsArray = MostDerivedPathLength == Entries.size() && 371 MostDerivedIsArrayElement; 372 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 373 : (uint64_t)IsOnePastTheEnd; 374 uint64_t ArraySize = 375 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 376 return {ArrayIndex, ArraySize - ArrayIndex}; 377 } 378 379 /// Check that this refers to a valid subobject. 380 bool isValidSubobject() const { 381 if (Invalid) 382 return false; 383 return !isOnePastTheEnd(); 384 } 385 /// Check that this refers to a valid subobject, and if not, produce a 386 /// relevant diagnostic and set the designator as invalid. 387 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 388 389 /// Get the type of the designated object. 390 QualType getType(ASTContext &Ctx) const { 391 assert(!Invalid && "invalid designator has no subobject type"); 392 return MostDerivedPathLength == Entries.size() 393 ? MostDerivedType 394 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 395 } 396 397 /// Update this designator to refer to the first element within this array. 398 void addArrayUnchecked(const ConstantArrayType *CAT) { 399 Entries.push_back(PathEntry::ArrayIndex(0)); 400 401 // This is a most-derived object. 402 MostDerivedType = CAT->getElementType(); 403 MostDerivedIsArrayElement = true; 404 MostDerivedArraySize = CAT->getSize().getZExtValue(); 405 MostDerivedPathLength = Entries.size(); 406 } 407 /// Update this designator to refer to the first element within the array of 408 /// elements of type T. This is an array of unknown size. 409 void addUnsizedArrayUnchecked(QualType ElemTy) { 410 Entries.push_back(PathEntry::ArrayIndex(0)); 411 412 MostDerivedType = ElemTy; 413 MostDerivedIsArrayElement = true; 414 // The value in MostDerivedArraySize is undefined in this case. So, set it 415 // to an arbitrary value that's likely to loudly break things if it's 416 // used. 417 MostDerivedArraySize = AssumedSizeForUnsizedArray; 418 MostDerivedPathLength = Entries.size(); 419 } 420 /// Update this designator to refer to the given base or member of this 421 /// object. 422 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 423 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 424 425 // If this isn't a base class, it's a new most-derived object. 426 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 427 MostDerivedType = FD->getType(); 428 MostDerivedIsArrayElement = false; 429 MostDerivedArraySize = 0; 430 MostDerivedPathLength = Entries.size(); 431 } 432 } 433 /// Update this designator to refer to the given complex component. 434 void addComplexUnchecked(QualType EltTy, bool Imag) { 435 Entries.push_back(PathEntry::ArrayIndex(Imag)); 436 437 // This is technically a most-derived object, though in practice this 438 // is unlikely to matter. 439 MostDerivedType = EltTy; 440 MostDerivedIsArrayElement = true; 441 MostDerivedArraySize = 2; 442 MostDerivedPathLength = Entries.size(); 443 } 444 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 445 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 446 const APSInt &N); 447 /// Add N to the address of this subobject. 448 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 449 if (Invalid || !N) return; 450 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 451 if (isMostDerivedAnUnsizedArray()) { 452 diagnoseUnsizedArrayPointerArithmetic(Info, E); 453 // Can't verify -- trust that the user is doing the right thing (or if 454 // not, trust that the caller will catch the bad behavior). 455 // FIXME: Should we reject if this overflows, at least? 456 Entries.back() = PathEntry::ArrayIndex( 457 Entries.back().getAsArrayIndex() + TruncatedN); 458 return; 459 } 460 461 // [expr.add]p4: For the purposes of these operators, a pointer to a 462 // nonarray object behaves the same as a pointer to the first element of 463 // an array of length one with the type of the object as its element type. 464 bool IsArray = MostDerivedPathLength == Entries.size() && 465 MostDerivedIsArrayElement; 466 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 467 : (uint64_t)IsOnePastTheEnd; 468 uint64_t ArraySize = 469 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 470 471 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 472 // Calculate the actual index in a wide enough type, so we can include 473 // it in the note. 474 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 475 (llvm::APInt&)N += ArrayIndex; 476 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 477 diagnosePointerArithmetic(Info, E, N); 478 setInvalid(); 479 return; 480 } 481 482 ArrayIndex += TruncatedN; 483 assert(ArrayIndex <= ArraySize && 484 "bounds check succeeded for out-of-bounds index"); 485 486 if (IsArray) 487 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 488 else 489 IsOnePastTheEnd = (ArrayIndex != 0); 490 } 491 }; 492 493 /// A scope at the end of which an object can need to be destroyed. 494 enum class ScopeKind { 495 Block, 496 FullExpression, 497 Call 498 }; 499 500 /// A reference to a particular call and its arguments. 501 struct CallRef { 502 CallRef() : OrigCallee(), CallIndex(0), Version() {} 503 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 504 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 505 506 explicit operator bool() const { return OrigCallee; } 507 508 /// Get the parameter that the caller initialized, corresponding to the 509 /// given parameter in the callee. 510 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 511 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 512 : PVD; 513 } 514 515 /// The callee at the point where the arguments were evaluated. This might 516 /// be different from the actual callee (a different redeclaration, or a 517 /// virtual override), but this function's parameters are the ones that 518 /// appear in the parameter map. 519 const FunctionDecl *OrigCallee; 520 /// The call index of the frame that holds the argument values. 521 unsigned CallIndex; 522 /// The version of the parameters corresponding to this call. 523 unsigned Version; 524 }; 525 526 /// A stack frame in the constexpr call stack. 527 class CallStackFrame : public interp::Frame { 528 public: 529 EvalInfo &Info; 530 531 /// Parent - The caller of this stack frame. 532 CallStackFrame *Caller; 533 534 /// Callee - The function which was called. 535 const FunctionDecl *Callee; 536 537 /// This - The binding for the this pointer in this call, if any. 538 const LValue *This; 539 540 /// Information on how to find the arguments to this call. Our arguments 541 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 542 /// key and this value as the version. 543 CallRef Arguments; 544 545 /// Source location information about the default argument or default 546 /// initializer expression we're evaluating, if any. 547 CurrentSourceLocExprScope CurSourceLocExprScope; 548 549 // Note that we intentionally use std::map here so that references to 550 // values are stable. 551 typedef std::pair<const void *, unsigned> MapKeyTy; 552 typedef std::map<MapKeyTy, APValue> MapTy; 553 /// Temporaries - Temporary lvalues materialized within this stack frame. 554 MapTy Temporaries; 555 556 /// CallLoc - The location of the call expression for this call. 557 SourceLocation CallLoc; 558 559 /// Index - The call index of this call. 560 unsigned Index; 561 562 /// The stack of integers for tracking version numbers for temporaries. 563 SmallVector<unsigned, 2> TempVersionStack = {1}; 564 unsigned CurTempVersion = TempVersionStack.back(); 565 566 unsigned getTempVersion() const { return TempVersionStack.back(); } 567 568 void pushTempVersion() { 569 TempVersionStack.push_back(++CurTempVersion); 570 } 571 572 void popTempVersion() { 573 TempVersionStack.pop_back(); 574 } 575 576 CallRef createCall(const FunctionDecl *Callee) { 577 return {Callee, Index, ++CurTempVersion}; 578 } 579 580 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 581 // on the overall stack usage of deeply-recursing constexpr evaluations. 582 // (We should cache this map rather than recomputing it repeatedly.) 583 // But let's try this and see how it goes; we can look into caching the map 584 // as a later change. 585 586 /// LambdaCaptureFields - Mapping from captured variables/this to 587 /// corresponding data members in the closure class. 588 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 589 FieldDecl *LambdaThisCaptureField; 590 591 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 592 const FunctionDecl *Callee, const LValue *This, 593 CallRef Arguments); 594 ~CallStackFrame(); 595 596 // Return the temporary for Key whose version number is Version. 597 APValue *getTemporary(const void *Key, unsigned Version) { 598 MapKeyTy KV(Key, Version); 599 auto LB = Temporaries.lower_bound(KV); 600 if (LB != Temporaries.end() && LB->first == KV) 601 return &LB->second; 602 // Pair (Key,Version) wasn't found in the map. Check that no elements 603 // in the map have 'Key' as their key. 604 assert((LB == Temporaries.end() || LB->first.first != Key) && 605 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 606 "Element with key 'Key' found in map"); 607 return nullptr; 608 } 609 610 // Return the current temporary for Key in the map. 611 APValue *getCurrentTemporary(const void *Key) { 612 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 613 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 614 return &std::prev(UB)->second; 615 return nullptr; 616 } 617 618 // Return the version number of the current temporary for Key. 619 unsigned getCurrentTemporaryVersion(const void *Key) const { 620 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 621 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 622 return std::prev(UB)->first.second; 623 return 0; 624 } 625 626 /// Allocate storage for an object of type T in this stack frame. 627 /// Populates LV with a handle to the created object. Key identifies 628 /// the temporary within the stack frame, and must not be reused without 629 /// bumping the temporary version number. 630 template<typename KeyT> 631 APValue &createTemporary(const KeyT *Key, QualType T, 632 ScopeKind Scope, LValue &LV); 633 634 /// Allocate storage for a parameter of a function call made in this frame. 635 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 636 637 void describe(llvm::raw_ostream &OS) override; 638 639 Frame *getCaller() const override { return Caller; } 640 SourceLocation getCallLocation() const override { return CallLoc; } 641 const FunctionDecl *getCallee() const override { return Callee; } 642 643 bool isStdFunction() const { 644 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 645 if (DC->isStdNamespace()) 646 return true; 647 return false; 648 } 649 650 private: 651 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 652 ScopeKind Scope); 653 }; 654 655 /// Temporarily override 'this'. 656 class ThisOverrideRAII { 657 public: 658 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 659 : Frame(Frame), OldThis(Frame.This) { 660 if (Enable) 661 Frame.This = NewThis; 662 } 663 ~ThisOverrideRAII() { 664 Frame.This = OldThis; 665 } 666 private: 667 CallStackFrame &Frame; 668 const LValue *OldThis; 669 }; 670 } 671 672 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 673 const LValue &This, QualType ThisType); 674 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 675 APValue::LValueBase LVBase, APValue &Value, 676 QualType T); 677 678 namespace { 679 /// A cleanup, and a flag indicating whether it is lifetime-extended. 680 class Cleanup { 681 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 682 APValue::LValueBase Base; 683 QualType T; 684 685 public: 686 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 687 ScopeKind Scope) 688 : Value(Val, Scope), Base(Base), T(T) {} 689 690 /// Determine whether this cleanup should be performed at the end of the 691 /// given kind of scope. 692 bool isDestroyedAtEndOf(ScopeKind K) const { 693 return (int)Value.getInt() >= (int)K; 694 } 695 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 696 if (RunDestructors) { 697 SourceLocation Loc; 698 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 699 Loc = VD->getLocation(); 700 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 701 Loc = E->getExprLoc(); 702 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 703 } 704 *Value.getPointer() = APValue(); 705 return true; 706 } 707 708 bool hasSideEffect() { 709 return T.isDestructedType(); 710 } 711 }; 712 713 /// A reference to an object whose construction we are currently evaluating. 714 struct ObjectUnderConstruction { 715 APValue::LValueBase Base; 716 ArrayRef<APValue::LValuePathEntry> Path; 717 friend bool operator==(const ObjectUnderConstruction &LHS, 718 const ObjectUnderConstruction &RHS) { 719 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 720 } 721 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 722 return llvm::hash_combine(Obj.Base, Obj.Path); 723 } 724 }; 725 enum class ConstructionPhase { 726 None, 727 Bases, 728 AfterBases, 729 AfterFields, 730 Destroying, 731 DestroyingBases 732 }; 733 } 734 735 namespace llvm { 736 template<> struct DenseMapInfo<ObjectUnderConstruction> { 737 using Base = DenseMapInfo<APValue::LValueBase>; 738 static ObjectUnderConstruction getEmptyKey() { 739 return {Base::getEmptyKey(), {}}; } 740 static ObjectUnderConstruction getTombstoneKey() { 741 return {Base::getTombstoneKey(), {}}; 742 } 743 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 744 return hash_value(Object); 745 } 746 static bool isEqual(const ObjectUnderConstruction &LHS, 747 const ObjectUnderConstruction &RHS) { 748 return LHS == RHS; 749 } 750 }; 751 } 752 753 namespace { 754 /// A dynamically-allocated heap object. 755 struct DynAlloc { 756 /// The value of this heap-allocated object. 757 APValue Value; 758 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 759 /// or a CallExpr (the latter is for direct calls to operator new inside 760 /// std::allocator<T>::allocate). 761 const Expr *AllocExpr = nullptr; 762 763 enum Kind { 764 New, 765 ArrayNew, 766 StdAllocator 767 }; 768 769 /// Get the kind of the allocation. This must match between allocation 770 /// and deallocation. 771 Kind getKind() const { 772 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 773 return NE->isArray() ? ArrayNew : New; 774 assert(isa<CallExpr>(AllocExpr)); 775 return StdAllocator; 776 } 777 }; 778 779 struct DynAllocOrder { 780 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 781 return L.getIndex() < R.getIndex(); 782 } 783 }; 784 785 /// EvalInfo - This is a private struct used by the evaluator to capture 786 /// information about a subexpression as it is folded. It retains information 787 /// about the AST context, but also maintains information about the folded 788 /// expression. 789 /// 790 /// If an expression could be evaluated, it is still possible it is not a C 791 /// "integer constant expression" or constant expression. If not, this struct 792 /// captures information about how and why not. 793 /// 794 /// One bit of information passed *into* the request for constant folding 795 /// indicates whether the subexpression is "evaluated" or not according to C 796 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 797 /// evaluate the expression regardless of what the RHS is, but C only allows 798 /// certain things in certain situations. 799 class EvalInfo : public interp::State { 800 public: 801 ASTContext &Ctx; 802 803 /// EvalStatus - Contains information about the evaluation. 804 Expr::EvalStatus &EvalStatus; 805 806 /// CurrentCall - The top of the constexpr call stack. 807 CallStackFrame *CurrentCall; 808 809 /// CallStackDepth - The number of calls in the call stack right now. 810 unsigned CallStackDepth; 811 812 /// NextCallIndex - The next call index to assign. 813 unsigned NextCallIndex; 814 815 /// StepsLeft - The remaining number of evaluation steps we're permitted 816 /// to perform. This is essentially a limit for the number of statements 817 /// we will evaluate. 818 unsigned StepsLeft; 819 820 /// Enable the experimental new constant interpreter. If an expression is 821 /// not supported by the interpreter, an error is triggered. 822 bool EnableNewConstInterp; 823 824 /// BottomFrame - The frame in which evaluation started. This must be 825 /// initialized after CurrentCall and CallStackDepth. 826 CallStackFrame BottomFrame; 827 828 /// A stack of values whose lifetimes end at the end of some surrounding 829 /// evaluation frame. 830 llvm::SmallVector<Cleanup, 16> CleanupStack; 831 832 /// EvaluatingDecl - This is the declaration whose initializer is being 833 /// evaluated, if any. 834 APValue::LValueBase EvaluatingDecl; 835 836 enum class EvaluatingDeclKind { 837 None, 838 /// We're evaluating the construction of EvaluatingDecl. 839 Ctor, 840 /// We're evaluating the destruction of EvaluatingDecl. 841 Dtor, 842 }; 843 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 844 845 /// EvaluatingDeclValue - This is the value being constructed for the 846 /// declaration whose initializer is being evaluated, if any. 847 APValue *EvaluatingDeclValue; 848 849 /// Set of objects that are currently being constructed. 850 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 851 ObjectsUnderConstruction; 852 853 /// Current heap allocations, along with the location where each was 854 /// allocated. We use std::map here because we need stable addresses 855 /// for the stored APValues. 856 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 857 858 /// The number of heap allocations performed so far in this evaluation. 859 unsigned NumHeapAllocs = 0; 860 861 struct EvaluatingConstructorRAII { 862 EvalInfo &EI; 863 ObjectUnderConstruction Object; 864 bool DidInsert; 865 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 866 bool HasBases) 867 : EI(EI), Object(Object) { 868 DidInsert = 869 EI.ObjectsUnderConstruction 870 .insert({Object, HasBases ? ConstructionPhase::Bases 871 : ConstructionPhase::AfterBases}) 872 .second; 873 } 874 void finishedConstructingBases() { 875 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 876 } 877 void finishedConstructingFields() { 878 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 879 } 880 ~EvaluatingConstructorRAII() { 881 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 882 } 883 }; 884 885 struct EvaluatingDestructorRAII { 886 EvalInfo &EI; 887 ObjectUnderConstruction Object; 888 bool DidInsert; 889 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 890 : EI(EI), Object(Object) { 891 DidInsert = EI.ObjectsUnderConstruction 892 .insert({Object, ConstructionPhase::Destroying}) 893 .second; 894 } 895 void startedDestroyingBases() { 896 EI.ObjectsUnderConstruction[Object] = 897 ConstructionPhase::DestroyingBases; 898 } 899 ~EvaluatingDestructorRAII() { 900 if (DidInsert) 901 EI.ObjectsUnderConstruction.erase(Object); 902 } 903 }; 904 905 ConstructionPhase 906 isEvaluatingCtorDtor(APValue::LValueBase Base, 907 ArrayRef<APValue::LValuePathEntry> Path) { 908 return ObjectsUnderConstruction.lookup({Base, Path}); 909 } 910 911 /// If we're currently speculatively evaluating, the outermost call stack 912 /// depth at which we can mutate state, otherwise 0. 913 unsigned SpeculativeEvaluationDepth = 0; 914 915 /// The current array initialization index, if we're performing array 916 /// initialization. 917 uint64_t ArrayInitIndex = -1; 918 919 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 920 /// notes attached to it will also be stored, otherwise they will not be. 921 bool HasActiveDiagnostic; 922 923 /// Have we emitted a diagnostic explaining why we couldn't constant 924 /// fold (not just why it's not strictly a constant expression)? 925 bool HasFoldFailureDiagnostic; 926 927 /// Whether or not we're in a context where the front end requires a 928 /// constant value. 929 bool InConstantContext; 930 931 /// Whether we're checking that an expression is a potential constant 932 /// expression. If so, do not fail on constructs that could become constant 933 /// later on (such as a use of an undefined global). 934 bool CheckingPotentialConstantExpression = false; 935 936 /// Whether we're checking for an expression that has undefined behavior. 937 /// If so, we will produce warnings if we encounter an operation that is 938 /// always undefined. 939 bool CheckingForUndefinedBehavior = false; 940 941 enum EvaluationMode { 942 /// Evaluate as a constant expression. Stop if we find that the expression 943 /// is not a constant expression. 944 EM_ConstantExpression, 945 946 /// Evaluate as a constant expression. Stop if we find that the expression 947 /// is not a constant expression. Some expressions can be retried in the 948 /// optimizer if we don't constant fold them here, but in an unevaluated 949 /// context we try to fold them immediately since the optimizer never 950 /// gets a chance to look at it. 951 EM_ConstantExpressionUnevaluated, 952 953 /// Fold the expression to a constant. Stop if we hit a side-effect that 954 /// we can't model. 955 EM_ConstantFold, 956 957 /// Evaluate in any way we know how. Don't worry about side-effects that 958 /// can't be modeled. 959 EM_IgnoreSideEffects, 960 } EvalMode; 961 962 /// Are we checking whether the expression is a potential constant 963 /// expression? 964 bool checkingPotentialConstantExpression() const override { 965 return CheckingPotentialConstantExpression; 966 } 967 968 /// Are we checking an expression for overflow? 969 // FIXME: We should check for any kind of undefined or suspicious behavior 970 // in such constructs, not just overflow. 971 bool checkingForUndefinedBehavior() const override { 972 return CheckingForUndefinedBehavior; 973 } 974 975 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 976 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 977 CallStackDepth(0), NextCallIndex(1), 978 StepsLeft(C.getLangOpts().ConstexprStepLimit), 979 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 980 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 981 EvaluatingDecl((const ValueDecl *)nullptr), 982 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 983 HasFoldFailureDiagnostic(false), InConstantContext(false), 984 EvalMode(Mode) {} 985 986 ~EvalInfo() { 987 discardCleanups(); 988 } 989 990 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 991 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 992 EvaluatingDecl = Base; 993 IsEvaluatingDecl = EDK; 994 EvaluatingDeclValue = &Value; 995 } 996 997 bool CheckCallLimit(SourceLocation Loc) { 998 // Don't perform any constexpr calls (other than the call we're checking) 999 // when checking a potential constant expression. 1000 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 1001 return false; 1002 if (NextCallIndex == 0) { 1003 // NextCallIndex has wrapped around. 1004 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1005 return false; 1006 } 1007 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1008 return true; 1009 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1010 << getLangOpts().ConstexprCallDepth; 1011 return false; 1012 } 1013 1014 std::pair<CallStackFrame *, unsigned> 1015 getCallFrameAndDepth(unsigned CallIndex) { 1016 assert(CallIndex && "no call index in getCallFrameAndDepth"); 1017 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1018 // be null in this loop. 1019 unsigned Depth = CallStackDepth; 1020 CallStackFrame *Frame = CurrentCall; 1021 while (Frame->Index > CallIndex) { 1022 Frame = Frame->Caller; 1023 --Depth; 1024 } 1025 if (Frame->Index == CallIndex) 1026 return {Frame, Depth}; 1027 return {nullptr, 0}; 1028 } 1029 1030 bool nextStep(const Stmt *S) { 1031 if (!StepsLeft) { 1032 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1033 return false; 1034 } 1035 --StepsLeft; 1036 return true; 1037 } 1038 1039 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1040 1041 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1042 Optional<DynAlloc*> Result; 1043 auto It = HeapAllocs.find(DA); 1044 if (It != HeapAllocs.end()) 1045 Result = &It->second; 1046 return Result; 1047 } 1048 1049 /// Get the allocated storage for the given parameter of the given call. 1050 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1051 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1052 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1053 : nullptr; 1054 } 1055 1056 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1057 struct StdAllocatorCaller { 1058 unsigned FrameIndex; 1059 QualType ElemType; 1060 explicit operator bool() const { return FrameIndex != 0; }; 1061 }; 1062 1063 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1064 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1065 Call = Call->Caller) { 1066 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1067 if (!MD) 1068 continue; 1069 const IdentifierInfo *FnII = MD->getIdentifier(); 1070 if (!FnII || !FnII->isStr(FnName)) 1071 continue; 1072 1073 const auto *CTSD = 1074 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1075 if (!CTSD) 1076 continue; 1077 1078 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1079 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1080 if (CTSD->isInStdNamespace() && ClassII && 1081 ClassII->isStr("allocator") && TAL.size() >= 1 && 1082 TAL[0].getKind() == TemplateArgument::Type) 1083 return {Call->Index, TAL[0].getAsType()}; 1084 } 1085 1086 return {}; 1087 } 1088 1089 void performLifetimeExtension() { 1090 // Disable the cleanups for lifetime-extended temporaries. 1091 CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1092 CleanupStack.end(), 1093 [](Cleanup &C) { 1094 return !C.isDestroyedAtEndOf( 1095 ScopeKind::FullExpression); 1096 }), 1097 CleanupStack.end()); 1098 } 1099 1100 /// Throw away any remaining cleanups at the end of evaluation. If any 1101 /// cleanups would have had a side-effect, note that as an unmodeled 1102 /// side-effect and return false. Otherwise, return true. 1103 bool discardCleanups() { 1104 for (Cleanup &C : CleanupStack) { 1105 if (C.hasSideEffect() && !noteSideEffect()) { 1106 CleanupStack.clear(); 1107 return false; 1108 } 1109 } 1110 CleanupStack.clear(); 1111 return true; 1112 } 1113 1114 private: 1115 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1116 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1117 1118 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1119 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1120 1121 void setFoldFailureDiagnostic(bool Flag) override { 1122 HasFoldFailureDiagnostic = Flag; 1123 } 1124 1125 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1126 1127 ASTContext &getCtx() const override { return Ctx; } 1128 1129 // If we have a prior diagnostic, it will be noting that the expression 1130 // isn't a constant expression. This diagnostic is more important, 1131 // unless we require this evaluation to produce a constant expression. 1132 // 1133 // FIXME: We might want to show both diagnostics to the user in 1134 // EM_ConstantFold mode. 1135 bool hasPriorDiagnostic() override { 1136 if (!EvalStatus.Diag->empty()) { 1137 switch (EvalMode) { 1138 case EM_ConstantFold: 1139 case EM_IgnoreSideEffects: 1140 if (!HasFoldFailureDiagnostic) 1141 break; 1142 // We've already failed to fold something. Keep that diagnostic. 1143 LLVM_FALLTHROUGH; 1144 case EM_ConstantExpression: 1145 case EM_ConstantExpressionUnevaluated: 1146 setActiveDiagnostic(false); 1147 return true; 1148 } 1149 } 1150 return false; 1151 } 1152 1153 unsigned getCallStackDepth() override { return CallStackDepth; } 1154 1155 public: 1156 /// Should we continue evaluation after encountering a side-effect that we 1157 /// couldn't model? 1158 bool keepEvaluatingAfterSideEffect() { 1159 switch (EvalMode) { 1160 case EM_IgnoreSideEffects: 1161 return true; 1162 1163 case EM_ConstantExpression: 1164 case EM_ConstantExpressionUnevaluated: 1165 case EM_ConstantFold: 1166 // By default, assume any side effect might be valid in some other 1167 // evaluation of this expression from a different context. 1168 return checkingPotentialConstantExpression() || 1169 checkingForUndefinedBehavior(); 1170 } 1171 llvm_unreachable("Missed EvalMode case"); 1172 } 1173 1174 /// Note that we have had a side-effect, and determine whether we should 1175 /// keep evaluating. 1176 bool noteSideEffect() { 1177 EvalStatus.HasSideEffects = true; 1178 return keepEvaluatingAfterSideEffect(); 1179 } 1180 1181 /// Should we continue evaluation after encountering undefined behavior? 1182 bool keepEvaluatingAfterUndefinedBehavior() { 1183 switch (EvalMode) { 1184 case EM_IgnoreSideEffects: 1185 case EM_ConstantFold: 1186 return true; 1187 1188 case EM_ConstantExpression: 1189 case EM_ConstantExpressionUnevaluated: 1190 return checkingForUndefinedBehavior(); 1191 } 1192 llvm_unreachable("Missed EvalMode case"); 1193 } 1194 1195 /// Note that we hit something that was technically undefined behavior, but 1196 /// that we can evaluate past it (such as signed overflow or floating-point 1197 /// division by zero.) 1198 bool noteUndefinedBehavior() override { 1199 EvalStatus.HasUndefinedBehavior = true; 1200 return keepEvaluatingAfterUndefinedBehavior(); 1201 } 1202 1203 /// Should we continue evaluation as much as possible after encountering a 1204 /// construct which can't be reduced to a value? 1205 bool keepEvaluatingAfterFailure() const override { 1206 if (!StepsLeft) 1207 return false; 1208 1209 switch (EvalMode) { 1210 case EM_ConstantExpression: 1211 case EM_ConstantExpressionUnevaluated: 1212 case EM_ConstantFold: 1213 case EM_IgnoreSideEffects: 1214 return checkingPotentialConstantExpression() || 1215 checkingForUndefinedBehavior(); 1216 } 1217 llvm_unreachable("Missed EvalMode case"); 1218 } 1219 1220 /// Notes that we failed to evaluate an expression that other expressions 1221 /// directly depend on, and determine if we should keep evaluating. This 1222 /// should only be called if we actually intend to keep evaluating. 1223 /// 1224 /// Call noteSideEffect() instead if we may be able to ignore the value that 1225 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1226 /// 1227 /// (Foo(), 1) // use noteSideEffect 1228 /// (Foo() || true) // use noteSideEffect 1229 /// Foo() + 1 // use noteFailure 1230 LLVM_NODISCARD bool noteFailure() { 1231 // Failure when evaluating some expression often means there is some 1232 // subexpression whose evaluation was skipped. Therefore, (because we 1233 // don't track whether we skipped an expression when unwinding after an 1234 // evaluation failure) every evaluation failure that bubbles up from a 1235 // subexpression implies that a side-effect has potentially happened. We 1236 // skip setting the HasSideEffects flag to true until we decide to 1237 // continue evaluating after that point, which happens here. 1238 bool KeepGoing = keepEvaluatingAfterFailure(); 1239 EvalStatus.HasSideEffects |= KeepGoing; 1240 return KeepGoing; 1241 } 1242 1243 class ArrayInitLoopIndex { 1244 EvalInfo &Info; 1245 uint64_t OuterIndex; 1246 1247 public: 1248 ArrayInitLoopIndex(EvalInfo &Info) 1249 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1250 Info.ArrayInitIndex = 0; 1251 } 1252 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1253 1254 operator uint64_t&() { return Info.ArrayInitIndex; } 1255 }; 1256 }; 1257 1258 /// Object used to treat all foldable expressions as constant expressions. 1259 struct FoldConstant { 1260 EvalInfo &Info; 1261 bool Enabled; 1262 bool HadNoPriorDiags; 1263 EvalInfo::EvaluationMode OldMode; 1264 1265 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1266 : Info(Info), 1267 Enabled(Enabled), 1268 HadNoPriorDiags(Info.EvalStatus.Diag && 1269 Info.EvalStatus.Diag->empty() && 1270 !Info.EvalStatus.HasSideEffects), 1271 OldMode(Info.EvalMode) { 1272 if (Enabled) 1273 Info.EvalMode = EvalInfo::EM_ConstantFold; 1274 } 1275 void keepDiagnostics() { Enabled = false; } 1276 ~FoldConstant() { 1277 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1278 !Info.EvalStatus.HasSideEffects) 1279 Info.EvalStatus.Diag->clear(); 1280 Info.EvalMode = OldMode; 1281 } 1282 }; 1283 1284 /// RAII object used to set the current evaluation mode to ignore 1285 /// side-effects. 1286 struct IgnoreSideEffectsRAII { 1287 EvalInfo &Info; 1288 EvalInfo::EvaluationMode OldMode; 1289 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1290 : Info(Info), OldMode(Info.EvalMode) { 1291 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1292 } 1293 1294 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1295 }; 1296 1297 /// RAII object used to optionally suppress diagnostics and side-effects from 1298 /// a speculative evaluation. 1299 class SpeculativeEvaluationRAII { 1300 EvalInfo *Info = nullptr; 1301 Expr::EvalStatus OldStatus; 1302 unsigned OldSpeculativeEvaluationDepth; 1303 1304 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1305 Info = Other.Info; 1306 OldStatus = Other.OldStatus; 1307 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1308 Other.Info = nullptr; 1309 } 1310 1311 void maybeRestoreState() { 1312 if (!Info) 1313 return; 1314 1315 Info->EvalStatus = OldStatus; 1316 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1317 } 1318 1319 public: 1320 SpeculativeEvaluationRAII() = default; 1321 1322 SpeculativeEvaluationRAII( 1323 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1324 : Info(&Info), OldStatus(Info.EvalStatus), 1325 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1326 Info.EvalStatus.Diag = NewDiag; 1327 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1328 } 1329 1330 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1331 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1332 moveFromAndCancel(std::move(Other)); 1333 } 1334 1335 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1336 maybeRestoreState(); 1337 moveFromAndCancel(std::move(Other)); 1338 return *this; 1339 } 1340 1341 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1342 }; 1343 1344 /// RAII object wrapping a full-expression or block scope, and handling 1345 /// the ending of the lifetime of temporaries created within it. 1346 template<ScopeKind Kind> 1347 class ScopeRAII { 1348 EvalInfo &Info; 1349 unsigned OldStackSize; 1350 public: 1351 ScopeRAII(EvalInfo &Info) 1352 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1353 // Push a new temporary version. This is needed to distinguish between 1354 // temporaries created in different iterations of a loop. 1355 Info.CurrentCall->pushTempVersion(); 1356 } 1357 bool destroy(bool RunDestructors = true) { 1358 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1359 OldStackSize = -1U; 1360 return OK; 1361 } 1362 ~ScopeRAII() { 1363 if (OldStackSize != -1U) 1364 destroy(false); 1365 // Body moved to a static method to encourage the compiler to inline away 1366 // instances of this class. 1367 Info.CurrentCall->popTempVersion(); 1368 } 1369 private: 1370 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1371 unsigned OldStackSize) { 1372 assert(OldStackSize <= Info.CleanupStack.size() && 1373 "running cleanups out of order?"); 1374 1375 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1376 // for a full-expression scope. 1377 bool Success = true; 1378 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1379 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1380 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1381 Success = false; 1382 break; 1383 } 1384 } 1385 } 1386 1387 // Compact any retained cleanups. 1388 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1389 if (Kind != ScopeKind::Block) 1390 NewEnd = 1391 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1392 return C.isDestroyedAtEndOf(Kind); 1393 }); 1394 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1395 return Success; 1396 } 1397 }; 1398 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1399 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1400 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1401 } 1402 1403 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1404 CheckSubobjectKind CSK) { 1405 if (Invalid) 1406 return false; 1407 if (isOnePastTheEnd()) { 1408 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1409 << CSK; 1410 setInvalid(); 1411 return false; 1412 } 1413 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1414 // must actually be at least one array element; even a VLA cannot have a 1415 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1416 return true; 1417 } 1418 1419 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1420 const Expr *E) { 1421 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1422 // Do not set the designator as invalid: we can represent this situation, 1423 // and correct handling of __builtin_object_size requires us to do so. 1424 } 1425 1426 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1427 const Expr *E, 1428 const APSInt &N) { 1429 // If we're complaining, we must be able to statically determine the size of 1430 // the most derived array. 1431 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1432 Info.CCEDiag(E, diag::note_constexpr_array_index) 1433 << N << /*array*/ 0 1434 << static_cast<unsigned>(getMostDerivedArraySize()); 1435 else 1436 Info.CCEDiag(E, diag::note_constexpr_array_index) 1437 << N << /*non-array*/ 1; 1438 setInvalid(); 1439 } 1440 1441 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1442 const FunctionDecl *Callee, const LValue *This, 1443 CallRef Call) 1444 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1445 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1446 Info.CurrentCall = this; 1447 ++Info.CallStackDepth; 1448 } 1449 1450 CallStackFrame::~CallStackFrame() { 1451 assert(Info.CurrentCall == this && "calls retired out of order"); 1452 --Info.CallStackDepth; 1453 Info.CurrentCall = Caller; 1454 } 1455 1456 static bool isRead(AccessKinds AK) { 1457 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1458 } 1459 1460 static bool isModification(AccessKinds AK) { 1461 switch (AK) { 1462 case AK_Read: 1463 case AK_ReadObjectRepresentation: 1464 case AK_MemberCall: 1465 case AK_DynamicCast: 1466 case AK_TypeId: 1467 return false; 1468 case AK_Assign: 1469 case AK_Increment: 1470 case AK_Decrement: 1471 case AK_Construct: 1472 case AK_Destroy: 1473 return true; 1474 } 1475 llvm_unreachable("unknown access kind"); 1476 } 1477 1478 static bool isAnyAccess(AccessKinds AK) { 1479 return isRead(AK) || isModification(AK); 1480 } 1481 1482 /// Is this an access per the C++ definition? 1483 static bool isFormalAccess(AccessKinds AK) { 1484 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1485 } 1486 1487 /// Is this kind of axcess valid on an indeterminate object value? 1488 static bool isValidIndeterminateAccess(AccessKinds AK) { 1489 switch (AK) { 1490 case AK_Read: 1491 case AK_Increment: 1492 case AK_Decrement: 1493 // These need the object's value. 1494 return false; 1495 1496 case AK_ReadObjectRepresentation: 1497 case AK_Assign: 1498 case AK_Construct: 1499 case AK_Destroy: 1500 // Construction and destruction don't need the value. 1501 return true; 1502 1503 case AK_MemberCall: 1504 case AK_DynamicCast: 1505 case AK_TypeId: 1506 // These aren't really meaningful on scalars. 1507 return true; 1508 } 1509 llvm_unreachable("unknown access kind"); 1510 } 1511 1512 namespace { 1513 struct ComplexValue { 1514 private: 1515 bool IsInt; 1516 1517 public: 1518 APSInt IntReal, IntImag; 1519 APFloat FloatReal, FloatImag; 1520 1521 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1522 1523 void makeComplexFloat() { IsInt = false; } 1524 bool isComplexFloat() const { return !IsInt; } 1525 APFloat &getComplexFloatReal() { return FloatReal; } 1526 APFloat &getComplexFloatImag() { return FloatImag; } 1527 1528 void makeComplexInt() { IsInt = true; } 1529 bool isComplexInt() const { return IsInt; } 1530 APSInt &getComplexIntReal() { return IntReal; } 1531 APSInt &getComplexIntImag() { return IntImag; } 1532 1533 void moveInto(APValue &v) const { 1534 if (isComplexFloat()) 1535 v = APValue(FloatReal, FloatImag); 1536 else 1537 v = APValue(IntReal, IntImag); 1538 } 1539 void setFrom(const APValue &v) { 1540 assert(v.isComplexFloat() || v.isComplexInt()); 1541 if (v.isComplexFloat()) { 1542 makeComplexFloat(); 1543 FloatReal = v.getComplexFloatReal(); 1544 FloatImag = v.getComplexFloatImag(); 1545 } else { 1546 makeComplexInt(); 1547 IntReal = v.getComplexIntReal(); 1548 IntImag = v.getComplexIntImag(); 1549 } 1550 } 1551 }; 1552 1553 struct LValue { 1554 APValue::LValueBase Base; 1555 CharUnits Offset; 1556 SubobjectDesignator Designator; 1557 bool IsNullPtr : 1; 1558 bool InvalidBase : 1; 1559 1560 const APValue::LValueBase getLValueBase() const { return Base; } 1561 CharUnits &getLValueOffset() { return Offset; } 1562 const CharUnits &getLValueOffset() const { return Offset; } 1563 SubobjectDesignator &getLValueDesignator() { return Designator; } 1564 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1565 bool isNullPointer() const { return IsNullPtr;} 1566 1567 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1568 unsigned getLValueVersion() const { return Base.getVersion(); } 1569 1570 void moveInto(APValue &V) const { 1571 if (Designator.Invalid) 1572 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1573 else { 1574 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1575 V = APValue(Base, Offset, Designator.Entries, 1576 Designator.IsOnePastTheEnd, IsNullPtr); 1577 } 1578 } 1579 void setFrom(ASTContext &Ctx, const APValue &V) { 1580 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1581 Base = V.getLValueBase(); 1582 Offset = V.getLValueOffset(); 1583 InvalidBase = false; 1584 Designator = SubobjectDesignator(Ctx, V); 1585 IsNullPtr = V.isNullPointer(); 1586 } 1587 1588 void set(APValue::LValueBase B, bool BInvalid = false) { 1589 #ifndef NDEBUG 1590 // We only allow a few types of invalid bases. Enforce that here. 1591 if (BInvalid) { 1592 const auto *E = B.get<const Expr *>(); 1593 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1594 "Unexpected type of invalid base"); 1595 } 1596 #endif 1597 1598 Base = B; 1599 Offset = CharUnits::fromQuantity(0); 1600 InvalidBase = BInvalid; 1601 Designator = SubobjectDesignator(getType(B)); 1602 IsNullPtr = false; 1603 } 1604 1605 void setNull(ASTContext &Ctx, QualType PointerTy) { 1606 Base = (const ValueDecl *)nullptr; 1607 Offset = 1608 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1609 InvalidBase = false; 1610 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1611 IsNullPtr = true; 1612 } 1613 1614 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1615 set(B, true); 1616 } 1617 1618 std::string toString(ASTContext &Ctx, QualType T) const { 1619 APValue Printable; 1620 moveInto(Printable); 1621 return Printable.getAsString(Ctx, T); 1622 } 1623 1624 private: 1625 // Check that this LValue is not based on a null pointer. If it is, produce 1626 // a diagnostic and mark the designator as invalid. 1627 template <typename GenDiagType> 1628 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1629 if (Designator.Invalid) 1630 return false; 1631 if (IsNullPtr) { 1632 GenDiag(); 1633 Designator.setInvalid(); 1634 return false; 1635 } 1636 return true; 1637 } 1638 1639 public: 1640 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1641 CheckSubobjectKind CSK) { 1642 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1643 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1644 }); 1645 } 1646 1647 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1648 AccessKinds AK) { 1649 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1650 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1651 }); 1652 } 1653 1654 // Check this LValue refers to an object. If not, set the designator to be 1655 // invalid and emit a diagnostic. 1656 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1657 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1658 Designator.checkSubobject(Info, E, CSK); 1659 } 1660 1661 void addDecl(EvalInfo &Info, const Expr *E, 1662 const Decl *D, bool Virtual = false) { 1663 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1664 Designator.addDeclUnchecked(D, Virtual); 1665 } 1666 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1667 if (!Designator.Entries.empty()) { 1668 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1669 Designator.setInvalid(); 1670 return; 1671 } 1672 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1673 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1674 Designator.FirstEntryIsAnUnsizedArray = true; 1675 Designator.addUnsizedArrayUnchecked(ElemTy); 1676 } 1677 } 1678 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1679 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1680 Designator.addArrayUnchecked(CAT); 1681 } 1682 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1683 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1684 Designator.addComplexUnchecked(EltTy, Imag); 1685 } 1686 void clearIsNullPointer() { 1687 IsNullPtr = false; 1688 } 1689 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1690 const APSInt &Index, CharUnits ElementSize) { 1691 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1692 // but we're not required to diagnose it and it's valid in C++.) 1693 if (!Index) 1694 return; 1695 1696 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1697 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1698 // offsets. 1699 uint64_t Offset64 = Offset.getQuantity(); 1700 uint64_t ElemSize64 = ElementSize.getQuantity(); 1701 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1702 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1703 1704 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1705 Designator.adjustIndex(Info, E, Index); 1706 clearIsNullPointer(); 1707 } 1708 void adjustOffset(CharUnits N) { 1709 Offset += N; 1710 if (N.getQuantity()) 1711 clearIsNullPointer(); 1712 } 1713 }; 1714 1715 struct MemberPtr { 1716 MemberPtr() {} 1717 explicit MemberPtr(const ValueDecl *Decl) : 1718 DeclAndIsDerivedMember(Decl, false), Path() {} 1719 1720 /// The member or (direct or indirect) field referred to by this member 1721 /// pointer, or 0 if this is a null member pointer. 1722 const ValueDecl *getDecl() const { 1723 return DeclAndIsDerivedMember.getPointer(); 1724 } 1725 /// Is this actually a member of some type derived from the relevant class? 1726 bool isDerivedMember() const { 1727 return DeclAndIsDerivedMember.getInt(); 1728 } 1729 /// Get the class which the declaration actually lives in. 1730 const CXXRecordDecl *getContainingRecord() const { 1731 return cast<CXXRecordDecl>( 1732 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1733 } 1734 1735 void moveInto(APValue &V) const { 1736 V = APValue(getDecl(), isDerivedMember(), Path); 1737 } 1738 void setFrom(const APValue &V) { 1739 assert(V.isMemberPointer()); 1740 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1741 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1742 Path.clear(); 1743 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1744 Path.insert(Path.end(), P.begin(), P.end()); 1745 } 1746 1747 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1748 /// whether the member is a member of some class derived from the class type 1749 /// of the member pointer. 1750 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1751 /// Path - The path of base/derived classes from the member declaration's 1752 /// class (exclusive) to the class type of the member pointer (inclusive). 1753 SmallVector<const CXXRecordDecl*, 4> Path; 1754 1755 /// Perform a cast towards the class of the Decl (either up or down the 1756 /// hierarchy). 1757 bool castBack(const CXXRecordDecl *Class) { 1758 assert(!Path.empty()); 1759 const CXXRecordDecl *Expected; 1760 if (Path.size() >= 2) 1761 Expected = Path[Path.size() - 2]; 1762 else 1763 Expected = getContainingRecord(); 1764 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1765 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1766 // if B does not contain the original member and is not a base or 1767 // derived class of the class containing the original member, the result 1768 // of the cast is undefined. 1769 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1770 // (D::*). We consider that to be a language defect. 1771 return false; 1772 } 1773 Path.pop_back(); 1774 return true; 1775 } 1776 /// Perform a base-to-derived member pointer cast. 1777 bool castToDerived(const CXXRecordDecl *Derived) { 1778 if (!getDecl()) 1779 return true; 1780 if (!isDerivedMember()) { 1781 Path.push_back(Derived); 1782 return true; 1783 } 1784 if (!castBack(Derived)) 1785 return false; 1786 if (Path.empty()) 1787 DeclAndIsDerivedMember.setInt(false); 1788 return true; 1789 } 1790 /// Perform a derived-to-base member pointer cast. 1791 bool castToBase(const CXXRecordDecl *Base) { 1792 if (!getDecl()) 1793 return true; 1794 if (Path.empty()) 1795 DeclAndIsDerivedMember.setInt(true); 1796 if (isDerivedMember()) { 1797 Path.push_back(Base); 1798 return true; 1799 } 1800 return castBack(Base); 1801 } 1802 }; 1803 1804 /// Compare two member pointers, which are assumed to be of the same type. 1805 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1806 if (!LHS.getDecl() || !RHS.getDecl()) 1807 return !LHS.getDecl() && !RHS.getDecl(); 1808 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1809 return false; 1810 return LHS.Path == RHS.Path; 1811 } 1812 } 1813 1814 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1815 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1816 const LValue &This, const Expr *E, 1817 bool AllowNonLiteralTypes = false); 1818 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1819 bool InvalidBaseOK = false); 1820 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1821 bool InvalidBaseOK = false); 1822 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1823 EvalInfo &Info); 1824 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1825 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1826 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1827 EvalInfo &Info); 1828 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1829 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1830 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1831 EvalInfo &Info); 1832 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1833 1834 /// Evaluate an integer or fixed point expression into an APResult. 1835 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1836 EvalInfo &Info); 1837 1838 /// Evaluate only a fixed point expression into an APResult. 1839 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1840 EvalInfo &Info); 1841 1842 //===----------------------------------------------------------------------===// 1843 // Misc utilities 1844 //===----------------------------------------------------------------------===// 1845 1846 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1847 /// preserving its value (by extending by up to one bit as needed). 1848 static void negateAsSigned(APSInt &Int) { 1849 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1850 Int = Int.extend(Int.getBitWidth() + 1); 1851 Int.setIsSigned(true); 1852 } 1853 Int = -Int; 1854 } 1855 1856 template<typename KeyT> 1857 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1858 ScopeKind Scope, LValue &LV) { 1859 unsigned Version = getTempVersion(); 1860 APValue::LValueBase Base(Key, Index, Version); 1861 LV.set(Base); 1862 return createLocal(Base, Key, T, Scope); 1863 } 1864 1865 /// Allocate storage for a parameter of a function call made in this frame. 1866 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1867 LValue &LV) { 1868 assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1869 APValue::LValueBase Base(PVD, Index, Args.Version); 1870 LV.set(Base); 1871 // We always destroy parameters at the end of the call, even if we'd allow 1872 // them to live to the end of the full-expression at runtime, in order to 1873 // give portable results and match other compilers. 1874 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1875 } 1876 1877 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1878 QualType T, ScopeKind Scope) { 1879 assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1880 unsigned Version = Base.getVersion(); 1881 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1882 assert(Result.isAbsent() && "local created multiple times"); 1883 1884 // If we're creating a local immediately in the operand of a speculative 1885 // evaluation, don't register a cleanup to be run outside the speculative 1886 // evaluation context, since we won't actually be able to initialize this 1887 // object. 1888 if (Index <= Info.SpeculativeEvaluationDepth) { 1889 if (T.isDestructedType()) 1890 Info.noteSideEffect(); 1891 } else { 1892 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1893 } 1894 return Result; 1895 } 1896 1897 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1898 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1899 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1900 return nullptr; 1901 } 1902 1903 DynamicAllocLValue DA(NumHeapAllocs++); 1904 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1905 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1906 std::forward_as_tuple(DA), std::tuple<>()); 1907 assert(Result.second && "reused a heap alloc index?"); 1908 Result.first->second.AllocExpr = E; 1909 return &Result.first->second.Value; 1910 } 1911 1912 /// Produce a string describing the given constexpr call. 1913 void CallStackFrame::describe(raw_ostream &Out) { 1914 unsigned ArgIndex = 0; 1915 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1916 !isa<CXXConstructorDecl>(Callee) && 1917 cast<CXXMethodDecl>(Callee)->isInstance(); 1918 1919 if (!IsMemberCall) 1920 Out << *Callee << '('; 1921 1922 if (This && IsMemberCall) { 1923 APValue Val; 1924 This->moveInto(Val); 1925 Val.printPretty(Out, Info.Ctx, 1926 This->Designator.MostDerivedType); 1927 // FIXME: Add parens around Val if needed. 1928 Out << "->" << *Callee << '('; 1929 IsMemberCall = false; 1930 } 1931 1932 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1933 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1934 if (ArgIndex > (unsigned)IsMemberCall) 1935 Out << ", "; 1936 1937 const ParmVarDecl *Param = *I; 1938 APValue *V = Info.getParamSlot(Arguments, Param); 1939 if (V) 1940 V->printPretty(Out, Info.Ctx, Param->getType()); 1941 else 1942 Out << "<...>"; 1943 1944 if (ArgIndex == 0 && IsMemberCall) 1945 Out << "->" << *Callee << '('; 1946 } 1947 1948 Out << ')'; 1949 } 1950 1951 /// Evaluate an expression to see if it had side-effects, and discard its 1952 /// result. 1953 /// \return \c true if the caller should keep evaluating. 1954 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1955 APValue Scratch; 1956 if (!Evaluate(Scratch, Info, E)) 1957 // We don't need the value, but we might have skipped a side effect here. 1958 return Info.noteSideEffect(); 1959 return true; 1960 } 1961 1962 /// Should this call expression be treated as a string literal? 1963 static bool IsStringLiteralCall(const CallExpr *E) { 1964 unsigned Builtin = E->getBuiltinCallee(); 1965 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1966 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1967 } 1968 1969 static bool IsGlobalLValue(APValue::LValueBase B) { 1970 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1971 // constant expression of pointer type that evaluates to... 1972 1973 // ... a null pointer value, or a prvalue core constant expression of type 1974 // std::nullptr_t. 1975 if (!B) return true; 1976 1977 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1978 // ... the address of an object with static storage duration, 1979 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1980 return VD->hasGlobalStorage(); 1981 if (isa<TemplateParamObjectDecl>(D)) 1982 return true; 1983 // ... the address of a function, 1984 // ... the address of a GUID [MS extension], 1985 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1986 } 1987 1988 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1989 return true; 1990 1991 const Expr *E = B.get<const Expr*>(); 1992 switch (E->getStmtClass()) { 1993 default: 1994 return false; 1995 case Expr::CompoundLiteralExprClass: { 1996 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1997 return CLE->isFileScope() && CLE->isLValue(); 1998 } 1999 case Expr::MaterializeTemporaryExprClass: 2000 // A materialized temporary might have been lifetime-extended to static 2001 // storage duration. 2002 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2003 // A string literal has static storage duration. 2004 case Expr::StringLiteralClass: 2005 case Expr::PredefinedExprClass: 2006 case Expr::ObjCStringLiteralClass: 2007 case Expr::ObjCEncodeExprClass: 2008 return true; 2009 case Expr::ObjCBoxedExprClass: 2010 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2011 case Expr::CallExprClass: 2012 return IsStringLiteralCall(cast<CallExpr>(E)); 2013 // For GCC compatibility, &&label has static storage duration. 2014 case Expr::AddrLabelExprClass: 2015 return true; 2016 // A Block literal expression may be used as the initialization value for 2017 // Block variables at global or local static scope. 2018 case Expr::BlockExprClass: 2019 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2020 case Expr::ImplicitValueInitExprClass: 2021 // FIXME: 2022 // We can never form an lvalue with an implicit value initialization as its 2023 // base through expression evaluation, so these only appear in one case: the 2024 // implicit variable declaration we invent when checking whether a constexpr 2025 // constructor can produce a constant expression. We must assume that such 2026 // an expression might be a global lvalue. 2027 return true; 2028 } 2029 } 2030 2031 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2032 return LVal.Base.dyn_cast<const ValueDecl*>(); 2033 } 2034 2035 static bool IsLiteralLValue(const LValue &Value) { 2036 if (Value.getLValueCallIndex()) 2037 return false; 2038 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2039 return E && !isa<MaterializeTemporaryExpr>(E); 2040 } 2041 2042 static bool IsWeakLValue(const LValue &Value) { 2043 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2044 return Decl && Decl->isWeak(); 2045 } 2046 2047 static bool isZeroSized(const LValue &Value) { 2048 const ValueDecl *Decl = GetLValueBaseDecl(Value); 2049 if (Decl && isa<VarDecl>(Decl)) { 2050 QualType Ty = Decl->getType(); 2051 if (Ty->isArrayType()) 2052 return Ty->isIncompleteType() || 2053 Decl->getASTContext().getTypeSize(Ty) == 0; 2054 } 2055 return false; 2056 } 2057 2058 static bool HasSameBase(const LValue &A, const LValue &B) { 2059 if (!A.getLValueBase()) 2060 return !B.getLValueBase(); 2061 if (!B.getLValueBase()) 2062 return false; 2063 2064 if (A.getLValueBase().getOpaqueValue() != 2065 B.getLValueBase().getOpaqueValue()) 2066 return false; 2067 2068 return A.getLValueCallIndex() == B.getLValueCallIndex() && 2069 A.getLValueVersion() == B.getLValueVersion(); 2070 } 2071 2072 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2073 assert(Base && "no location for a null lvalue"); 2074 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2075 2076 // For a parameter, find the corresponding call stack frame (if it still 2077 // exists), and point at the parameter of the function definition we actually 2078 // invoked. 2079 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2080 unsigned Idx = PVD->getFunctionScopeIndex(); 2081 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2082 if (F->Arguments.CallIndex == Base.getCallIndex() && 2083 F->Arguments.Version == Base.getVersion() && F->Callee && 2084 Idx < F->Callee->getNumParams()) { 2085 VD = F->Callee->getParamDecl(Idx); 2086 break; 2087 } 2088 } 2089 } 2090 2091 if (VD) 2092 Info.Note(VD->getLocation(), diag::note_declared_at); 2093 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2094 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2095 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2096 // FIXME: Produce a note for dangling pointers too. 2097 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2098 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2099 diag::note_constexpr_dynamic_alloc_here); 2100 } 2101 // We have no information to show for a typeid(T) object. 2102 } 2103 2104 enum class CheckEvaluationResultKind { 2105 ConstantExpression, 2106 FullyInitialized, 2107 }; 2108 2109 /// Materialized temporaries that we've already checked to determine if they're 2110 /// initializsed by a constant expression. 2111 using CheckedTemporaries = 2112 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2113 2114 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2115 EvalInfo &Info, SourceLocation DiagLoc, 2116 QualType Type, const APValue &Value, 2117 Expr::ConstExprUsage Usage, 2118 SourceLocation SubobjectLoc, 2119 CheckedTemporaries &CheckedTemps); 2120 2121 /// Check that this reference or pointer core constant expression is a valid 2122 /// value for an address or reference constant expression. Return true if we 2123 /// can fold this expression, whether or not it's a constant expression. 2124 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2125 QualType Type, const LValue &LVal, 2126 Expr::ConstExprUsage Usage, 2127 CheckedTemporaries &CheckedTemps) { 2128 bool IsReferenceType = Type->isReferenceType(); 2129 2130 APValue::LValueBase Base = LVal.getLValueBase(); 2131 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2132 2133 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2134 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2135 if (FD->isConsteval()) { 2136 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2137 << !Type->isAnyPointerType(); 2138 Info.Note(FD->getLocation(), diag::note_declared_at); 2139 return false; 2140 } 2141 } 2142 } 2143 2144 // Check that the object is a global. Note that the fake 'this' object we 2145 // manufacture when checking potential constant expressions is conservatively 2146 // assumed to be global here. 2147 if (!IsGlobalLValue(Base)) { 2148 if (Info.getLangOpts().CPlusPlus11) { 2149 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2150 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2151 << IsReferenceType << !Designator.Entries.empty() 2152 << !!VD << VD; 2153 2154 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2155 if (VarD && VarD->isConstexpr()) { 2156 // Non-static local constexpr variables have unintuitive semantics: 2157 // constexpr int a = 1; 2158 // constexpr const int *p = &a; 2159 // ... is invalid because the address of 'a' is not constant. Suggest 2160 // adding a 'static' in this case. 2161 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2162 << VarD 2163 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2164 } else { 2165 NoteLValueLocation(Info, Base); 2166 } 2167 } else { 2168 Info.FFDiag(Loc); 2169 } 2170 // Don't allow references to temporaries to escape. 2171 return false; 2172 } 2173 assert((Info.checkingPotentialConstantExpression() || 2174 LVal.getLValueCallIndex() == 0) && 2175 "have call index for global lvalue"); 2176 2177 if (Base.is<DynamicAllocLValue>()) { 2178 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2179 << IsReferenceType << !Designator.Entries.empty(); 2180 NoteLValueLocation(Info, Base); 2181 return false; 2182 } 2183 2184 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2185 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2186 // Check if this is a thread-local variable. 2187 if (Var->getTLSKind()) 2188 // FIXME: Diagnostic! 2189 return false; 2190 2191 // A dllimport variable never acts like a constant. 2192 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2193 // FIXME: Diagnostic! 2194 return false; 2195 } 2196 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2197 // __declspec(dllimport) must be handled very carefully: 2198 // We must never initialize an expression with the thunk in C++. 2199 // Doing otherwise would allow the same id-expression to yield 2200 // different addresses for the same function in different translation 2201 // units. However, this means that we must dynamically initialize the 2202 // expression with the contents of the import address table at runtime. 2203 // 2204 // The C language has no notion of ODR; furthermore, it has no notion of 2205 // dynamic initialization. This means that we are permitted to 2206 // perform initialization with the address of the thunk. 2207 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2208 FD->hasAttr<DLLImportAttr>()) 2209 // FIXME: Diagnostic! 2210 return false; 2211 } 2212 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2213 Base.dyn_cast<const Expr *>())) { 2214 if (CheckedTemps.insert(MTE).second) { 2215 QualType TempType = getType(Base); 2216 if (TempType.isDestructedType()) { 2217 Info.FFDiag(MTE->getExprLoc(), 2218 diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2219 << TempType; 2220 return false; 2221 } 2222 2223 APValue *V = MTE->getOrCreateValue(false); 2224 assert(V && "evasluation result refers to uninitialised temporary"); 2225 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2226 Info, MTE->getExprLoc(), TempType, *V, 2227 Usage, SourceLocation(), CheckedTemps)) 2228 return false; 2229 } 2230 } 2231 2232 // Allow address constant expressions to be past-the-end pointers. This is 2233 // an extension: the standard requires them to point to an object. 2234 if (!IsReferenceType) 2235 return true; 2236 2237 // A reference constant expression must refer to an object. 2238 if (!Base) { 2239 // FIXME: diagnostic 2240 Info.CCEDiag(Loc); 2241 return true; 2242 } 2243 2244 // Does this refer one past the end of some object? 2245 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2246 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2247 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2248 << !Designator.Entries.empty() << !!VD << VD; 2249 NoteLValueLocation(Info, Base); 2250 } 2251 2252 return true; 2253 } 2254 2255 /// Member pointers are constant expressions unless they point to a 2256 /// non-virtual dllimport member function. 2257 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2258 SourceLocation Loc, 2259 QualType Type, 2260 const APValue &Value, 2261 Expr::ConstExprUsage Usage) { 2262 const ValueDecl *Member = Value.getMemberPointerDecl(); 2263 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2264 if (!FD) 2265 return true; 2266 if (FD->isConsteval()) { 2267 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2268 Info.Note(FD->getLocation(), diag::note_declared_at); 2269 return false; 2270 } 2271 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2272 !FD->hasAttr<DLLImportAttr>(); 2273 } 2274 2275 /// Check that this core constant expression is of literal type, and if not, 2276 /// produce an appropriate diagnostic. 2277 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2278 const LValue *This = nullptr) { 2279 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2280 return true; 2281 2282 // C++1y: A constant initializer for an object o [...] may also invoke 2283 // constexpr constructors for o and its subobjects even if those objects 2284 // are of non-literal class types. 2285 // 2286 // C++11 missed this detail for aggregates, so classes like this: 2287 // struct foo_t { union { int i; volatile int j; } u; }; 2288 // are not (obviously) initializable like so: 2289 // __attribute__((__require_constant_initialization__)) 2290 // static const foo_t x = {{0}}; 2291 // because "i" is a subobject with non-literal initialization (due to the 2292 // volatile member of the union). See: 2293 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2294 // Therefore, we use the C++1y behavior. 2295 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2296 return true; 2297 2298 // Prvalue constant expressions must be of literal types. 2299 if (Info.getLangOpts().CPlusPlus11) 2300 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2301 << E->getType(); 2302 else 2303 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2304 return false; 2305 } 2306 2307 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2308 EvalInfo &Info, SourceLocation DiagLoc, 2309 QualType Type, const APValue &Value, 2310 Expr::ConstExprUsage Usage, 2311 SourceLocation SubobjectLoc, 2312 CheckedTemporaries &CheckedTemps) { 2313 if (!Value.hasValue()) { 2314 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2315 << true << Type; 2316 if (SubobjectLoc.isValid()) 2317 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2318 return false; 2319 } 2320 2321 // We allow _Atomic(T) to be initialized from anything that T can be 2322 // initialized from. 2323 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2324 Type = AT->getValueType(); 2325 2326 // Core issue 1454: For a literal constant expression of array or class type, 2327 // each subobject of its value shall have been initialized by a constant 2328 // expression. 2329 if (Value.isArray()) { 2330 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2331 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2332 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2333 Value.getArrayInitializedElt(I), Usage, 2334 SubobjectLoc, CheckedTemps)) 2335 return false; 2336 } 2337 if (!Value.hasArrayFiller()) 2338 return true; 2339 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2340 Value.getArrayFiller(), Usage, SubobjectLoc, 2341 CheckedTemps); 2342 } 2343 if (Value.isUnion() && Value.getUnionField()) { 2344 return CheckEvaluationResult( 2345 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2346 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2347 CheckedTemps); 2348 } 2349 if (Value.isStruct()) { 2350 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2351 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2352 unsigned BaseIndex = 0; 2353 for (const CXXBaseSpecifier &BS : CD->bases()) { 2354 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2355 Value.getStructBase(BaseIndex), Usage, 2356 BS.getBeginLoc(), CheckedTemps)) 2357 return false; 2358 ++BaseIndex; 2359 } 2360 } 2361 for (const auto *I : RD->fields()) { 2362 if (I->isUnnamedBitfield()) 2363 continue; 2364 2365 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2366 Value.getStructField(I->getFieldIndex()), 2367 Usage, I->getLocation(), CheckedTemps)) 2368 return false; 2369 } 2370 } 2371 2372 if (Value.isLValue() && 2373 CERK == CheckEvaluationResultKind::ConstantExpression) { 2374 LValue LVal; 2375 LVal.setFrom(Info.Ctx, Value); 2376 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2377 CheckedTemps); 2378 } 2379 2380 if (Value.isMemberPointer() && 2381 CERK == CheckEvaluationResultKind::ConstantExpression) 2382 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2383 2384 // Everything else is fine. 2385 return true; 2386 } 2387 2388 /// Check that this core constant expression value is a valid value for a 2389 /// constant expression. If not, report an appropriate diagnostic. Does not 2390 /// check that the expression is of literal type. 2391 static bool 2392 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2393 const APValue &Value, 2394 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2395 // Nothing to check for a constant expression of type 'cv void'. 2396 if (Type->isVoidType()) 2397 return true; 2398 2399 CheckedTemporaries CheckedTemps; 2400 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2401 Info, DiagLoc, Type, Value, Usage, 2402 SourceLocation(), CheckedTemps); 2403 } 2404 2405 /// Check that this evaluated value is fully-initialized and can be loaded by 2406 /// an lvalue-to-rvalue conversion. 2407 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2408 QualType Type, const APValue &Value) { 2409 CheckedTemporaries CheckedTemps; 2410 return CheckEvaluationResult( 2411 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2412 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2413 } 2414 2415 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2416 /// "the allocated storage is deallocated within the evaluation". 2417 static bool CheckMemoryLeaks(EvalInfo &Info) { 2418 if (!Info.HeapAllocs.empty()) { 2419 // We can still fold to a constant despite a compile-time memory leak, 2420 // so long as the heap allocation isn't referenced in the result (we check 2421 // that in CheckConstantExpression). 2422 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2423 diag::note_constexpr_memory_leak) 2424 << unsigned(Info.HeapAllocs.size() - 1); 2425 } 2426 return true; 2427 } 2428 2429 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2430 // A null base expression indicates a null pointer. These are always 2431 // evaluatable, and they are false unless the offset is zero. 2432 if (!Value.getLValueBase()) { 2433 Result = !Value.getLValueOffset().isZero(); 2434 return true; 2435 } 2436 2437 // We have a non-null base. These are generally known to be true, but if it's 2438 // a weak declaration it can be null at runtime. 2439 Result = true; 2440 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2441 return !Decl || !Decl->isWeak(); 2442 } 2443 2444 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2445 switch (Val.getKind()) { 2446 case APValue::None: 2447 case APValue::Indeterminate: 2448 return false; 2449 case APValue::Int: 2450 Result = Val.getInt().getBoolValue(); 2451 return true; 2452 case APValue::FixedPoint: 2453 Result = Val.getFixedPoint().getBoolValue(); 2454 return true; 2455 case APValue::Float: 2456 Result = !Val.getFloat().isZero(); 2457 return true; 2458 case APValue::ComplexInt: 2459 Result = Val.getComplexIntReal().getBoolValue() || 2460 Val.getComplexIntImag().getBoolValue(); 2461 return true; 2462 case APValue::ComplexFloat: 2463 Result = !Val.getComplexFloatReal().isZero() || 2464 !Val.getComplexFloatImag().isZero(); 2465 return true; 2466 case APValue::LValue: 2467 return EvalPointerValueAsBool(Val, Result); 2468 case APValue::MemberPointer: 2469 Result = Val.getMemberPointerDecl(); 2470 return true; 2471 case APValue::Vector: 2472 case APValue::Array: 2473 case APValue::Struct: 2474 case APValue::Union: 2475 case APValue::AddrLabelDiff: 2476 return false; 2477 } 2478 2479 llvm_unreachable("unknown APValue kind"); 2480 } 2481 2482 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2483 EvalInfo &Info) { 2484 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2485 APValue Val; 2486 if (!Evaluate(Val, Info, E)) 2487 return false; 2488 return HandleConversionToBool(Val, Result); 2489 } 2490 2491 template<typename T> 2492 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2493 const T &SrcValue, QualType DestType) { 2494 Info.CCEDiag(E, diag::note_constexpr_overflow) 2495 << SrcValue << DestType; 2496 return Info.noteUndefinedBehavior(); 2497 } 2498 2499 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2500 QualType SrcType, const APFloat &Value, 2501 QualType DestType, APSInt &Result) { 2502 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2503 // Determine whether we are converting to unsigned or signed. 2504 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2505 2506 Result = APSInt(DestWidth, !DestSigned); 2507 bool ignored; 2508 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2509 & APFloat::opInvalidOp) 2510 return HandleOverflow(Info, E, Value, DestType); 2511 return true; 2512 } 2513 2514 /// Get rounding mode used for evaluation of the specified expression. 2515 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2516 /// dynamic. 2517 /// If rounding mode is unknown at compile time, still try to evaluate the 2518 /// expression. If the result is exact, it does not depend on rounding mode. 2519 /// So return "tonearest" mode instead of "dynamic". 2520 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2521 bool &DynamicRM) { 2522 llvm::RoundingMode RM = 2523 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2524 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2525 if (DynamicRM) 2526 RM = llvm::RoundingMode::NearestTiesToEven; 2527 return RM; 2528 } 2529 2530 /// Check if the given evaluation result is allowed for constant evaluation. 2531 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2532 APFloat::opStatus St) { 2533 // In a constant context, assume that any dynamic rounding mode or FP 2534 // exception state matches the default floating-point environment. 2535 if (Info.InConstantContext) 2536 return true; 2537 2538 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2539 if ((St & APFloat::opInexact) && 2540 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2541 // Inexact result means that it depends on rounding mode. If the requested 2542 // mode is dynamic, the evaluation cannot be made in compile time. 2543 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2544 return false; 2545 } 2546 2547 if ((St & APFloat::opStatus::opInvalidOp) && 2548 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2549 // There is no usefully definable result. 2550 Info.FFDiag(E); 2551 return false; 2552 } 2553 2554 // FIXME: if: 2555 // - evaluation triggered other FP exception, and 2556 // - exception mode is not "ignore", and 2557 // - the expression being evaluated is not a part of global variable 2558 // initializer, 2559 // the evaluation probably need to be rejected. 2560 return true; 2561 } 2562 2563 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2564 QualType SrcType, QualType DestType, 2565 APFloat &Result) { 2566 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2567 bool DynamicRM; 2568 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2569 APFloat::opStatus St; 2570 APFloat Value = Result; 2571 bool ignored; 2572 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2573 return checkFloatingPointResult(Info, E, St); 2574 } 2575 2576 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2577 QualType DestType, QualType SrcType, 2578 const APSInt &Value) { 2579 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2580 // Figure out if this is a truncate, extend or noop cast. 2581 // If the input is signed, do a sign extend, noop, or truncate. 2582 APSInt Result = Value.extOrTrunc(DestWidth); 2583 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2584 if (DestType->isBooleanType()) 2585 Result = Value.getBoolValue(); 2586 return Result; 2587 } 2588 2589 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2590 QualType SrcType, const APSInt &Value, 2591 QualType DestType, APFloat &Result) { 2592 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2593 Result.convertFromAPInt(Value, Value.isSigned(), 2594 APFloat::rmNearestTiesToEven); 2595 return true; 2596 } 2597 2598 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2599 APValue &Value, const FieldDecl *FD) { 2600 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2601 2602 if (!Value.isInt()) { 2603 // Trying to store a pointer-cast-to-integer into a bitfield. 2604 // FIXME: In this case, we should provide the diagnostic for casting 2605 // a pointer to an integer. 2606 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2607 Info.FFDiag(E); 2608 return false; 2609 } 2610 2611 APSInt &Int = Value.getInt(); 2612 unsigned OldBitWidth = Int.getBitWidth(); 2613 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2614 if (NewBitWidth < OldBitWidth) 2615 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2616 return true; 2617 } 2618 2619 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2620 llvm::APInt &Res) { 2621 APValue SVal; 2622 if (!Evaluate(SVal, Info, E)) 2623 return false; 2624 if (SVal.isInt()) { 2625 Res = SVal.getInt(); 2626 return true; 2627 } 2628 if (SVal.isFloat()) { 2629 Res = SVal.getFloat().bitcastToAPInt(); 2630 return true; 2631 } 2632 if (SVal.isVector()) { 2633 QualType VecTy = E->getType(); 2634 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2635 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2636 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2637 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2638 Res = llvm::APInt::getNullValue(VecSize); 2639 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2640 APValue &Elt = SVal.getVectorElt(i); 2641 llvm::APInt EltAsInt; 2642 if (Elt.isInt()) { 2643 EltAsInt = Elt.getInt(); 2644 } else if (Elt.isFloat()) { 2645 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2646 } else { 2647 // Don't try to handle vectors of anything other than int or float 2648 // (not sure if it's possible to hit this case). 2649 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2650 return false; 2651 } 2652 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2653 if (BigEndian) 2654 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2655 else 2656 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2657 } 2658 return true; 2659 } 2660 // Give up if the input isn't an int, float, or vector. For example, we 2661 // reject "(v4i16)(intptr_t)&a". 2662 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2663 return false; 2664 } 2665 2666 /// Perform the given integer operation, which is known to need at most BitWidth 2667 /// bits, and check for overflow in the original type (if that type was not an 2668 /// unsigned type). 2669 template<typename Operation> 2670 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2671 const APSInt &LHS, const APSInt &RHS, 2672 unsigned BitWidth, Operation Op, 2673 APSInt &Result) { 2674 if (LHS.isUnsigned()) { 2675 Result = Op(LHS, RHS); 2676 return true; 2677 } 2678 2679 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2680 Result = Value.trunc(LHS.getBitWidth()); 2681 if (Result.extend(BitWidth) != Value) { 2682 if (Info.checkingForUndefinedBehavior()) 2683 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2684 diag::warn_integer_constant_overflow) 2685 << Result.toString(10) << E->getType(); 2686 else 2687 return HandleOverflow(Info, E, Value, E->getType()); 2688 } 2689 return true; 2690 } 2691 2692 /// Perform the given binary integer operation. 2693 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2694 BinaryOperatorKind Opcode, APSInt RHS, 2695 APSInt &Result) { 2696 switch (Opcode) { 2697 default: 2698 Info.FFDiag(E); 2699 return false; 2700 case BO_Mul: 2701 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2702 std::multiplies<APSInt>(), Result); 2703 case BO_Add: 2704 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2705 std::plus<APSInt>(), Result); 2706 case BO_Sub: 2707 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2708 std::minus<APSInt>(), Result); 2709 case BO_And: Result = LHS & RHS; return true; 2710 case BO_Xor: Result = LHS ^ RHS; return true; 2711 case BO_Or: Result = LHS | RHS; return true; 2712 case BO_Div: 2713 case BO_Rem: 2714 if (RHS == 0) { 2715 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2716 return false; 2717 } 2718 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2719 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2720 // this operation and gives the two's complement result. 2721 if (RHS.isNegative() && RHS.isAllOnesValue() && 2722 LHS.isSigned() && LHS.isMinSignedValue()) 2723 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2724 E->getType()); 2725 return true; 2726 case BO_Shl: { 2727 if (Info.getLangOpts().OpenCL) 2728 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2729 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2730 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2731 RHS.isUnsigned()); 2732 else if (RHS.isSigned() && RHS.isNegative()) { 2733 // During constant-folding, a negative shift is an opposite shift. Such 2734 // a shift is not a constant expression. 2735 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2736 RHS = -RHS; 2737 goto shift_right; 2738 } 2739 shift_left: 2740 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2741 // the shifted type. 2742 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2743 if (SA != RHS) { 2744 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2745 << RHS << E->getType() << LHS.getBitWidth(); 2746 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2747 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2748 // operand, and must not overflow the corresponding unsigned type. 2749 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2750 // E1 x 2^E2 module 2^N. 2751 if (LHS.isNegative()) 2752 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2753 else if (LHS.countLeadingZeros() < SA) 2754 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2755 } 2756 Result = LHS << SA; 2757 return true; 2758 } 2759 case BO_Shr: { 2760 if (Info.getLangOpts().OpenCL) 2761 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2762 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2763 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2764 RHS.isUnsigned()); 2765 else if (RHS.isSigned() && RHS.isNegative()) { 2766 // During constant-folding, a negative shift is an opposite shift. Such a 2767 // shift is not a constant expression. 2768 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2769 RHS = -RHS; 2770 goto shift_left; 2771 } 2772 shift_right: 2773 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2774 // shifted type. 2775 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2776 if (SA != RHS) 2777 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2778 << RHS << E->getType() << LHS.getBitWidth(); 2779 Result = LHS >> SA; 2780 return true; 2781 } 2782 2783 case BO_LT: Result = LHS < RHS; return true; 2784 case BO_GT: Result = LHS > RHS; return true; 2785 case BO_LE: Result = LHS <= RHS; return true; 2786 case BO_GE: Result = LHS >= RHS; return true; 2787 case BO_EQ: Result = LHS == RHS; return true; 2788 case BO_NE: Result = LHS != RHS; return true; 2789 case BO_Cmp: 2790 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2791 } 2792 } 2793 2794 /// Perform the given binary floating-point operation, in-place, on LHS. 2795 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2796 APFloat &LHS, BinaryOperatorKind Opcode, 2797 const APFloat &RHS) { 2798 bool DynamicRM; 2799 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2800 APFloat::opStatus St; 2801 switch (Opcode) { 2802 default: 2803 Info.FFDiag(E); 2804 return false; 2805 case BO_Mul: 2806 St = LHS.multiply(RHS, RM); 2807 break; 2808 case BO_Add: 2809 St = LHS.add(RHS, RM); 2810 break; 2811 case BO_Sub: 2812 St = LHS.subtract(RHS, RM); 2813 break; 2814 case BO_Div: 2815 // [expr.mul]p4: 2816 // If the second operand of / or % is zero the behavior is undefined. 2817 if (RHS.isZero()) 2818 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2819 St = LHS.divide(RHS, RM); 2820 break; 2821 } 2822 2823 // [expr.pre]p4: 2824 // If during the evaluation of an expression, the result is not 2825 // mathematically defined [...], the behavior is undefined. 2826 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2827 if (LHS.isNaN()) { 2828 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2829 return Info.noteUndefinedBehavior(); 2830 } 2831 2832 return checkFloatingPointResult(Info, E, St); 2833 } 2834 2835 static bool handleLogicalOpForVector(const APInt &LHSValue, 2836 BinaryOperatorKind Opcode, 2837 const APInt &RHSValue, APInt &Result) { 2838 bool LHS = (LHSValue != 0); 2839 bool RHS = (RHSValue != 0); 2840 2841 if (Opcode == BO_LAnd) 2842 Result = LHS && RHS; 2843 else 2844 Result = LHS || RHS; 2845 return true; 2846 } 2847 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2848 BinaryOperatorKind Opcode, 2849 const APFloat &RHSValue, APInt &Result) { 2850 bool LHS = !LHSValue.isZero(); 2851 bool RHS = !RHSValue.isZero(); 2852 2853 if (Opcode == BO_LAnd) 2854 Result = LHS && RHS; 2855 else 2856 Result = LHS || RHS; 2857 return true; 2858 } 2859 2860 static bool handleLogicalOpForVector(const APValue &LHSValue, 2861 BinaryOperatorKind Opcode, 2862 const APValue &RHSValue, APInt &Result) { 2863 // The result is always an int type, however operands match the first. 2864 if (LHSValue.getKind() == APValue::Int) 2865 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2866 RHSValue.getInt(), Result); 2867 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2868 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2869 RHSValue.getFloat(), Result); 2870 } 2871 2872 template <typename APTy> 2873 static bool 2874 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2875 const APTy &RHSValue, APInt &Result) { 2876 switch (Opcode) { 2877 default: 2878 llvm_unreachable("unsupported binary operator"); 2879 case BO_EQ: 2880 Result = (LHSValue == RHSValue); 2881 break; 2882 case BO_NE: 2883 Result = (LHSValue != RHSValue); 2884 break; 2885 case BO_LT: 2886 Result = (LHSValue < RHSValue); 2887 break; 2888 case BO_GT: 2889 Result = (LHSValue > RHSValue); 2890 break; 2891 case BO_LE: 2892 Result = (LHSValue <= RHSValue); 2893 break; 2894 case BO_GE: 2895 Result = (LHSValue >= RHSValue); 2896 break; 2897 } 2898 2899 return true; 2900 } 2901 2902 static bool handleCompareOpForVector(const APValue &LHSValue, 2903 BinaryOperatorKind Opcode, 2904 const APValue &RHSValue, APInt &Result) { 2905 // The result is always an int type, however operands match the first. 2906 if (LHSValue.getKind() == APValue::Int) 2907 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2908 RHSValue.getInt(), Result); 2909 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2910 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2911 RHSValue.getFloat(), Result); 2912 } 2913 2914 // Perform binary operations for vector types, in place on the LHS. 2915 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2916 BinaryOperatorKind Opcode, 2917 APValue &LHSValue, 2918 const APValue &RHSValue) { 2919 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2920 "Operation not supported on vector types"); 2921 2922 const auto *VT = E->getType()->castAs<VectorType>(); 2923 unsigned NumElements = VT->getNumElements(); 2924 QualType EltTy = VT->getElementType(); 2925 2926 // In the cases (typically C as I've observed) where we aren't evaluating 2927 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2928 // just give up. 2929 if (!LHSValue.isVector()) { 2930 assert(LHSValue.isLValue() && 2931 "A vector result that isn't a vector OR uncalculated LValue"); 2932 Info.FFDiag(E); 2933 return false; 2934 } 2935 2936 assert(LHSValue.getVectorLength() == NumElements && 2937 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2938 2939 SmallVector<APValue, 4> ResultElements; 2940 2941 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2942 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2943 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2944 2945 if (EltTy->isIntegerType()) { 2946 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2947 EltTy->isUnsignedIntegerType()}; 2948 bool Success = true; 2949 2950 if (BinaryOperator::isLogicalOp(Opcode)) 2951 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2952 else if (BinaryOperator::isComparisonOp(Opcode)) 2953 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2954 else 2955 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2956 RHSElt.getInt(), EltResult); 2957 2958 if (!Success) { 2959 Info.FFDiag(E); 2960 return false; 2961 } 2962 ResultElements.emplace_back(EltResult); 2963 2964 } else if (EltTy->isFloatingType()) { 2965 assert(LHSElt.getKind() == APValue::Float && 2966 RHSElt.getKind() == APValue::Float && 2967 "Mismatched LHS/RHS/Result Type"); 2968 APFloat LHSFloat = LHSElt.getFloat(); 2969 2970 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2971 RHSElt.getFloat())) { 2972 Info.FFDiag(E); 2973 return false; 2974 } 2975 2976 ResultElements.emplace_back(LHSFloat); 2977 } 2978 } 2979 2980 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2981 return true; 2982 } 2983 2984 /// Cast an lvalue referring to a base subobject to a derived class, by 2985 /// truncating the lvalue's path to the given length. 2986 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2987 const RecordDecl *TruncatedType, 2988 unsigned TruncatedElements) { 2989 SubobjectDesignator &D = Result.Designator; 2990 2991 // Check we actually point to a derived class object. 2992 if (TruncatedElements == D.Entries.size()) 2993 return true; 2994 assert(TruncatedElements >= D.MostDerivedPathLength && 2995 "not casting to a derived class"); 2996 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2997 return false; 2998 2999 // Truncate the path to the subobject, and remove any derived-to-base offsets. 3000 const RecordDecl *RD = TruncatedType; 3001 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3002 if (RD->isInvalidDecl()) return false; 3003 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3004 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3005 if (isVirtualBaseClass(D.Entries[I])) 3006 Result.Offset -= Layout.getVBaseClassOffset(Base); 3007 else 3008 Result.Offset -= Layout.getBaseClassOffset(Base); 3009 RD = Base; 3010 } 3011 D.Entries.resize(TruncatedElements); 3012 return true; 3013 } 3014 3015 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3016 const CXXRecordDecl *Derived, 3017 const CXXRecordDecl *Base, 3018 const ASTRecordLayout *RL = nullptr) { 3019 if (!RL) { 3020 if (Derived->isInvalidDecl()) return false; 3021 RL = &Info.Ctx.getASTRecordLayout(Derived); 3022 } 3023 3024 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3025 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3026 return true; 3027 } 3028 3029 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3030 const CXXRecordDecl *DerivedDecl, 3031 const CXXBaseSpecifier *Base) { 3032 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3033 3034 if (!Base->isVirtual()) 3035 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3036 3037 SubobjectDesignator &D = Obj.Designator; 3038 if (D.Invalid) 3039 return false; 3040 3041 // Extract most-derived object and corresponding type. 3042 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3043 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3044 return false; 3045 3046 // Find the virtual base class. 3047 if (DerivedDecl->isInvalidDecl()) return false; 3048 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3049 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3050 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3051 return true; 3052 } 3053 3054 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3055 QualType Type, LValue &Result) { 3056 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3057 PathE = E->path_end(); 3058 PathI != PathE; ++PathI) { 3059 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3060 *PathI)) 3061 return false; 3062 Type = (*PathI)->getType(); 3063 } 3064 return true; 3065 } 3066 3067 /// Cast an lvalue referring to a derived class to a known base subobject. 3068 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3069 const CXXRecordDecl *DerivedRD, 3070 const CXXRecordDecl *BaseRD) { 3071 CXXBasePaths Paths(/*FindAmbiguities=*/false, 3072 /*RecordPaths=*/true, /*DetectVirtual=*/false); 3073 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3074 llvm_unreachable("Class must be derived from the passed in base class!"); 3075 3076 for (CXXBasePathElement &Elem : Paths.front()) 3077 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3078 return false; 3079 return true; 3080 } 3081 3082 /// Update LVal to refer to the given field, which must be a member of the type 3083 /// currently described by LVal. 3084 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3085 const FieldDecl *FD, 3086 const ASTRecordLayout *RL = nullptr) { 3087 if (!RL) { 3088 if (FD->getParent()->isInvalidDecl()) return false; 3089 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3090 } 3091 3092 unsigned I = FD->getFieldIndex(); 3093 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3094 LVal.addDecl(Info, E, FD); 3095 return true; 3096 } 3097 3098 /// Update LVal to refer to the given indirect field. 3099 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3100 LValue &LVal, 3101 const IndirectFieldDecl *IFD) { 3102 for (const auto *C : IFD->chain()) 3103 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3104 return false; 3105 return true; 3106 } 3107 3108 /// Get the size of the given type in char units. 3109 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3110 QualType Type, CharUnits &Size) { 3111 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3112 // extension. 3113 if (Type->isVoidType() || Type->isFunctionType()) { 3114 Size = CharUnits::One(); 3115 return true; 3116 } 3117 3118 if (Type->isDependentType()) { 3119 Info.FFDiag(Loc); 3120 return false; 3121 } 3122 3123 if (!Type->isConstantSizeType()) { 3124 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3125 // FIXME: Better diagnostic. 3126 Info.FFDiag(Loc); 3127 return false; 3128 } 3129 3130 Size = Info.Ctx.getTypeSizeInChars(Type); 3131 return true; 3132 } 3133 3134 /// Update a pointer value to model pointer arithmetic. 3135 /// \param Info - Information about the ongoing evaluation. 3136 /// \param E - The expression being evaluated, for diagnostic purposes. 3137 /// \param LVal - The pointer value to be updated. 3138 /// \param EltTy - The pointee type represented by LVal. 3139 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3140 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3141 LValue &LVal, QualType EltTy, 3142 APSInt Adjustment) { 3143 CharUnits SizeOfPointee; 3144 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3145 return false; 3146 3147 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3148 return true; 3149 } 3150 3151 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3152 LValue &LVal, QualType EltTy, 3153 int64_t Adjustment) { 3154 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3155 APSInt::get(Adjustment)); 3156 } 3157 3158 /// Update an lvalue to refer to a component of a complex number. 3159 /// \param Info - Information about the ongoing evaluation. 3160 /// \param LVal - The lvalue to be updated. 3161 /// \param EltTy - The complex number's component type. 3162 /// \param Imag - False for the real component, true for the imaginary. 3163 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3164 LValue &LVal, QualType EltTy, 3165 bool Imag) { 3166 if (Imag) { 3167 CharUnits SizeOfComponent; 3168 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3169 return false; 3170 LVal.Offset += SizeOfComponent; 3171 } 3172 LVal.addComplex(Info, E, EltTy, Imag); 3173 return true; 3174 } 3175 3176 /// Try to evaluate the initializer for a variable declaration. 3177 /// 3178 /// \param Info Information about the ongoing evaluation. 3179 /// \param E An expression to be used when printing diagnostics. 3180 /// \param VD The variable whose initializer should be obtained. 3181 /// \param Version The version of the variable within the frame. 3182 /// \param Frame The frame in which the variable was created. Must be null 3183 /// if this variable is not local to the evaluation. 3184 /// \param Result Filled in with a pointer to the value of the variable. 3185 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3186 const VarDecl *VD, CallStackFrame *Frame, 3187 unsigned Version, APValue *&Result) { 3188 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3189 3190 // If this is a local variable, dig out its value. 3191 if (Frame) { 3192 Result = Frame->getTemporary(VD, Version); 3193 if (Result) 3194 return true; 3195 3196 if (!isa<ParmVarDecl>(VD)) { 3197 // Assume variables referenced within a lambda's call operator that were 3198 // not declared within the call operator are captures and during checking 3199 // of a potential constant expression, assume they are unknown constant 3200 // expressions. 3201 assert(isLambdaCallOperator(Frame->Callee) && 3202 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3203 "missing value for local variable"); 3204 if (Info.checkingPotentialConstantExpression()) 3205 return false; 3206 // FIXME: This diagnostic is bogus; we do support captures. Is this code 3207 // still reachable at all? 3208 Info.FFDiag(E->getBeginLoc(), 3209 diag::note_unimplemented_constexpr_lambda_feature_ast) 3210 << "captures not currently allowed"; 3211 return false; 3212 } 3213 } 3214 3215 if (isa<ParmVarDecl>(VD)) { 3216 // Assume parameters of a potential constant expression are usable in 3217 // constant expressions. 3218 if (!Info.checkingPotentialConstantExpression() || 3219 !Info.CurrentCall->Callee || 3220 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3221 if (Info.getLangOpts().CPlusPlus11) { 3222 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3223 << VD; 3224 NoteLValueLocation(Info, Base); 3225 } else { 3226 Info.FFDiag(E); 3227 } 3228 } 3229 return false; 3230 } 3231 3232 // Dig out the initializer, and use the declaration which it's attached to. 3233 // FIXME: We should eventually check whether the variable has a reachable 3234 // initializing declaration. 3235 const Expr *Init = VD->getAnyInitializer(VD); 3236 if (!Init) { 3237 // Don't diagnose during potential constant expression checking; an 3238 // initializer might be added later. 3239 if (!Info.checkingPotentialConstantExpression()) { 3240 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3241 << VD; 3242 NoteLValueLocation(Info, Base); 3243 } 3244 return false; 3245 } 3246 3247 if (Init->isValueDependent()) { 3248 // The DeclRefExpr is not value-dependent, but the variable it refers to 3249 // has a value-dependent initializer. This should only happen in 3250 // constant-folding cases, where the variable is not actually of a suitable 3251 // type for use in a constant expression (otherwise the DeclRefExpr would 3252 // have been value-dependent too), so diagnose that. 3253 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3254 if (!Info.checkingPotentialConstantExpression()) { 3255 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3256 ? diag::note_constexpr_ltor_non_constexpr 3257 : diag::note_constexpr_ltor_non_integral, 1) 3258 << VD << VD->getType(); 3259 NoteLValueLocation(Info, Base); 3260 } 3261 return false; 3262 } 3263 3264 // If we're currently evaluating the initializer of this declaration, use that 3265 // in-flight value. 3266 if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(), 3267 VD)) { 3268 Result = Info.EvaluatingDeclValue; 3269 return true; 3270 } 3271 3272 // Check that we can fold the initializer. In C++, we will have already done 3273 // this in the cases where it matters for conformance. 3274 if (!VD->evaluateValue()) { 3275 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3276 NoteLValueLocation(Info, Base); 3277 return false; 3278 } 3279 3280 // Check that the variable is actually usable in constant expressions. For a 3281 // const integral variable or a reference, we might have a non-constant 3282 // initializer that we can nonetheless evaluate the initializer for. Such 3283 // variables are not usable in constant expressions. In C++98, the 3284 // initializer also syntactically needs to be an ICE. 3285 // 3286 // FIXME: We don't diagnose cases that aren't potentially usable in constant 3287 // expressions here; doing so would regress diagnostics for things like 3288 // reading from a volatile constexpr variable. 3289 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3290 VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3291 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3292 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3293 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3294 NoteLValueLocation(Info, Base); 3295 } 3296 3297 // Never use the initializer of a weak variable, not even for constant 3298 // folding. We can't be sure that this is the definition that will be used. 3299 if (VD->isWeak()) { 3300 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3301 NoteLValueLocation(Info, Base); 3302 return false; 3303 } 3304 3305 Result = VD->getEvaluatedValue(); 3306 return true; 3307 } 3308 3309 /// Get the base index of the given base class within an APValue representing 3310 /// the given derived class. 3311 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3312 const CXXRecordDecl *Base) { 3313 Base = Base->getCanonicalDecl(); 3314 unsigned Index = 0; 3315 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3316 E = Derived->bases_end(); I != E; ++I, ++Index) { 3317 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3318 return Index; 3319 } 3320 3321 llvm_unreachable("base class missing from derived class's bases list"); 3322 } 3323 3324 /// Extract the value of a character from a string literal. 3325 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3326 uint64_t Index) { 3327 assert(!isa<SourceLocExpr>(Lit) && 3328 "SourceLocExpr should have already been converted to a StringLiteral"); 3329 3330 // FIXME: Support MakeStringConstant 3331 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3332 std::string Str; 3333 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3334 assert(Index <= Str.size() && "Index too large"); 3335 return APSInt::getUnsigned(Str.c_str()[Index]); 3336 } 3337 3338 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3339 Lit = PE->getFunctionName(); 3340 const StringLiteral *S = cast<StringLiteral>(Lit); 3341 const ConstantArrayType *CAT = 3342 Info.Ctx.getAsConstantArrayType(S->getType()); 3343 assert(CAT && "string literal isn't an array"); 3344 QualType CharType = CAT->getElementType(); 3345 assert(CharType->isIntegerType() && "unexpected character type"); 3346 3347 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3348 CharType->isUnsignedIntegerType()); 3349 if (Index < S->getLength()) 3350 Value = S->getCodeUnit(Index); 3351 return Value; 3352 } 3353 3354 // Expand a string literal into an array of characters. 3355 // 3356 // FIXME: This is inefficient; we should probably introduce something similar 3357 // to the LLVM ConstantDataArray to make this cheaper. 3358 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3359 APValue &Result, 3360 QualType AllocType = QualType()) { 3361 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3362 AllocType.isNull() ? S->getType() : AllocType); 3363 assert(CAT && "string literal isn't an array"); 3364 QualType CharType = CAT->getElementType(); 3365 assert(CharType->isIntegerType() && "unexpected character type"); 3366 3367 unsigned Elts = CAT->getSize().getZExtValue(); 3368 Result = APValue(APValue::UninitArray(), 3369 std::min(S->getLength(), Elts), Elts); 3370 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3371 CharType->isUnsignedIntegerType()); 3372 if (Result.hasArrayFiller()) 3373 Result.getArrayFiller() = APValue(Value); 3374 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3375 Value = S->getCodeUnit(I); 3376 Result.getArrayInitializedElt(I) = APValue(Value); 3377 } 3378 } 3379 3380 // Expand an array so that it has more than Index filled elements. 3381 static void expandArray(APValue &Array, unsigned Index) { 3382 unsigned Size = Array.getArraySize(); 3383 assert(Index < Size); 3384 3385 // Always at least double the number of elements for which we store a value. 3386 unsigned OldElts = Array.getArrayInitializedElts(); 3387 unsigned NewElts = std::max(Index+1, OldElts * 2); 3388 NewElts = std::min(Size, std::max(NewElts, 8u)); 3389 3390 // Copy the data across. 3391 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3392 for (unsigned I = 0; I != OldElts; ++I) 3393 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3394 for (unsigned I = OldElts; I != NewElts; ++I) 3395 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3396 if (NewValue.hasArrayFiller()) 3397 NewValue.getArrayFiller() = Array.getArrayFiller(); 3398 Array.swap(NewValue); 3399 } 3400 3401 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3402 /// conversion. If it's of class type, we may assume that the copy operation 3403 /// is trivial. Note that this is never true for a union type with fields 3404 /// (because the copy always "reads" the active member) and always true for 3405 /// a non-class type. 3406 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3407 static bool isReadByLvalueToRvalueConversion(QualType T) { 3408 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3409 return !RD || isReadByLvalueToRvalueConversion(RD); 3410 } 3411 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3412 // FIXME: A trivial copy of a union copies the object representation, even if 3413 // the union is empty. 3414 if (RD->isUnion()) 3415 return !RD->field_empty(); 3416 if (RD->isEmpty()) 3417 return false; 3418 3419 for (auto *Field : RD->fields()) 3420 if (!Field->isUnnamedBitfield() && 3421 isReadByLvalueToRvalueConversion(Field->getType())) 3422 return true; 3423 3424 for (auto &BaseSpec : RD->bases()) 3425 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3426 return true; 3427 3428 return false; 3429 } 3430 3431 /// Diagnose an attempt to read from any unreadable field within the specified 3432 /// type, which might be a class type. 3433 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3434 QualType T) { 3435 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3436 if (!RD) 3437 return false; 3438 3439 if (!RD->hasMutableFields()) 3440 return false; 3441 3442 for (auto *Field : RD->fields()) { 3443 // If we're actually going to read this field in some way, then it can't 3444 // be mutable. If we're in a union, then assigning to a mutable field 3445 // (even an empty one) can change the active member, so that's not OK. 3446 // FIXME: Add core issue number for the union case. 3447 if (Field->isMutable() && 3448 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3449 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3450 Info.Note(Field->getLocation(), diag::note_declared_at); 3451 return true; 3452 } 3453 3454 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3455 return true; 3456 } 3457 3458 for (auto &BaseSpec : RD->bases()) 3459 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3460 return true; 3461 3462 // All mutable fields were empty, and thus not actually read. 3463 return false; 3464 } 3465 3466 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3467 APValue::LValueBase Base, 3468 bool MutableSubobject = false) { 3469 // A temporary we created. 3470 if (Base.getCallIndex()) 3471 return true; 3472 3473 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3474 if (!Evaluating) 3475 return false; 3476 3477 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3478 3479 switch (Info.IsEvaluatingDecl) { 3480 case EvalInfo::EvaluatingDeclKind::None: 3481 return false; 3482 3483 case EvalInfo::EvaluatingDeclKind::Ctor: 3484 // The variable whose initializer we're evaluating. 3485 if (BaseD) 3486 return declaresSameEntity(Evaluating, BaseD); 3487 3488 // A temporary lifetime-extended by the variable whose initializer we're 3489 // evaluating. 3490 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3491 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3492 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3493 return false; 3494 3495 case EvalInfo::EvaluatingDeclKind::Dtor: 3496 // C++2a [expr.const]p6: 3497 // [during constant destruction] the lifetime of a and its non-mutable 3498 // subobjects (but not its mutable subobjects) [are] considered to start 3499 // within e. 3500 // 3501 // FIXME: We can meaningfully extend this to cover non-const objects, but 3502 // we will need special handling: we should be able to access only 3503 // subobjects of such objects that are themselves declared const. 3504 if (!BaseD || 3505 !(BaseD->getType().isConstQualified() || 3506 BaseD->getType()->isReferenceType()) || 3507 MutableSubobject) 3508 return false; 3509 return declaresSameEntity(Evaluating, BaseD); 3510 } 3511 3512 llvm_unreachable("unknown evaluating decl kind"); 3513 } 3514 3515 namespace { 3516 /// A handle to a complete object (an object that is not a subobject of 3517 /// another object). 3518 struct CompleteObject { 3519 /// The identity of the object. 3520 APValue::LValueBase Base; 3521 /// The value of the complete object. 3522 APValue *Value; 3523 /// The type of the complete object. 3524 QualType Type; 3525 3526 CompleteObject() : Value(nullptr) {} 3527 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3528 : Base(Base), Value(Value), Type(Type) {} 3529 3530 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3531 // If this isn't a "real" access (eg, if it's just accessing the type 3532 // info), allow it. We assume the type doesn't change dynamically for 3533 // subobjects of constexpr objects (even though we'd hit UB here if it 3534 // did). FIXME: Is this right? 3535 if (!isAnyAccess(AK)) 3536 return true; 3537 3538 // In C++14 onwards, it is permitted to read a mutable member whose 3539 // lifetime began within the evaluation. 3540 // FIXME: Should we also allow this in C++11? 3541 if (!Info.getLangOpts().CPlusPlus14) 3542 return false; 3543 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3544 } 3545 3546 explicit operator bool() const { return !Type.isNull(); } 3547 }; 3548 } // end anonymous namespace 3549 3550 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3551 bool IsMutable = false) { 3552 // C++ [basic.type.qualifier]p1: 3553 // - A const object is an object of type const T or a non-mutable subobject 3554 // of a const object. 3555 if (ObjType.isConstQualified() && !IsMutable) 3556 SubobjType.addConst(); 3557 // - A volatile object is an object of type const T or a subobject of a 3558 // volatile object. 3559 if (ObjType.isVolatileQualified()) 3560 SubobjType.addVolatile(); 3561 return SubobjType; 3562 } 3563 3564 /// Find the designated sub-object of an rvalue. 3565 template<typename SubobjectHandler> 3566 typename SubobjectHandler::result_type 3567 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3568 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3569 if (Sub.Invalid) 3570 // A diagnostic will have already been produced. 3571 return handler.failed(); 3572 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3573 if (Info.getLangOpts().CPlusPlus11) 3574 Info.FFDiag(E, Sub.isOnePastTheEnd() 3575 ? diag::note_constexpr_access_past_end 3576 : diag::note_constexpr_access_unsized_array) 3577 << handler.AccessKind; 3578 else 3579 Info.FFDiag(E); 3580 return handler.failed(); 3581 } 3582 3583 APValue *O = Obj.Value; 3584 QualType ObjType = Obj.Type; 3585 const FieldDecl *LastField = nullptr; 3586 const FieldDecl *VolatileField = nullptr; 3587 3588 // Walk the designator's path to find the subobject. 3589 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3590 // Reading an indeterminate value is undefined, but assigning over one is OK. 3591 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3592 (O->isIndeterminate() && 3593 !isValidIndeterminateAccess(handler.AccessKind))) { 3594 if (!Info.checkingPotentialConstantExpression()) 3595 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3596 << handler.AccessKind << O->isIndeterminate(); 3597 return handler.failed(); 3598 } 3599 3600 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3601 // const and volatile semantics are not applied on an object under 3602 // {con,de}struction. 3603 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3604 ObjType->isRecordType() && 3605 Info.isEvaluatingCtorDtor( 3606 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3607 Sub.Entries.begin() + I)) != 3608 ConstructionPhase::None) { 3609 ObjType = Info.Ctx.getCanonicalType(ObjType); 3610 ObjType.removeLocalConst(); 3611 ObjType.removeLocalVolatile(); 3612 } 3613 3614 // If this is our last pass, check that the final object type is OK. 3615 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3616 // Accesses to volatile objects are prohibited. 3617 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3618 if (Info.getLangOpts().CPlusPlus) { 3619 int DiagKind; 3620 SourceLocation Loc; 3621 const NamedDecl *Decl = nullptr; 3622 if (VolatileField) { 3623 DiagKind = 2; 3624 Loc = VolatileField->getLocation(); 3625 Decl = VolatileField; 3626 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3627 DiagKind = 1; 3628 Loc = VD->getLocation(); 3629 Decl = VD; 3630 } else { 3631 DiagKind = 0; 3632 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3633 Loc = E->getExprLoc(); 3634 } 3635 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3636 << handler.AccessKind << DiagKind << Decl; 3637 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3638 } else { 3639 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3640 } 3641 return handler.failed(); 3642 } 3643 3644 // If we are reading an object of class type, there may still be more 3645 // things we need to check: if there are any mutable subobjects, we 3646 // cannot perform this read. (This only happens when performing a trivial 3647 // copy or assignment.) 3648 if (ObjType->isRecordType() && 3649 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3650 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3651 return handler.failed(); 3652 } 3653 3654 if (I == N) { 3655 if (!handler.found(*O, ObjType)) 3656 return false; 3657 3658 // If we modified a bit-field, truncate it to the right width. 3659 if (isModification(handler.AccessKind) && 3660 LastField && LastField->isBitField() && 3661 !truncateBitfieldValue(Info, E, *O, LastField)) 3662 return false; 3663 3664 return true; 3665 } 3666 3667 LastField = nullptr; 3668 if (ObjType->isArrayType()) { 3669 // Next subobject is an array element. 3670 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3671 assert(CAT && "vla in literal type?"); 3672 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3673 if (CAT->getSize().ule(Index)) { 3674 // Note, it should not be possible to form a pointer with a valid 3675 // designator which points more than one past the end of the array. 3676 if (Info.getLangOpts().CPlusPlus11) 3677 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3678 << handler.AccessKind; 3679 else 3680 Info.FFDiag(E); 3681 return handler.failed(); 3682 } 3683 3684 ObjType = CAT->getElementType(); 3685 3686 if (O->getArrayInitializedElts() > Index) 3687 O = &O->getArrayInitializedElt(Index); 3688 else if (!isRead(handler.AccessKind)) { 3689 expandArray(*O, Index); 3690 O = &O->getArrayInitializedElt(Index); 3691 } else 3692 O = &O->getArrayFiller(); 3693 } else if (ObjType->isAnyComplexType()) { 3694 // Next subobject is a complex number. 3695 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3696 if (Index > 1) { 3697 if (Info.getLangOpts().CPlusPlus11) 3698 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3699 << handler.AccessKind; 3700 else 3701 Info.FFDiag(E); 3702 return handler.failed(); 3703 } 3704 3705 ObjType = getSubobjectType( 3706 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3707 3708 assert(I == N - 1 && "extracting subobject of scalar?"); 3709 if (O->isComplexInt()) { 3710 return handler.found(Index ? O->getComplexIntImag() 3711 : O->getComplexIntReal(), ObjType); 3712 } else { 3713 assert(O->isComplexFloat()); 3714 return handler.found(Index ? O->getComplexFloatImag() 3715 : O->getComplexFloatReal(), ObjType); 3716 } 3717 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3718 if (Field->isMutable() && 3719 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3720 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3721 << handler.AccessKind << Field; 3722 Info.Note(Field->getLocation(), diag::note_declared_at); 3723 return handler.failed(); 3724 } 3725 3726 // Next subobject is a class, struct or union field. 3727 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3728 if (RD->isUnion()) { 3729 const FieldDecl *UnionField = O->getUnionField(); 3730 if (!UnionField || 3731 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3732 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3733 // Placement new onto an inactive union member makes it active. 3734 O->setUnion(Field, APValue()); 3735 } else { 3736 // FIXME: If O->getUnionValue() is absent, report that there's no 3737 // active union member rather than reporting the prior active union 3738 // member. We'll need to fix nullptr_t to not use APValue() as its 3739 // representation first. 3740 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3741 << handler.AccessKind << Field << !UnionField << UnionField; 3742 return handler.failed(); 3743 } 3744 } 3745 O = &O->getUnionValue(); 3746 } else 3747 O = &O->getStructField(Field->getFieldIndex()); 3748 3749 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3750 LastField = Field; 3751 if (Field->getType().isVolatileQualified()) 3752 VolatileField = Field; 3753 } else { 3754 // Next subobject is a base class. 3755 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3756 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3757 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3758 3759 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3760 } 3761 } 3762 } 3763 3764 namespace { 3765 struct ExtractSubobjectHandler { 3766 EvalInfo &Info; 3767 const Expr *E; 3768 APValue &Result; 3769 const AccessKinds AccessKind; 3770 3771 typedef bool result_type; 3772 bool failed() { return false; } 3773 bool found(APValue &Subobj, QualType SubobjType) { 3774 Result = Subobj; 3775 if (AccessKind == AK_ReadObjectRepresentation) 3776 return true; 3777 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3778 } 3779 bool found(APSInt &Value, QualType SubobjType) { 3780 Result = APValue(Value); 3781 return true; 3782 } 3783 bool found(APFloat &Value, QualType SubobjType) { 3784 Result = APValue(Value); 3785 return true; 3786 } 3787 }; 3788 } // end anonymous namespace 3789 3790 /// Extract the designated sub-object of an rvalue. 3791 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3792 const CompleteObject &Obj, 3793 const SubobjectDesignator &Sub, APValue &Result, 3794 AccessKinds AK = AK_Read) { 3795 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3796 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3797 return findSubobject(Info, E, Obj, Sub, Handler); 3798 } 3799 3800 namespace { 3801 struct ModifySubobjectHandler { 3802 EvalInfo &Info; 3803 APValue &NewVal; 3804 const Expr *E; 3805 3806 typedef bool result_type; 3807 static const AccessKinds AccessKind = AK_Assign; 3808 3809 bool checkConst(QualType QT) { 3810 // Assigning to a const object has undefined behavior. 3811 if (QT.isConstQualified()) { 3812 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3813 return false; 3814 } 3815 return true; 3816 } 3817 3818 bool failed() { return false; } 3819 bool found(APValue &Subobj, QualType SubobjType) { 3820 if (!checkConst(SubobjType)) 3821 return false; 3822 // We've been given ownership of NewVal, so just swap it in. 3823 Subobj.swap(NewVal); 3824 return true; 3825 } 3826 bool found(APSInt &Value, QualType SubobjType) { 3827 if (!checkConst(SubobjType)) 3828 return false; 3829 if (!NewVal.isInt()) { 3830 // Maybe trying to write a cast pointer value into a complex? 3831 Info.FFDiag(E); 3832 return false; 3833 } 3834 Value = NewVal.getInt(); 3835 return true; 3836 } 3837 bool found(APFloat &Value, QualType SubobjType) { 3838 if (!checkConst(SubobjType)) 3839 return false; 3840 Value = NewVal.getFloat(); 3841 return true; 3842 } 3843 }; 3844 } // end anonymous namespace 3845 3846 const AccessKinds ModifySubobjectHandler::AccessKind; 3847 3848 /// Update the designated sub-object of an rvalue to the given value. 3849 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3850 const CompleteObject &Obj, 3851 const SubobjectDesignator &Sub, 3852 APValue &NewVal) { 3853 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3854 return findSubobject(Info, E, Obj, Sub, Handler); 3855 } 3856 3857 /// Find the position where two subobject designators diverge, or equivalently 3858 /// the length of the common initial subsequence. 3859 static unsigned FindDesignatorMismatch(QualType ObjType, 3860 const SubobjectDesignator &A, 3861 const SubobjectDesignator &B, 3862 bool &WasArrayIndex) { 3863 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3864 for (/**/; I != N; ++I) { 3865 if (!ObjType.isNull() && 3866 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3867 // Next subobject is an array element. 3868 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3869 WasArrayIndex = true; 3870 return I; 3871 } 3872 if (ObjType->isAnyComplexType()) 3873 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3874 else 3875 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3876 } else { 3877 if (A.Entries[I].getAsBaseOrMember() != 3878 B.Entries[I].getAsBaseOrMember()) { 3879 WasArrayIndex = false; 3880 return I; 3881 } 3882 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3883 // Next subobject is a field. 3884 ObjType = FD->getType(); 3885 else 3886 // Next subobject is a base class. 3887 ObjType = QualType(); 3888 } 3889 } 3890 WasArrayIndex = false; 3891 return I; 3892 } 3893 3894 /// Determine whether the given subobject designators refer to elements of the 3895 /// same array object. 3896 static bool AreElementsOfSameArray(QualType ObjType, 3897 const SubobjectDesignator &A, 3898 const SubobjectDesignator &B) { 3899 if (A.Entries.size() != B.Entries.size()) 3900 return false; 3901 3902 bool IsArray = A.MostDerivedIsArrayElement; 3903 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3904 // A is a subobject of the array element. 3905 return false; 3906 3907 // If A (and B) designates an array element, the last entry will be the array 3908 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3909 // of length 1' case, and the entire path must match. 3910 bool WasArrayIndex; 3911 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3912 return CommonLength >= A.Entries.size() - IsArray; 3913 } 3914 3915 /// Find the complete object to which an LValue refers. 3916 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3917 AccessKinds AK, const LValue &LVal, 3918 QualType LValType) { 3919 if (LVal.InvalidBase) { 3920 Info.FFDiag(E); 3921 return CompleteObject(); 3922 } 3923 3924 if (!LVal.Base) { 3925 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3926 return CompleteObject(); 3927 } 3928 3929 CallStackFrame *Frame = nullptr; 3930 unsigned Depth = 0; 3931 if (LVal.getLValueCallIndex()) { 3932 std::tie(Frame, Depth) = 3933 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3934 if (!Frame) { 3935 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3936 << AK << LVal.Base.is<const ValueDecl*>(); 3937 NoteLValueLocation(Info, LVal.Base); 3938 return CompleteObject(); 3939 } 3940 } 3941 3942 bool IsAccess = isAnyAccess(AK); 3943 3944 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3945 // is not a constant expression (even if the object is non-volatile). We also 3946 // apply this rule to C++98, in order to conform to the expected 'volatile' 3947 // semantics. 3948 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3949 if (Info.getLangOpts().CPlusPlus) 3950 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3951 << AK << LValType; 3952 else 3953 Info.FFDiag(E); 3954 return CompleteObject(); 3955 } 3956 3957 // Compute value storage location and type of base object. 3958 APValue *BaseVal = nullptr; 3959 QualType BaseType = getType(LVal.Base); 3960 3961 if (const ConstantExpr *CE = 3962 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3963 /// Nested immediate invocation have been previously removed so if we found 3964 /// a ConstantExpr it can only be the EvaluatingDecl. 3965 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3966 (void)CE; 3967 BaseVal = Info.EvaluatingDeclValue; 3968 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3969 // Allow reading from a GUID declaration. 3970 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3971 if (isModification(AK)) { 3972 // All the remaining cases do not permit modification of the object. 3973 Info.FFDiag(E, diag::note_constexpr_modify_global); 3974 return CompleteObject(); 3975 } 3976 APValue &V = GD->getAsAPValue(); 3977 if (V.isAbsent()) { 3978 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3979 << GD->getType(); 3980 return CompleteObject(); 3981 } 3982 return CompleteObject(LVal.Base, &V, GD->getType()); 3983 } 3984 3985 // Allow reading from template parameter objects. 3986 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 3987 if (isModification(AK)) { 3988 Info.FFDiag(E, diag::note_constexpr_modify_global); 3989 return CompleteObject(); 3990 } 3991 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 3992 TPO->getType()); 3993 } 3994 3995 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3996 // In C++11, constexpr, non-volatile variables initialized with constant 3997 // expressions are constant expressions too. Inside constexpr functions, 3998 // parameters are constant expressions even if they're non-const. 3999 // In C++1y, objects local to a constant expression (those with a Frame) are 4000 // both readable and writable inside constant expressions. 4001 // In C, such things can also be folded, although they are not ICEs. 4002 const VarDecl *VD = dyn_cast<VarDecl>(D); 4003 if (VD) { 4004 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4005 VD = VDef; 4006 } 4007 if (!VD || VD->isInvalidDecl()) { 4008 Info.FFDiag(E); 4009 return CompleteObject(); 4010 } 4011 4012 bool IsConstant = BaseType.isConstant(Info.Ctx); 4013 4014 // Unless we're looking at a local variable or argument in a constexpr call, 4015 // the variable we're reading must be const. 4016 if (!Frame) { 4017 if (IsAccess && isa<ParmVarDecl>(VD)) { 4018 // Access of a parameter that's not associated with a frame isn't going 4019 // to work out, but we can leave it to evaluateVarDeclInit to provide a 4020 // suitable diagnostic. 4021 } else if (Info.getLangOpts().CPlusPlus14 && 4022 lifetimeStartedInEvaluation(Info, LVal.Base)) { 4023 // OK, we can read and modify an object if we're in the process of 4024 // evaluating its initializer, because its lifetime began in this 4025 // evaluation. 4026 } else if (isModification(AK)) { 4027 // All the remaining cases do not permit modification of the object. 4028 Info.FFDiag(E, diag::note_constexpr_modify_global); 4029 return CompleteObject(); 4030 } else if (VD->isConstexpr()) { 4031 // OK, we can read this variable. 4032 } else if (BaseType->isIntegralOrEnumerationType()) { 4033 if (!IsConstant) { 4034 if (!IsAccess) 4035 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4036 if (Info.getLangOpts().CPlusPlus) { 4037 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4038 Info.Note(VD->getLocation(), diag::note_declared_at); 4039 } else { 4040 Info.FFDiag(E); 4041 } 4042 return CompleteObject(); 4043 } 4044 } else if (!IsAccess) { 4045 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4046 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4047 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4048 // This variable might end up being constexpr. Don't diagnose it yet. 4049 } else if (IsConstant) { 4050 // Keep evaluating to see what we can do. In particular, we support 4051 // folding of const floating-point types, in order to make static const 4052 // data members of such types (supported as an extension) more useful. 4053 if (Info.getLangOpts().CPlusPlus) { 4054 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4055 ? diag::note_constexpr_ltor_non_constexpr 4056 : diag::note_constexpr_ltor_non_integral, 1) 4057 << VD << BaseType; 4058 Info.Note(VD->getLocation(), diag::note_declared_at); 4059 } else { 4060 Info.CCEDiag(E); 4061 } 4062 } else { 4063 // Never allow reading a non-const value. 4064 if (Info.getLangOpts().CPlusPlus) { 4065 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4066 ? diag::note_constexpr_ltor_non_constexpr 4067 : diag::note_constexpr_ltor_non_integral, 1) 4068 << VD << BaseType; 4069 Info.Note(VD->getLocation(), diag::note_declared_at); 4070 } else { 4071 Info.FFDiag(E); 4072 } 4073 return CompleteObject(); 4074 } 4075 } 4076 4077 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4078 return CompleteObject(); 4079 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4080 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4081 if (!Alloc) { 4082 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4083 return CompleteObject(); 4084 } 4085 return CompleteObject(LVal.Base, &(*Alloc)->Value, 4086 LVal.Base.getDynamicAllocType()); 4087 } else { 4088 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4089 4090 if (!Frame) { 4091 if (const MaterializeTemporaryExpr *MTE = 4092 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4093 assert(MTE->getStorageDuration() == SD_Static && 4094 "should have a frame for a non-global materialized temporary"); 4095 4096 // Per C++1y [expr.const]p2: 4097 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4098 // - a [...] glvalue of integral or enumeration type that refers to 4099 // a non-volatile const object [...] 4100 // [...] 4101 // - a [...] glvalue of literal type that refers to a non-volatile 4102 // object whose lifetime began within the evaluation of e. 4103 // 4104 // C++11 misses the 'began within the evaluation of e' check and 4105 // instead allows all temporaries, including things like: 4106 // int &&r = 1; 4107 // int x = ++r; 4108 // constexpr int k = r; 4109 // Therefore we use the C++14 rules in C++11 too. 4110 // 4111 // Note that temporaries whose lifetimes began while evaluating a 4112 // variable's constructor are not usable while evaluating the 4113 // corresponding destructor, not even if they're of const-qualified 4114 // types. 4115 if (!(BaseType.isConstQualified() && 4116 BaseType->isIntegralOrEnumerationType()) && 4117 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4118 if (!IsAccess) 4119 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4120 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4121 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4122 return CompleteObject(); 4123 } 4124 4125 BaseVal = MTE->getOrCreateValue(false); 4126 assert(BaseVal && "got reference to unevaluated temporary"); 4127 } else { 4128 if (!IsAccess) 4129 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4130 APValue Val; 4131 LVal.moveInto(Val); 4132 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4133 << AK 4134 << Val.getAsString(Info.Ctx, 4135 Info.Ctx.getLValueReferenceType(LValType)); 4136 NoteLValueLocation(Info, LVal.Base); 4137 return CompleteObject(); 4138 } 4139 } else { 4140 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4141 assert(BaseVal && "missing value for temporary"); 4142 } 4143 } 4144 4145 // In C++14, we can't safely access any mutable state when we might be 4146 // evaluating after an unmodeled side effect. Parameters are modeled as state 4147 // in the caller, but aren't visible once the call returns, so they can be 4148 // modified in a speculatively-evaluated call. 4149 // 4150 // FIXME: Not all local state is mutable. Allow local constant subobjects 4151 // to be read here (but take care with 'mutable' fields). 4152 unsigned VisibleDepth = Depth; 4153 if (llvm::isa_and_nonnull<ParmVarDecl>( 4154 LVal.Base.dyn_cast<const ValueDecl *>())) 4155 ++VisibleDepth; 4156 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4157 Info.EvalStatus.HasSideEffects) || 4158 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4159 return CompleteObject(); 4160 4161 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4162 } 4163 4164 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4165 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4166 /// glvalue referred to by an entity of reference type. 4167 /// 4168 /// \param Info - Information about the ongoing evaluation. 4169 /// \param Conv - The expression for which we are performing the conversion. 4170 /// Used for diagnostics. 4171 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4172 /// case of a non-class type). 4173 /// \param LVal - The glvalue on which we are attempting to perform this action. 4174 /// \param RVal - The produced value will be placed here. 4175 /// \param WantObjectRepresentation - If true, we're looking for the object 4176 /// representation rather than the value, and in particular, 4177 /// there is no requirement that the result be fully initialized. 4178 static bool 4179 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4180 const LValue &LVal, APValue &RVal, 4181 bool WantObjectRepresentation = false) { 4182 if (LVal.Designator.Invalid) 4183 return false; 4184 4185 // Check for special cases where there is no existing APValue to look at. 4186 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4187 4188 AccessKinds AK = 4189 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4190 4191 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4192 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4193 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4194 // initializer until now for such expressions. Such an expression can't be 4195 // an ICE in C, so this only matters for fold. 4196 if (Type.isVolatileQualified()) { 4197 Info.FFDiag(Conv); 4198 return false; 4199 } 4200 APValue Lit; 4201 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4202 return false; 4203 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4204 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4205 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4206 // Special-case character extraction so we don't have to construct an 4207 // APValue for the whole string. 4208 assert(LVal.Designator.Entries.size() <= 1 && 4209 "Can only read characters from string literals"); 4210 if (LVal.Designator.Entries.empty()) { 4211 // Fail for now for LValue to RValue conversion of an array. 4212 // (This shouldn't show up in C/C++, but it could be triggered by a 4213 // weird EvaluateAsRValue call from a tool.) 4214 Info.FFDiag(Conv); 4215 return false; 4216 } 4217 if (LVal.Designator.isOnePastTheEnd()) { 4218 if (Info.getLangOpts().CPlusPlus11) 4219 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4220 else 4221 Info.FFDiag(Conv); 4222 return false; 4223 } 4224 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4225 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4226 return true; 4227 } 4228 } 4229 4230 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4231 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4232 } 4233 4234 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4235 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4236 QualType LValType, APValue &Val) { 4237 if (LVal.Designator.Invalid) 4238 return false; 4239 4240 if (!Info.getLangOpts().CPlusPlus14) { 4241 Info.FFDiag(E); 4242 return false; 4243 } 4244 4245 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4246 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4247 } 4248 4249 namespace { 4250 struct CompoundAssignSubobjectHandler { 4251 EvalInfo &Info; 4252 const CompoundAssignOperator *E; 4253 QualType PromotedLHSType; 4254 BinaryOperatorKind Opcode; 4255 const APValue &RHS; 4256 4257 static const AccessKinds AccessKind = AK_Assign; 4258 4259 typedef bool result_type; 4260 4261 bool checkConst(QualType QT) { 4262 // Assigning to a const object has undefined behavior. 4263 if (QT.isConstQualified()) { 4264 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4265 return false; 4266 } 4267 return true; 4268 } 4269 4270 bool failed() { return false; } 4271 bool found(APValue &Subobj, QualType SubobjType) { 4272 switch (Subobj.getKind()) { 4273 case APValue::Int: 4274 return found(Subobj.getInt(), SubobjType); 4275 case APValue::Float: 4276 return found(Subobj.getFloat(), SubobjType); 4277 case APValue::ComplexInt: 4278 case APValue::ComplexFloat: 4279 // FIXME: Implement complex compound assignment. 4280 Info.FFDiag(E); 4281 return false; 4282 case APValue::LValue: 4283 return foundPointer(Subobj, SubobjType); 4284 case APValue::Vector: 4285 return foundVector(Subobj, SubobjType); 4286 default: 4287 // FIXME: can this happen? 4288 Info.FFDiag(E); 4289 return false; 4290 } 4291 } 4292 4293 bool foundVector(APValue &Value, QualType SubobjType) { 4294 if (!checkConst(SubobjType)) 4295 return false; 4296 4297 if (!SubobjType->isVectorType()) { 4298 Info.FFDiag(E); 4299 return false; 4300 } 4301 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4302 } 4303 4304 bool found(APSInt &Value, QualType SubobjType) { 4305 if (!checkConst(SubobjType)) 4306 return false; 4307 4308 if (!SubobjType->isIntegerType()) { 4309 // We don't support compound assignment on integer-cast-to-pointer 4310 // values. 4311 Info.FFDiag(E); 4312 return false; 4313 } 4314 4315 if (RHS.isInt()) { 4316 APSInt LHS = 4317 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4318 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4319 return false; 4320 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4321 return true; 4322 } else if (RHS.isFloat()) { 4323 APFloat FValue(0.0); 4324 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4325 FValue) && 4326 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4327 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4328 Value); 4329 } 4330 4331 Info.FFDiag(E); 4332 return false; 4333 } 4334 bool found(APFloat &Value, QualType SubobjType) { 4335 return checkConst(SubobjType) && 4336 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4337 Value) && 4338 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4339 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4340 } 4341 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4342 if (!checkConst(SubobjType)) 4343 return false; 4344 4345 QualType PointeeType; 4346 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4347 PointeeType = PT->getPointeeType(); 4348 4349 if (PointeeType.isNull() || !RHS.isInt() || 4350 (Opcode != BO_Add && Opcode != BO_Sub)) { 4351 Info.FFDiag(E); 4352 return false; 4353 } 4354 4355 APSInt Offset = RHS.getInt(); 4356 if (Opcode == BO_Sub) 4357 negateAsSigned(Offset); 4358 4359 LValue LVal; 4360 LVal.setFrom(Info.Ctx, Subobj); 4361 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4362 return false; 4363 LVal.moveInto(Subobj); 4364 return true; 4365 } 4366 }; 4367 } // end anonymous namespace 4368 4369 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4370 4371 /// Perform a compound assignment of LVal <op>= RVal. 4372 static bool handleCompoundAssignment(EvalInfo &Info, 4373 const CompoundAssignOperator *E, 4374 const LValue &LVal, QualType LValType, 4375 QualType PromotedLValType, 4376 BinaryOperatorKind Opcode, 4377 const APValue &RVal) { 4378 if (LVal.Designator.Invalid) 4379 return false; 4380 4381 if (!Info.getLangOpts().CPlusPlus14) { 4382 Info.FFDiag(E); 4383 return false; 4384 } 4385 4386 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4387 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4388 RVal }; 4389 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4390 } 4391 4392 namespace { 4393 struct IncDecSubobjectHandler { 4394 EvalInfo &Info; 4395 const UnaryOperator *E; 4396 AccessKinds AccessKind; 4397 APValue *Old; 4398 4399 typedef bool result_type; 4400 4401 bool checkConst(QualType QT) { 4402 // Assigning to a const object has undefined behavior. 4403 if (QT.isConstQualified()) { 4404 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4405 return false; 4406 } 4407 return true; 4408 } 4409 4410 bool failed() { return false; } 4411 bool found(APValue &Subobj, QualType SubobjType) { 4412 // Stash the old value. Also clear Old, so we don't clobber it later 4413 // if we're post-incrementing a complex. 4414 if (Old) { 4415 *Old = Subobj; 4416 Old = nullptr; 4417 } 4418 4419 switch (Subobj.getKind()) { 4420 case APValue::Int: 4421 return found(Subobj.getInt(), SubobjType); 4422 case APValue::Float: 4423 return found(Subobj.getFloat(), SubobjType); 4424 case APValue::ComplexInt: 4425 return found(Subobj.getComplexIntReal(), 4426 SubobjType->castAs<ComplexType>()->getElementType() 4427 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4428 case APValue::ComplexFloat: 4429 return found(Subobj.getComplexFloatReal(), 4430 SubobjType->castAs<ComplexType>()->getElementType() 4431 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4432 case APValue::LValue: 4433 return foundPointer(Subobj, SubobjType); 4434 default: 4435 // FIXME: can this happen? 4436 Info.FFDiag(E); 4437 return false; 4438 } 4439 } 4440 bool found(APSInt &Value, QualType SubobjType) { 4441 if (!checkConst(SubobjType)) 4442 return false; 4443 4444 if (!SubobjType->isIntegerType()) { 4445 // We don't support increment / decrement on integer-cast-to-pointer 4446 // values. 4447 Info.FFDiag(E); 4448 return false; 4449 } 4450 4451 if (Old) *Old = APValue(Value); 4452 4453 // bool arithmetic promotes to int, and the conversion back to bool 4454 // doesn't reduce mod 2^n, so special-case it. 4455 if (SubobjType->isBooleanType()) { 4456 if (AccessKind == AK_Increment) 4457 Value = 1; 4458 else 4459 Value = !Value; 4460 return true; 4461 } 4462 4463 bool WasNegative = Value.isNegative(); 4464 if (AccessKind == AK_Increment) { 4465 ++Value; 4466 4467 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4468 APSInt ActualValue(Value, /*IsUnsigned*/true); 4469 return HandleOverflow(Info, E, ActualValue, SubobjType); 4470 } 4471 } else { 4472 --Value; 4473 4474 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4475 unsigned BitWidth = Value.getBitWidth(); 4476 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4477 ActualValue.setBit(BitWidth); 4478 return HandleOverflow(Info, E, ActualValue, SubobjType); 4479 } 4480 } 4481 return true; 4482 } 4483 bool found(APFloat &Value, QualType SubobjType) { 4484 if (!checkConst(SubobjType)) 4485 return false; 4486 4487 if (Old) *Old = APValue(Value); 4488 4489 APFloat One(Value.getSemantics(), 1); 4490 if (AccessKind == AK_Increment) 4491 Value.add(One, APFloat::rmNearestTiesToEven); 4492 else 4493 Value.subtract(One, APFloat::rmNearestTiesToEven); 4494 return true; 4495 } 4496 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4497 if (!checkConst(SubobjType)) 4498 return false; 4499 4500 QualType PointeeType; 4501 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4502 PointeeType = PT->getPointeeType(); 4503 else { 4504 Info.FFDiag(E); 4505 return false; 4506 } 4507 4508 LValue LVal; 4509 LVal.setFrom(Info.Ctx, Subobj); 4510 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4511 AccessKind == AK_Increment ? 1 : -1)) 4512 return false; 4513 LVal.moveInto(Subobj); 4514 return true; 4515 } 4516 }; 4517 } // end anonymous namespace 4518 4519 /// Perform an increment or decrement on LVal. 4520 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4521 QualType LValType, bool IsIncrement, APValue *Old) { 4522 if (LVal.Designator.Invalid) 4523 return false; 4524 4525 if (!Info.getLangOpts().CPlusPlus14) { 4526 Info.FFDiag(E); 4527 return false; 4528 } 4529 4530 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4531 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4532 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4533 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4534 } 4535 4536 /// Build an lvalue for the object argument of a member function call. 4537 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4538 LValue &This) { 4539 if (Object->getType()->isPointerType() && Object->isRValue()) 4540 return EvaluatePointer(Object, This, Info); 4541 4542 if (Object->isGLValue()) 4543 return EvaluateLValue(Object, This, Info); 4544 4545 if (Object->getType()->isLiteralType(Info.Ctx)) 4546 return EvaluateTemporary(Object, This, Info); 4547 4548 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4549 return false; 4550 } 4551 4552 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4553 /// lvalue referring to the result. 4554 /// 4555 /// \param Info - Information about the ongoing evaluation. 4556 /// \param LV - An lvalue referring to the base of the member pointer. 4557 /// \param RHS - The member pointer expression. 4558 /// \param IncludeMember - Specifies whether the member itself is included in 4559 /// the resulting LValue subobject designator. This is not possible when 4560 /// creating a bound member function. 4561 /// \return The field or method declaration to which the member pointer refers, 4562 /// or 0 if evaluation fails. 4563 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4564 QualType LVType, 4565 LValue &LV, 4566 const Expr *RHS, 4567 bool IncludeMember = true) { 4568 MemberPtr MemPtr; 4569 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4570 return nullptr; 4571 4572 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4573 // member value, the behavior is undefined. 4574 if (!MemPtr.getDecl()) { 4575 // FIXME: Specific diagnostic. 4576 Info.FFDiag(RHS); 4577 return nullptr; 4578 } 4579 4580 if (MemPtr.isDerivedMember()) { 4581 // This is a member of some derived class. Truncate LV appropriately. 4582 // The end of the derived-to-base path for the base object must match the 4583 // derived-to-base path for the member pointer. 4584 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4585 LV.Designator.Entries.size()) { 4586 Info.FFDiag(RHS); 4587 return nullptr; 4588 } 4589 unsigned PathLengthToMember = 4590 LV.Designator.Entries.size() - MemPtr.Path.size(); 4591 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4592 const CXXRecordDecl *LVDecl = getAsBaseClass( 4593 LV.Designator.Entries[PathLengthToMember + I]); 4594 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4595 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4596 Info.FFDiag(RHS); 4597 return nullptr; 4598 } 4599 } 4600 4601 // Truncate the lvalue to the appropriate derived class. 4602 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4603 PathLengthToMember)) 4604 return nullptr; 4605 } else if (!MemPtr.Path.empty()) { 4606 // Extend the LValue path with the member pointer's path. 4607 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4608 MemPtr.Path.size() + IncludeMember); 4609 4610 // Walk down to the appropriate base class. 4611 if (const PointerType *PT = LVType->getAs<PointerType>()) 4612 LVType = PT->getPointeeType(); 4613 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4614 assert(RD && "member pointer access on non-class-type expression"); 4615 // The first class in the path is that of the lvalue. 4616 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4617 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4618 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4619 return nullptr; 4620 RD = Base; 4621 } 4622 // Finally cast to the class containing the member. 4623 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4624 MemPtr.getContainingRecord())) 4625 return nullptr; 4626 } 4627 4628 // Add the member. Note that we cannot build bound member functions here. 4629 if (IncludeMember) { 4630 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4631 if (!HandleLValueMember(Info, RHS, LV, FD)) 4632 return nullptr; 4633 } else if (const IndirectFieldDecl *IFD = 4634 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4635 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4636 return nullptr; 4637 } else { 4638 llvm_unreachable("can't construct reference to bound member function"); 4639 } 4640 } 4641 4642 return MemPtr.getDecl(); 4643 } 4644 4645 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4646 const BinaryOperator *BO, 4647 LValue &LV, 4648 bool IncludeMember = true) { 4649 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4650 4651 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4652 if (Info.noteFailure()) { 4653 MemberPtr MemPtr; 4654 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4655 } 4656 return nullptr; 4657 } 4658 4659 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4660 BO->getRHS(), IncludeMember); 4661 } 4662 4663 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4664 /// the provided lvalue, which currently refers to the base object. 4665 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4666 LValue &Result) { 4667 SubobjectDesignator &D = Result.Designator; 4668 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4669 return false; 4670 4671 QualType TargetQT = E->getType(); 4672 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4673 TargetQT = PT->getPointeeType(); 4674 4675 // Check this cast lands within the final derived-to-base subobject path. 4676 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4677 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4678 << D.MostDerivedType << TargetQT; 4679 return false; 4680 } 4681 4682 // Check the type of the final cast. We don't need to check the path, 4683 // since a cast can only be formed if the path is unique. 4684 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4685 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4686 const CXXRecordDecl *FinalType; 4687 if (NewEntriesSize == D.MostDerivedPathLength) 4688 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4689 else 4690 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4691 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4692 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4693 << D.MostDerivedType << TargetQT; 4694 return false; 4695 } 4696 4697 // Truncate the lvalue to the appropriate derived class. 4698 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4699 } 4700 4701 /// Get the value to use for a default-initialized object of type T. 4702 /// Return false if it encounters something invalid. 4703 static bool getDefaultInitValue(QualType T, APValue &Result) { 4704 bool Success = true; 4705 if (auto *RD = T->getAsCXXRecordDecl()) { 4706 if (RD->isInvalidDecl()) { 4707 Result = APValue(); 4708 return false; 4709 } 4710 if (RD->isUnion()) { 4711 Result = APValue((const FieldDecl *)nullptr); 4712 return true; 4713 } 4714 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4715 std::distance(RD->field_begin(), RD->field_end())); 4716 4717 unsigned Index = 0; 4718 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4719 End = RD->bases_end(); 4720 I != End; ++I, ++Index) 4721 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4722 4723 for (const auto *I : RD->fields()) { 4724 if (I->isUnnamedBitfield()) 4725 continue; 4726 Success &= getDefaultInitValue(I->getType(), 4727 Result.getStructField(I->getFieldIndex())); 4728 } 4729 return Success; 4730 } 4731 4732 if (auto *AT = 4733 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4734 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4735 if (Result.hasArrayFiller()) 4736 Success &= 4737 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4738 4739 return Success; 4740 } 4741 4742 Result = APValue::IndeterminateValue(); 4743 return true; 4744 } 4745 4746 namespace { 4747 enum EvalStmtResult { 4748 /// Evaluation failed. 4749 ESR_Failed, 4750 /// Hit a 'return' statement. 4751 ESR_Returned, 4752 /// Evaluation succeeded. 4753 ESR_Succeeded, 4754 /// Hit a 'continue' statement. 4755 ESR_Continue, 4756 /// Hit a 'break' statement. 4757 ESR_Break, 4758 /// Still scanning for 'case' or 'default' statement. 4759 ESR_CaseNotFound 4760 }; 4761 } 4762 4763 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4764 // We don't need to evaluate the initializer for a static local. 4765 if (!VD->hasLocalStorage()) 4766 return true; 4767 4768 LValue Result; 4769 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4770 ScopeKind::Block, Result); 4771 4772 const Expr *InitE = VD->getInit(); 4773 if (!InitE) 4774 return getDefaultInitValue(VD->getType(), Val); 4775 4776 if (InitE->isValueDependent()) 4777 return false; 4778 4779 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4780 // Wipe out any partially-computed value, to allow tracking that this 4781 // evaluation failed. 4782 Val = APValue(); 4783 return false; 4784 } 4785 4786 return true; 4787 } 4788 4789 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4790 bool OK = true; 4791 4792 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4793 OK &= EvaluateVarDecl(Info, VD); 4794 4795 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4796 for (auto *BD : DD->bindings()) 4797 if (auto *VD = BD->getHoldingVar()) 4798 OK &= EvaluateDecl(Info, VD); 4799 4800 return OK; 4801 } 4802 4803 4804 /// Evaluate a condition (either a variable declaration or an expression). 4805 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4806 const Expr *Cond, bool &Result) { 4807 FullExpressionRAII Scope(Info); 4808 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4809 return false; 4810 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4811 return false; 4812 return Scope.destroy(); 4813 } 4814 4815 namespace { 4816 /// A location where the result (returned value) of evaluating a 4817 /// statement should be stored. 4818 struct StmtResult { 4819 /// The APValue that should be filled in with the returned value. 4820 APValue &Value; 4821 /// The location containing the result, if any (used to support RVO). 4822 const LValue *Slot; 4823 }; 4824 4825 struct TempVersionRAII { 4826 CallStackFrame &Frame; 4827 4828 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4829 Frame.pushTempVersion(); 4830 } 4831 4832 ~TempVersionRAII() { 4833 Frame.popTempVersion(); 4834 } 4835 }; 4836 4837 } 4838 4839 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4840 const Stmt *S, 4841 const SwitchCase *SC = nullptr); 4842 4843 /// Evaluate the body of a loop, and translate the result as appropriate. 4844 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4845 const Stmt *Body, 4846 const SwitchCase *Case = nullptr) { 4847 BlockScopeRAII Scope(Info); 4848 4849 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4850 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4851 ESR = ESR_Failed; 4852 4853 switch (ESR) { 4854 case ESR_Break: 4855 return ESR_Succeeded; 4856 case ESR_Succeeded: 4857 case ESR_Continue: 4858 return ESR_Continue; 4859 case ESR_Failed: 4860 case ESR_Returned: 4861 case ESR_CaseNotFound: 4862 return ESR; 4863 } 4864 llvm_unreachable("Invalid EvalStmtResult!"); 4865 } 4866 4867 /// Evaluate a switch statement. 4868 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4869 const SwitchStmt *SS) { 4870 BlockScopeRAII Scope(Info); 4871 4872 // Evaluate the switch condition. 4873 APSInt Value; 4874 { 4875 if (const Stmt *Init = SS->getInit()) { 4876 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4877 if (ESR != ESR_Succeeded) { 4878 if (ESR != ESR_Failed && !Scope.destroy()) 4879 ESR = ESR_Failed; 4880 return ESR; 4881 } 4882 } 4883 4884 FullExpressionRAII CondScope(Info); 4885 if (SS->getConditionVariable() && 4886 !EvaluateDecl(Info, SS->getConditionVariable())) 4887 return ESR_Failed; 4888 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4889 return ESR_Failed; 4890 if (!CondScope.destroy()) 4891 return ESR_Failed; 4892 } 4893 4894 // Find the switch case corresponding to the value of the condition. 4895 // FIXME: Cache this lookup. 4896 const SwitchCase *Found = nullptr; 4897 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4898 SC = SC->getNextSwitchCase()) { 4899 if (isa<DefaultStmt>(SC)) { 4900 Found = SC; 4901 continue; 4902 } 4903 4904 const CaseStmt *CS = cast<CaseStmt>(SC); 4905 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4906 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4907 : LHS; 4908 if (LHS <= Value && Value <= RHS) { 4909 Found = SC; 4910 break; 4911 } 4912 } 4913 4914 if (!Found) 4915 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4916 4917 // Search the switch body for the switch case and evaluate it from there. 4918 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4919 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4920 return ESR_Failed; 4921 4922 switch (ESR) { 4923 case ESR_Break: 4924 return ESR_Succeeded; 4925 case ESR_Succeeded: 4926 case ESR_Continue: 4927 case ESR_Failed: 4928 case ESR_Returned: 4929 return ESR; 4930 case ESR_CaseNotFound: 4931 // This can only happen if the switch case is nested within a statement 4932 // expression. We have no intention of supporting that. 4933 Info.FFDiag(Found->getBeginLoc(), 4934 diag::note_constexpr_stmt_expr_unsupported); 4935 return ESR_Failed; 4936 } 4937 llvm_unreachable("Invalid EvalStmtResult!"); 4938 } 4939 4940 // Evaluate a statement. 4941 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4942 const Stmt *S, const SwitchCase *Case) { 4943 if (!Info.nextStep(S)) 4944 return ESR_Failed; 4945 4946 // If we're hunting down a 'case' or 'default' label, recurse through 4947 // substatements until we hit the label. 4948 if (Case) { 4949 switch (S->getStmtClass()) { 4950 case Stmt::CompoundStmtClass: 4951 // FIXME: Precompute which substatement of a compound statement we 4952 // would jump to, and go straight there rather than performing a 4953 // linear scan each time. 4954 case Stmt::LabelStmtClass: 4955 case Stmt::AttributedStmtClass: 4956 case Stmt::DoStmtClass: 4957 break; 4958 4959 case Stmt::CaseStmtClass: 4960 case Stmt::DefaultStmtClass: 4961 if (Case == S) 4962 Case = nullptr; 4963 break; 4964 4965 case Stmt::IfStmtClass: { 4966 // FIXME: Precompute which side of an 'if' we would jump to, and go 4967 // straight there rather than scanning both sides. 4968 const IfStmt *IS = cast<IfStmt>(S); 4969 4970 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4971 // preceded by our switch label. 4972 BlockScopeRAII Scope(Info); 4973 4974 // Step into the init statement in case it brings an (uninitialized) 4975 // variable into scope. 4976 if (const Stmt *Init = IS->getInit()) { 4977 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4978 if (ESR != ESR_CaseNotFound) { 4979 assert(ESR != ESR_Succeeded); 4980 return ESR; 4981 } 4982 } 4983 4984 // Condition variable must be initialized if it exists. 4985 // FIXME: We can skip evaluating the body if there's a condition 4986 // variable, as there can't be any case labels within it. 4987 // (The same is true for 'for' statements.) 4988 4989 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4990 if (ESR == ESR_Failed) 4991 return ESR; 4992 if (ESR != ESR_CaseNotFound) 4993 return Scope.destroy() ? ESR : ESR_Failed; 4994 if (!IS->getElse()) 4995 return ESR_CaseNotFound; 4996 4997 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4998 if (ESR == ESR_Failed) 4999 return ESR; 5000 if (ESR != ESR_CaseNotFound) 5001 return Scope.destroy() ? ESR : ESR_Failed; 5002 return ESR_CaseNotFound; 5003 } 5004 5005 case Stmt::WhileStmtClass: { 5006 EvalStmtResult ESR = 5007 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5008 if (ESR != ESR_Continue) 5009 return ESR; 5010 break; 5011 } 5012 5013 case Stmt::ForStmtClass: { 5014 const ForStmt *FS = cast<ForStmt>(S); 5015 BlockScopeRAII Scope(Info); 5016 5017 // Step into the init statement in case it brings an (uninitialized) 5018 // variable into scope. 5019 if (const Stmt *Init = FS->getInit()) { 5020 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5021 if (ESR != ESR_CaseNotFound) { 5022 assert(ESR != ESR_Succeeded); 5023 return ESR; 5024 } 5025 } 5026 5027 EvalStmtResult ESR = 5028 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5029 if (ESR != ESR_Continue) 5030 return ESR; 5031 if (FS->getInc()) { 5032 FullExpressionRAII IncScope(Info); 5033 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5034 return ESR_Failed; 5035 } 5036 break; 5037 } 5038 5039 case Stmt::DeclStmtClass: { 5040 // Start the lifetime of any uninitialized variables we encounter. They 5041 // might be used by the selected branch of the switch. 5042 const DeclStmt *DS = cast<DeclStmt>(S); 5043 for (const auto *D : DS->decls()) { 5044 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5045 if (VD->hasLocalStorage() && !VD->getInit()) 5046 if (!EvaluateVarDecl(Info, VD)) 5047 return ESR_Failed; 5048 // FIXME: If the variable has initialization that can't be jumped 5049 // over, bail out of any immediately-surrounding compound-statement 5050 // too. There can't be any case labels here. 5051 } 5052 } 5053 return ESR_CaseNotFound; 5054 } 5055 5056 default: 5057 return ESR_CaseNotFound; 5058 } 5059 } 5060 5061 switch (S->getStmtClass()) { 5062 default: 5063 if (const Expr *E = dyn_cast<Expr>(S)) { 5064 // Don't bother evaluating beyond an expression-statement which couldn't 5065 // be evaluated. 5066 // FIXME: Do we need the FullExpressionRAII object here? 5067 // VisitExprWithCleanups should create one when necessary. 5068 FullExpressionRAII Scope(Info); 5069 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5070 return ESR_Failed; 5071 return ESR_Succeeded; 5072 } 5073 5074 Info.FFDiag(S->getBeginLoc()); 5075 return ESR_Failed; 5076 5077 case Stmt::NullStmtClass: 5078 return ESR_Succeeded; 5079 5080 case Stmt::DeclStmtClass: { 5081 const DeclStmt *DS = cast<DeclStmt>(S); 5082 for (const auto *D : DS->decls()) { 5083 // Each declaration initialization is its own full-expression. 5084 FullExpressionRAII Scope(Info); 5085 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5086 return ESR_Failed; 5087 if (!Scope.destroy()) 5088 return ESR_Failed; 5089 } 5090 return ESR_Succeeded; 5091 } 5092 5093 case Stmt::ReturnStmtClass: { 5094 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5095 FullExpressionRAII Scope(Info); 5096 if (RetExpr && 5097 !(Result.Slot 5098 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5099 : Evaluate(Result.Value, Info, RetExpr))) 5100 return ESR_Failed; 5101 return Scope.destroy() ? ESR_Returned : ESR_Failed; 5102 } 5103 5104 case Stmt::CompoundStmtClass: { 5105 BlockScopeRAII Scope(Info); 5106 5107 const CompoundStmt *CS = cast<CompoundStmt>(S); 5108 for (const auto *BI : CS->body()) { 5109 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5110 if (ESR == ESR_Succeeded) 5111 Case = nullptr; 5112 else if (ESR != ESR_CaseNotFound) { 5113 if (ESR != ESR_Failed && !Scope.destroy()) 5114 return ESR_Failed; 5115 return ESR; 5116 } 5117 } 5118 if (Case) 5119 return ESR_CaseNotFound; 5120 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5121 } 5122 5123 case Stmt::IfStmtClass: { 5124 const IfStmt *IS = cast<IfStmt>(S); 5125 5126 // Evaluate the condition, as either a var decl or as an expression. 5127 BlockScopeRAII Scope(Info); 5128 if (const Stmt *Init = IS->getInit()) { 5129 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5130 if (ESR != ESR_Succeeded) { 5131 if (ESR != ESR_Failed && !Scope.destroy()) 5132 return ESR_Failed; 5133 return ESR; 5134 } 5135 } 5136 bool Cond; 5137 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5138 return ESR_Failed; 5139 5140 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5141 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5142 if (ESR != ESR_Succeeded) { 5143 if (ESR != ESR_Failed && !Scope.destroy()) 5144 return ESR_Failed; 5145 return ESR; 5146 } 5147 } 5148 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5149 } 5150 5151 case Stmt::WhileStmtClass: { 5152 const WhileStmt *WS = cast<WhileStmt>(S); 5153 while (true) { 5154 BlockScopeRAII Scope(Info); 5155 bool Continue; 5156 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5157 Continue)) 5158 return ESR_Failed; 5159 if (!Continue) 5160 break; 5161 5162 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5163 if (ESR != ESR_Continue) { 5164 if (ESR != ESR_Failed && !Scope.destroy()) 5165 return ESR_Failed; 5166 return ESR; 5167 } 5168 if (!Scope.destroy()) 5169 return ESR_Failed; 5170 } 5171 return ESR_Succeeded; 5172 } 5173 5174 case Stmt::DoStmtClass: { 5175 const DoStmt *DS = cast<DoStmt>(S); 5176 bool Continue; 5177 do { 5178 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5179 if (ESR != ESR_Continue) 5180 return ESR; 5181 Case = nullptr; 5182 5183 FullExpressionRAII CondScope(Info); 5184 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5185 !CondScope.destroy()) 5186 return ESR_Failed; 5187 } while (Continue); 5188 return ESR_Succeeded; 5189 } 5190 5191 case Stmt::ForStmtClass: { 5192 const ForStmt *FS = cast<ForStmt>(S); 5193 BlockScopeRAII ForScope(Info); 5194 if (FS->getInit()) { 5195 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5196 if (ESR != ESR_Succeeded) { 5197 if (ESR != ESR_Failed && !ForScope.destroy()) 5198 return ESR_Failed; 5199 return ESR; 5200 } 5201 } 5202 while (true) { 5203 BlockScopeRAII IterScope(Info); 5204 bool Continue = true; 5205 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5206 FS->getCond(), Continue)) 5207 return ESR_Failed; 5208 if (!Continue) 5209 break; 5210 5211 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5212 if (ESR != ESR_Continue) { 5213 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5214 return ESR_Failed; 5215 return ESR; 5216 } 5217 5218 if (FS->getInc()) { 5219 FullExpressionRAII IncScope(Info); 5220 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5221 return ESR_Failed; 5222 } 5223 5224 if (!IterScope.destroy()) 5225 return ESR_Failed; 5226 } 5227 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5228 } 5229 5230 case Stmt::CXXForRangeStmtClass: { 5231 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5232 BlockScopeRAII Scope(Info); 5233 5234 // Evaluate the init-statement if present. 5235 if (FS->getInit()) { 5236 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5237 if (ESR != ESR_Succeeded) { 5238 if (ESR != ESR_Failed && !Scope.destroy()) 5239 return ESR_Failed; 5240 return ESR; 5241 } 5242 } 5243 5244 // Initialize the __range variable. 5245 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5246 if (ESR != ESR_Succeeded) { 5247 if (ESR != ESR_Failed && !Scope.destroy()) 5248 return ESR_Failed; 5249 return ESR; 5250 } 5251 5252 // Create the __begin and __end iterators. 5253 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5254 if (ESR != ESR_Succeeded) { 5255 if (ESR != ESR_Failed && !Scope.destroy()) 5256 return ESR_Failed; 5257 return ESR; 5258 } 5259 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5260 if (ESR != ESR_Succeeded) { 5261 if (ESR != ESR_Failed && !Scope.destroy()) 5262 return ESR_Failed; 5263 return ESR; 5264 } 5265 5266 while (true) { 5267 // Condition: __begin != __end. 5268 { 5269 bool Continue = true; 5270 FullExpressionRAII CondExpr(Info); 5271 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5272 return ESR_Failed; 5273 if (!Continue) 5274 break; 5275 } 5276 5277 // User's variable declaration, initialized by *__begin. 5278 BlockScopeRAII InnerScope(Info); 5279 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5280 if (ESR != ESR_Succeeded) { 5281 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5282 return ESR_Failed; 5283 return ESR; 5284 } 5285 5286 // Loop body. 5287 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5288 if (ESR != ESR_Continue) { 5289 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5290 return ESR_Failed; 5291 return ESR; 5292 } 5293 5294 // Increment: ++__begin 5295 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5296 return ESR_Failed; 5297 5298 if (!InnerScope.destroy()) 5299 return ESR_Failed; 5300 } 5301 5302 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5303 } 5304 5305 case Stmt::SwitchStmtClass: 5306 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5307 5308 case Stmt::ContinueStmtClass: 5309 return ESR_Continue; 5310 5311 case Stmt::BreakStmtClass: 5312 return ESR_Break; 5313 5314 case Stmt::LabelStmtClass: 5315 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5316 5317 case Stmt::AttributedStmtClass: 5318 // As a general principle, C++11 attributes can be ignored without 5319 // any semantic impact. 5320 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5321 Case); 5322 5323 case Stmt::CaseStmtClass: 5324 case Stmt::DefaultStmtClass: 5325 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5326 case Stmt::CXXTryStmtClass: 5327 // Evaluate try blocks by evaluating all sub statements. 5328 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5329 } 5330 } 5331 5332 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5333 /// default constructor. If so, we'll fold it whether or not it's marked as 5334 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5335 /// so we need special handling. 5336 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5337 const CXXConstructorDecl *CD, 5338 bool IsValueInitialization) { 5339 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5340 return false; 5341 5342 // Value-initialization does not call a trivial default constructor, so such a 5343 // call is a core constant expression whether or not the constructor is 5344 // constexpr. 5345 if (!CD->isConstexpr() && !IsValueInitialization) { 5346 if (Info.getLangOpts().CPlusPlus11) { 5347 // FIXME: If DiagDecl is an implicitly-declared special member function, 5348 // we should be much more explicit about why it's not constexpr. 5349 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5350 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5351 Info.Note(CD->getLocation(), diag::note_declared_at); 5352 } else { 5353 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5354 } 5355 } 5356 return true; 5357 } 5358 5359 /// CheckConstexprFunction - Check that a function can be called in a constant 5360 /// expression. 5361 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5362 const FunctionDecl *Declaration, 5363 const FunctionDecl *Definition, 5364 const Stmt *Body) { 5365 // Potential constant expressions can contain calls to declared, but not yet 5366 // defined, constexpr functions. 5367 if (Info.checkingPotentialConstantExpression() && !Definition && 5368 Declaration->isConstexpr()) 5369 return false; 5370 5371 // Bail out if the function declaration itself is invalid. We will 5372 // have produced a relevant diagnostic while parsing it, so just 5373 // note the problematic sub-expression. 5374 if (Declaration->isInvalidDecl()) { 5375 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5376 return false; 5377 } 5378 5379 // DR1872: An instantiated virtual constexpr function can't be called in a 5380 // constant expression (prior to C++20). We can still constant-fold such a 5381 // call. 5382 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5383 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5384 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5385 5386 if (Definition && Definition->isInvalidDecl()) { 5387 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5388 return false; 5389 } 5390 5391 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5392 for (const auto *InitExpr : CtorDecl->inits()) { 5393 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5394 return false; 5395 } 5396 } 5397 5398 // Can we evaluate this function call? 5399 if (Definition && Definition->isConstexpr() && Body) 5400 return true; 5401 5402 if (Info.getLangOpts().CPlusPlus11) { 5403 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5404 5405 // If this function is not constexpr because it is an inherited 5406 // non-constexpr constructor, diagnose that directly. 5407 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5408 if (CD && CD->isInheritingConstructor()) { 5409 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5410 if (!Inherited->isConstexpr()) 5411 DiagDecl = CD = Inherited; 5412 } 5413 5414 // FIXME: If DiagDecl is an implicitly-declared special member function 5415 // or an inheriting constructor, we should be much more explicit about why 5416 // it's not constexpr. 5417 if (CD && CD->isInheritingConstructor()) 5418 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5419 << CD->getInheritedConstructor().getConstructor()->getParent(); 5420 else 5421 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5422 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5423 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5424 } else { 5425 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5426 } 5427 return false; 5428 } 5429 5430 namespace { 5431 struct CheckDynamicTypeHandler { 5432 AccessKinds AccessKind; 5433 typedef bool result_type; 5434 bool failed() { return false; } 5435 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5436 bool found(APSInt &Value, QualType SubobjType) { return true; } 5437 bool found(APFloat &Value, QualType SubobjType) { return true; } 5438 }; 5439 } // end anonymous namespace 5440 5441 /// Check that we can access the notional vptr of an object / determine its 5442 /// dynamic type. 5443 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5444 AccessKinds AK, bool Polymorphic) { 5445 if (This.Designator.Invalid) 5446 return false; 5447 5448 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5449 5450 if (!Obj) 5451 return false; 5452 5453 if (!Obj.Value) { 5454 // The object is not usable in constant expressions, so we can't inspect 5455 // its value to see if it's in-lifetime or what the active union members 5456 // are. We can still check for a one-past-the-end lvalue. 5457 if (This.Designator.isOnePastTheEnd() || 5458 This.Designator.isMostDerivedAnUnsizedArray()) { 5459 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5460 ? diag::note_constexpr_access_past_end 5461 : diag::note_constexpr_access_unsized_array) 5462 << AK; 5463 return false; 5464 } else if (Polymorphic) { 5465 // Conservatively refuse to perform a polymorphic operation if we would 5466 // not be able to read a notional 'vptr' value. 5467 APValue Val; 5468 This.moveInto(Val); 5469 QualType StarThisType = 5470 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5471 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5472 << AK << Val.getAsString(Info.Ctx, StarThisType); 5473 return false; 5474 } 5475 return true; 5476 } 5477 5478 CheckDynamicTypeHandler Handler{AK}; 5479 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5480 } 5481 5482 /// Check that the pointee of the 'this' pointer in a member function call is 5483 /// either within its lifetime or in its period of construction or destruction. 5484 static bool 5485 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5486 const LValue &This, 5487 const CXXMethodDecl *NamedMember) { 5488 return checkDynamicType( 5489 Info, E, This, 5490 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5491 } 5492 5493 struct DynamicType { 5494 /// The dynamic class type of the object. 5495 const CXXRecordDecl *Type; 5496 /// The corresponding path length in the lvalue. 5497 unsigned PathLength; 5498 }; 5499 5500 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5501 unsigned PathLength) { 5502 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5503 Designator.Entries.size() && "invalid path length"); 5504 return (PathLength == Designator.MostDerivedPathLength) 5505 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5506 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5507 } 5508 5509 /// Determine the dynamic type of an object. 5510 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5511 LValue &This, AccessKinds AK) { 5512 // If we don't have an lvalue denoting an object of class type, there is no 5513 // meaningful dynamic type. (We consider objects of non-class type to have no 5514 // dynamic type.) 5515 if (!checkDynamicType(Info, E, This, AK, true)) 5516 return None; 5517 5518 // Refuse to compute a dynamic type in the presence of virtual bases. This 5519 // shouldn't happen other than in constant-folding situations, since literal 5520 // types can't have virtual bases. 5521 // 5522 // Note that consumers of DynamicType assume that the type has no virtual 5523 // bases, and will need modifications if this restriction is relaxed. 5524 const CXXRecordDecl *Class = 5525 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5526 if (!Class || Class->getNumVBases()) { 5527 Info.FFDiag(E); 5528 return None; 5529 } 5530 5531 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5532 // binary search here instead. But the overwhelmingly common case is that 5533 // we're not in the middle of a constructor, so it probably doesn't matter 5534 // in practice. 5535 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5536 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5537 PathLength <= Path.size(); ++PathLength) { 5538 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5539 Path.slice(0, PathLength))) { 5540 case ConstructionPhase::Bases: 5541 case ConstructionPhase::DestroyingBases: 5542 // We're constructing or destroying a base class. This is not the dynamic 5543 // type. 5544 break; 5545 5546 case ConstructionPhase::None: 5547 case ConstructionPhase::AfterBases: 5548 case ConstructionPhase::AfterFields: 5549 case ConstructionPhase::Destroying: 5550 // We've finished constructing the base classes and not yet started 5551 // destroying them again, so this is the dynamic type. 5552 return DynamicType{getBaseClassType(This.Designator, PathLength), 5553 PathLength}; 5554 } 5555 } 5556 5557 // CWG issue 1517: we're constructing a base class of the object described by 5558 // 'This', so that object has not yet begun its period of construction and 5559 // any polymorphic operation on it results in undefined behavior. 5560 Info.FFDiag(E); 5561 return None; 5562 } 5563 5564 /// Perform virtual dispatch. 5565 static const CXXMethodDecl *HandleVirtualDispatch( 5566 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5567 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5568 Optional<DynamicType> DynType = ComputeDynamicType( 5569 Info, E, This, 5570 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5571 if (!DynType) 5572 return nullptr; 5573 5574 // Find the final overrider. It must be declared in one of the classes on the 5575 // path from the dynamic type to the static type. 5576 // FIXME: If we ever allow literal types to have virtual base classes, that 5577 // won't be true. 5578 const CXXMethodDecl *Callee = Found; 5579 unsigned PathLength = DynType->PathLength; 5580 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5581 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5582 const CXXMethodDecl *Overrider = 5583 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5584 if (Overrider) { 5585 Callee = Overrider; 5586 break; 5587 } 5588 } 5589 5590 // C++2a [class.abstract]p6: 5591 // the effect of making a virtual call to a pure virtual function [...] is 5592 // undefined 5593 if (Callee->isPure()) { 5594 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5595 Info.Note(Callee->getLocation(), diag::note_declared_at); 5596 return nullptr; 5597 } 5598 5599 // If necessary, walk the rest of the path to determine the sequence of 5600 // covariant adjustment steps to apply. 5601 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5602 Found->getReturnType())) { 5603 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5604 for (unsigned CovariantPathLength = PathLength + 1; 5605 CovariantPathLength != This.Designator.Entries.size(); 5606 ++CovariantPathLength) { 5607 const CXXRecordDecl *NextClass = 5608 getBaseClassType(This.Designator, CovariantPathLength); 5609 const CXXMethodDecl *Next = 5610 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5611 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5612 Next->getReturnType(), CovariantAdjustmentPath.back())) 5613 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5614 } 5615 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5616 CovariantAdjustmentPath.back())) 5617 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5618 } 5619 5620 // Perform 'this' adjustment. 5621 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5622 return nullptr; 5623 5624 return Callee; 5625 } 5626 5627 /// Perform the adjustment from a value returned by a virtual function to 5628 /// a value of the statically expected type, which may be a pointer or 5629 /// reference to a base class of the returned type. 5630 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5631 APValue &Result, 5632 ArrayRef<QualType> Path) { 5633 assert(Result.isLValue() && 5634 "unexpected kind of APValue for covariant return"); 5635 if (Result.isNullPointer()) 5636 return true; 5637 5638 LValue LVal; 5639 LVal.setFrom(Info.Ctx, Result); 5640 5641 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5642 for (unsigned I = 1; I != Path.size(); ++I) { 5643 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5644 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5645 if (OldClass != NewClass && 5646 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5647 return false; 5648 OldClass = NewClass; 5649 } 5650 5651 LVal.moveInto(Result); 5652 return true; 5653 } 5654 5655 /// Determine whether \p Base, which is known to be a direct base class of 5656 /// \p Derived, is a public base class. 5657 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5658 const CXXRecordDecl *Base) { 5659 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5660 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5661 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5662 return BaseSpec.getAccessSpecifier() == AS_public; 5663 } 5664 llvm_unreachable("Base is not a direct base of Derived"); 5665 } 5666 5667 /// Apply the given dynamic cast operation on the provided lvalue. 5668 /// 5669 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5670 /// to find a suitable target subobject. 5671 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5672 LValue &Ptr) { 5673 // We can't do anything with a non-symbolic pointer value. 5674 SubobjectDesignator &D = Ptr.Designator; 5675 if (D.Invalid) 5676 return false; 5677 5678 // C++ [expr.dynamic.cast]p6: 5679 // If v is a null pointer value, the result is a null pointer value. 5680 if (Ptr.isNullPointer() && !E->isGLValue()) 5681 return true; 5682 5683 // For all the other cases, we need the pointer to point to an object within 5684 // its lifetime / period of construction / destruction, and we need to know 5685 // its dynamic type. 5686 Optional<DynamicType> DynType = 5687 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5688 if (!DynType) 5689 return false; 5690 5691 // C++ [expr.dynamic.cast]p7: 5692 // If T is "pointer to cv void", then the result is a pointer to the most 5693 // derived object 5694 if (E->getType()->isVoidPointerType()) 5695 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5696 5697 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5698 assert(C && "dynamic_cast target is not void pointer nor class"); 5699 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5700 5701 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5702 // C++ [expr.dynamic.cast]p9: 5703 if (!E->isGLValue()) { 5704 // The value of a failed cast to pointer type is the null pointer value 5705 // of the required result type. 5706 Ptr.setNull(Info.Ctx, E->getType()); 5707 return true; 5708 } 5709 5710 // A failed cast to reference type throws [...] std::bad_cast. 5711 unsigned DiagKind; 5712 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5713 DynType->Type->isDerivedFrom(C))) 5714 DiagKind = 0; 5715 else if (!Paths || Paths->begin() == Paths->end()) 5716 DiagKind = 1; 5717 else if (Paths->isAmbiguous(CQT)) 5718 DiagKind = 2; 5719 else { 5720 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5721 DiagKind = 3; 5722 } 5723 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5724 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5725 << Info.Ctx.getRecordType(DynType->Type) 5726 << E->getType().getUnqualifiedType(); 5727 return false; 5728 }; 5729 5730 // Runtime check, phase 1: 5731 // Walk from the base subobject towards the derived object looking for the 5732 // target type. 5733 for (int PathLength = Ptr.Designator.Entries.size(); 5734 PathLength >= (int)DynType->PathLength; --PathLength) { 5735 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5736 if (declaresSameEntity(Class, C)) 5737 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5738 // We can only walk across public inheritance edges. 5739 if (PathLength > (int)DynType->PathLength && 5740 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5741 Class)) 5742 return RuntimeCheckFailed(nullptr); 5743 } 5744 5745 // Runtime check, phase 2: 5746 // Search the dynamic type for an unambiguous public base of type C. 5747 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5748 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5749 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5750 Paths.front().Access == AS_public) { 5751 // Downcast to the dynamic type... 5752 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5753 return false; 5754 // ... then upcast to the chosen base class subobject. 5755 for (CXXBasePathElement &Elem : Paths.front()) 5756 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5757 return false; 5758 return true; 5759 } 5760 5761 // Otherwise, the runtime check fails. 5762 return RuntimeCheckFailed(&Paths); 5763 } 5764 5765 namespace { 5766 struct StartLifetimeOfUnionMemberHandler { 5767 EvalInfo &Info; 5768 const Expr *LHSExpr; 5769 const FieldDecl *Field; 5770 bool DuringInit; 5771 bool Failed = false; 5772 static const AccessKinds AccessKind = AK_Assign; 5773 5774 typedef bool result_type; 5775 bool failed() { return Failed; } 5776 bool found(APValue &Subobj, QualType SubobjType) { 5777 // We are supposed to perform no initialization but begin the lifetime of 5778 // the object. We interpret that as meaning to do what default 5779 // initialization of the object would do if all constructors involved were 5780 // trivial: 5781 // * All base, non-variant member, and array element subobjects' lifetimes 5782 // begin 5783 // * No variant members' lifetimes begin 5784 // * All scalar subobjects whose lifetimes begin have indeterminate values 5785 assert(SubobjType->isUnionType()); 5786 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5787 // This union member is already active. If it's also in-lifetime, there's 5788 // nothing to do. 5789 if (Subobj.getUnionValue().hasValue()) 5790 return true; 5791 } else if (DuringInit) { 5792 // We're currently in the process of initializing a different union 5793 // member. If we carried on, that initialization would attempt to 5794 // store to an inactive union member, resulting in undefined behavior. 5795 Info.FFDiag(LHSExpr, 5796 diag::note_constexpr_union_member_change_during_init); 5797 return false; 5798 } 5799 APValue Result; 5800 Failed = !getDefaultInitValue(Field->getType(), Result); 5801 Subobj.setUnion(Field, Result); 5802 return true; 5803 } 5804 bool found(APSInt &Value, QualType SubobjType) { 5805 llvm_unreachable("wrong value kind for union object"); 5806 } 5807 bool found(APFloat &Value, QualType SubobjType) { 5808 llvm_unreachable("wrong value kind for union object"); 5809 } 5810 }; 5811 } // end anonymous namespace 5812 5813 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5814 5815 /// Handle a builtin simple-assignment or a call to a trivial assignment 5816 /// operator whose left-hand side might involve a union member access. If it 5817 /// does, implicitly start the lifetime of any accessed union elements per 5818 /// C++20 [class.union]5. 5819 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5820 const LValue &LHS) { 5821 if (LHS.InvalidBase || LHS.Designator.Invalid) 5822 return false; 5823 5824 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5825 // C++ [class.union]p5: 5826 // define the set S(E) of subexpressions of E as follows: 5827 unsigned PathLength = LHS.Designator.Entries.size(); 5828 for (const Expr *E = LHSExpr; E != nullptr;) { 5829 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5830 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5831 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5832 // Note that we can't implicitly start the lifetime of a reference, 5833 // so we don't need to proceed any further if we reach one. 5834 if (!FD || FD->getType()->isReferenceType()) 5835 break; 5836 5837 // ... and also contains A.B if B names a union member ... 5838 if (FD->getParent()->isUnion()) { 5839 // ... of a non-class, non-array type, or of a class type with a 5840 // trivial default constructor that is not deleted, or an array of 5841 // such types. 5842 auto *RD = 5843 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5844 if (!RD || RD->hasTrivialDefaultConstructor()) 5845 UnionPathLengths.push_back({PathLength - 1, FD}); 5846 } 5847 5848 E = ME->getBase(); 5849 --PathLength; 5850 assert(declaresSameEntity(FD, 5851 LHS.Designator.Entries[PathLength] 5852 .getAsBaseOrMember().getPointer())); 5853 5854 // -- If E is of the form A[B] and is interpreted as a built-in array 5855 // subscripting operator, S(E) is [S(the array operand, if any)]. 5856 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5857 // Step over an ArrayToPointerDecay implicit cast. 5858 auto *Base = ASE->getBase()->IgnoreImplicit(); 5859 if (!Base->getType()->isArrayType()) 5860 break; 5861 5862 E = Base; 5863 --PathLength; 5864 5865 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5866 // Step over a derived-to-base conversion. 5867 E = ICE->getSubExpr(); 5868 if (ICE->getCastKind() == CK_NoOp) 5869 continue; 5870 if (ICE->getCastKind() != CK_DerivedToBase && 5871 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5872 break; 5873 // Walk path backwards as we walk up from the base to the derived class. 5874 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5875 --PathLength; 5876 (void)Elt; 5877 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5878 LHS.Designator.Entries[PathLength] 5879 .getAsBaseOrMember().getPointer())); 5880 } 5881 5882 // -- Otherwise, S(E) is empty. 5883 } else { 5884 break; 5885 } 5886 } 5887 5888 // Common case: no unions' lifetimes are started. 5889 if (UnionPathLengths.empty()) 5890 return true; 5891 5892 // if modification of X [would access an inactive union member], an object 5893 // of the type of X is implicitly created 5894 CompleteObject Obj = 5895 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5896 if (!Obj) 5897 return false; 5898 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5899 llvm::reverse(UnionPathLengths)) { 5900 // Form a designator for the union object. 5901 SubobjectDesignator D = LHS.Designator; 5902 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5903 5904 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5905 ConstructionPhase::AfterBases; 5906 StartLifetimeOfUnionMemberHandler StartLifetime{ 5907 Info, LHSExpr, LengthAndField.second, DuringInit}; 5908 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5909 return false; 5910 } 5911 5912 return true; 5913 } 5914 5915 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5916 CallRef Call, EvalInfo &Info, 5917 bool NonNull = false) { 5918 LValue LV; 5919 // Create the parameter slot and register its destruction. For a vararg 5920 // argument, create a temporary. 5921 // FIXME: For calling conventions that destroy parameters in the callee, 5922 // should we consider performing destruction when the function returns 5923 // instead? 5924 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5925 : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5926 ScopeKind::Call, LV); 5927 if (!EvaluateInPlace(V, Info, LV, Arg)) 5928 return false; 5929 5930 // Passing a null pointer to an __attribute__((nonnull)) parameter results in 5931 // undefined behavior, so is non-constant. 5932 if (NonNull && V.isLValue() && V.isNullPointer()) { 5933 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 5934 return false; 5935 } 5936 5937 return true; 5938 } 5939 5940 /// Evaluate the arguments to a function call. 5941 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 5942 EvalInfo &Info, const FunctionDecl *Callee, 5943 bool RightToLeft = false) { 5944 bool Success = true; 5945 llvm::SmallBitVector ForbiddenNullArgs; 5946 if (Callee->hasAttr<NonNullAttr>()) { 5947 ForbiddenNullArgs.resize(Args.size()); 5948 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5949 if (!Attr->args_size()) { 5950 ForbiddenNullArgs.set(); 5951 break; 5952 } else 5953 for (auto Idx : Attr->args()) { 5954 unsigned ASTIdx = Idx.getASTIndex(); 5955 if (ASTIdx >= Args.size()) 5956 continue; 5957 ForbiddenNullArgs[ASTIdx] = 1; 5958 } 5959 } 5960 } 5961 for (unsigned I = 0; I < Args.size(); I++) { 5962 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 5963 const ParmVarDecl *PVD = 5964 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 5965 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 5966 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 5967 // If we're checking for a potential constant expression, evaluate all 5968 // initializers even if some of them fail. 5969 if (!Info.noteFailure()) 5970 return false; 5971 Success = false; 5972 } 5973 } 5974 return Success; 5975 } 5976 5977 /// Perform a trivial copy from Param, which is the parameter of a copy or move 5978 /// constructor or assignment operator. 5979 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 5980 const Expr *E, APValue &Result, 5981 bool CopyObjectRepresentation) { 5982 // Find the reference argument. 5983 CallStackFrame *Frame = Info.CurrentCall; 5984 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 5985 if (!RefValue) { 5986 Info.FFDiag(E); 5987 return false; 5988 } 5989 5990 // Copy out the contents of the RHS object. 5991 LValue RefLValue; 5992 RefLValue.setFrom(Info.Ctx, *RefValue); 5993 return handleLValueToRValueConversion( 5994 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 5995 CopyObjectRepresentation); 5996 } 5997 5998 /// Evaluate a function call. 5999 static bool HandleFunctionCall(SourceLocation CallLoc, 6000 const FunctionDecl *Callee, const LValue *This, 6001 ArrayRef<const Expr *> Args, CallRef Call, 6002 const Stmt *Body, EvalInfo &Info, 6003 APValue &Result, const LValue *ResultSlot) { 6004 if (!Info.CheckCallLimit(CallLoc)) 6005 return false; 6006 6007 CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6008 6009 // For a trivial copy or move assignment, perform an APValue copy. This is 6010 // essential for unions, where the operations performed by the assignment 6011 // operator cannot be represented as statements. 6012 // 6013 // Skip this for non-union classes with no fields; in that case, the defaulted 6014 // copy/move does not actually read the object. 6015 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6016 if (MD && MD->isDefaulted() && 6017 (MD->getParent()->isUnion() || 6018 (MD->isTrivial() && 6019 isReadByLvalueToRvalueConversion(MD->getParent())))) { 6020 assert(This && 6021 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6022 APValue RHSValue; 6023 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6024 MD->getParent()->isUnion())) 6025 return false; 6026 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6027 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6028 return false; 6029 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6030 RHSValue)) 6031 return false; 6032 This->moveInto(Result); 6033 return true; 6034 } else if (MD && isLambdaCallOperator(MD)) { 6035 // We're in a lambda; determine the lambda capture field maps unless we're 6036 // just constexpr checking a lambda's call operator. constexpr checking is 6037 // done before the captures have been added to the closure object (unless 6038 // we're inferring constexpr-ness), so we don't have access to them in this 6039 // case. But since we don't need the captures to constexpr check, we can 6040 // just ignore them. 6041 if (!Info.checkingPotentialConstantExpression()) 6042 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6043 Frame.LambdaThisCaptureField); 6044 } 6045 6046 StmtResult Ret = {Result, ResultSlot}; 6047 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6048 if (ESR == ESR_Succeeded) { 6049 if (Callee->getReturnType()->isVoidType()) 6050 return true; 6051 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6052 } 6053 return ESR == ESR_Returned; 6054 } 6055 6056 /// Evaluate a constructor call. 6057 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6058 CallRef Call, 6059 const CXXConstructorDecl *Definition, 6060 EvalInfo &Info, APValue &Result) { 6061 SourceLocation CallLoc = E->getExprLoc(); 6062 if (!Info.CheckCallLimit(CallLoc)) 6063 return false; 6064 6065 const CXXRecordDecl *RD = Definition->getParent(); 6066 if (RD->getNumVBases()) { 6067 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6068 return false; 6069 } 6070 6071 EvalInfo::EvaluatingConstructorRAII EvalObj( 6072 Info, 6073 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6074 RD->getNumBases()); 6075 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6076 6077 // FIXME: Creating an APValue just to hold a nonexistent return value is 6078 // wasteful. 6079 APValue RetVal; 6080 StmtResult Ret = {RetVal, nullptr}; 6081 6082 // If it's a delegating constructor, delegate. 6083 if (Definition->isDelegatingConstructor()) { 6084 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6085 { 6086 FullExpressionRAII InitScope(Info); 6087 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6088 !InitScope.destroy()) 6089 return false; 6090 } 6091 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6092 } 6093 6094 // For a trivial copy or move constructor, perform an APValue copy. This is 6095 // essential for unions (or classes with anonymous union members), where the 6096 // operations performed by the constructor cannot be represented by 6097 // ctor-initializers. 6098 // 6099 // Skip this for empty non-union classes; we should not perform an 6100 // lvalue-to-rvalue conversion on them because their copy constructor does not 6101 // actually read them. 6102 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6103 (Definition->getParent()->isUnion() || 6104 (Definition->isTrivial() && 6105 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6106 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6107 Definition->getParent()->isUnion()); 6108 } 6109 6110 // Reserve space for the struct members. 6111 if (!Result.hasValue()) { 6112 if (!RD->isUnion()) 6113 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6114 std::distance(RD->field_begin(), RD->field_end())); 6115 else 6116 // A union starts with no active member. 6117 Result = APValue((const FieldDecl*)nullptr); 6118 } 6119 6120 if (RD->isInvalidDecl()) return false; 6121 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6122 6123 // A scope for temporaries lifetime-extended by reference members. 6124 BlockScopeRAII LifetimeExtendedScope(Info); 6125 6126 bool Success = true; 6127 unsigned BasesSeen = 0; 6128 #ifndef NDEBUG 6129 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6130 #endif 6131 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6132 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6133 // We might be initializing the same field again if this is an indirect 6134 // field initialization. 6135 if (FieldIt == RD->field_end() || 6136 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6137 assert(Indirect && "fields out of order?"); 6138 return; 6139 } 6140 6141 // Default-initialize any fields with no explicit initializer. 6142 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6143 assert(FieldIt != RD->field_end() && "missing field?"); 6144 if (!FieldIt->isUnnamedBitfield()) 6145 Success &= getDefaultInitValue( 6146 FieldIt->getType(), 6147 Result.getStructField(FieldIt->getFieldIndex())); 6148 } 6149 ++FieldIt; 6150 }; 6151 for (const auto *I : Definition->inits()) { 6152 LValue Subobject = This; 6153 LValue SubobjectParent = This; 6154 APValue *Value = &Result; 6155 6156 // Determine the subobject to initialize. 6157 FieldDecl *FD = nullptr; 6158 if (I->isBaseInitializer()) { 6159 QualType BaseType(I->getBaseClass(), 0); 6160 #ifndef NDEBUG 6161 // Non-virtual base classes are initialized in the order in the class 6162 // definition. We have already checked for virtual base classes. 6163 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6164 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6165 "base class initializers not in expected order"); 6166 ++BaseIt; 6167 #endif 6168 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6169 BaseType->getAsCXXRecordDecl(), &Layout)) 6170 return false; 6171 Value = &Result.getStructBase(BasesSeen++); 6172 } else if ((FD = I->getMember())) { 6173 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6174 return false; 6175 if (RD->isUnion()) { 6176 Result = APValue(FD); 6177 Value = &Result.getUnionValue(); 6178 } else { 6179 SkipToField(FD, false); 6180 Value = &Result.getStructField(FD->getFieldIndex()); 6181 } 6182 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6183 // Walk the indirect field decl's chain to find the object to initialize, 6184 // and make sure we've initialized every step along it. 6185 auto IndirectFieldChain = IFD->chain(); 6186 for (auto *C : IndirectFieldChain) { 6187 FD = cast<FieldDecl>(C); 6188 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6189 // Switch the union field if it differs. This happens if we had 6190 // preceding zero-initialization, and we're now initializing a union 6191 // subobject other than the first. 6192 // FIXME: In this case, the values of the other subobjects are 6193 // specified, since zero-initialization sets all padding bits to zero. 6194 if (!Value->hasValue() || 6195 (Value->isUnion() && Value->getUnionField() != FD)) { 6196 if (CD->isUnion()) 6197 *Value = APValue(FD); 6198 else 6199 // FIXME: This immediately starts the lifetime of all members of 6200 // an anonymous struct. It would be preferable to strictly start 6201 // member lifetime in initialization order. 6202 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6203 } 6204 // Store Subobject as its parent before updating it for the last element 6205 // in the chain. 6206 if (C == IndirectFieldChain.back()) 6207 SubobjectParent = Subobject; 6208 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6209 return false; 6210 if (CD->isUnion()) 6211 Value = &Value->getUnionValue(); 6212 else { 6213 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6214 SkipToField(FD, true); 6215 Value = &Value->getStructField(FD->getFieldIndex()); 6216 } 6217 } 6218 } else { 6219 llvm_unreachable("unknown base initializer kind"); 6220 } 6221 6222 // Need to override This for implicit field initializers as in this case 6223 // This refers to innermost anonymous struct/union containing initializer, 6224 // not to currently constructed class. 6225 const Expr *Init = I->getInit(); 6226 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6227 isa<CXXDefaultInitExpr>(Init)); 6228 FullExpressionRAII InitScope(Info); 6229 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6230 (FD && FD->isBitField() && 6231 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6232 // If we're checking for a potential constant expression, evaluate all 6233 // initializers even if some of them fail. 6234 if (!Info.noteFailure()) 6235 return false; 6236 Success = false; 6237 } 6238 6239 // This is the point at which the dynamic type of the object becomes this 6240 // class type. 6241 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6242 EvalObj.finishedConstructingBases(); 6243 } 6244 6245 // Default-initialize any remaining fields. 6246 if (!RD->isUnion()) { 6247 for (; FieldIt != RD->field_end(); ++FieldIt) { 6248 if (!FieldIt->isUnnamedBitfield()) 6249 Success &= getDefaultInitValue( 6250 FieldIt->getType(), 6251 Result.getStructField(FieldIt->getFieldIndex())); 6252 } 6253 } 6254 6255 EvalObj.finishedConstructingFields(); 6256 6257 return Success && 6258 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6259 LifetimeExtendedScope.destroy(); 6260 } 6261 6262 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6263 ArrayRef<const Expr*> Args, 6264 const CXXConstructorDecl *Definition, 6265 EvalInfo &Info, APValue &Result) { 6266 CallScopeRAII CallScope(Info); 6267 CallRef Call = Info.CurrentCall->createCall(Definition); 6268 if (!EvaluateArgs(Args, Call, Info, Definition)) 6269 return false; 6270 6271 return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6272 CallScope.destroy(); 6273 } 6274 6275 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6276 const LValue &This, APValue &Value, 6277 QualType T) { 6278 // Objects can only be destroyed while they're within their lifetimes. 6279 // FIXME: We have no representation for whether an object of type nullptr_t 6280 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6281 // as indeterminate instead? 6282 if (Value.isAbsent() && !T->isNullPtrType()) { 6283 APValue Printable; 6284 This.moveInto(Printable); 6285 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6286 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6287 return false; 6288 } 6289 6290 // Invent an expression for location purposes. 6291 // FIXME: We shouldn't need to do this. 6292 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6293 6294 // For arrays, destroy elements right-to-left. 6295 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6296 uint64_t Size = CAT->getSize().getZExtValue(); 6297 QualType ElemT = CAT->getElementType(); 6298 6299 LValue ElemLV = This; 6300 ElemLV.addArray(Info, &LocE, CAT); 6301 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6302 return false; 6303 6304 // Ensure that we have actual array elements available to destroy; the 6305 // destructors might mutate the value, so we can't run them on the array 6306 // filler. 6307 if (Size && Size > Value.getArrayInitializedElts()) 6308 expandArray(Value, Value.getArraySize() - 1); 6309 6310 for (; Size != 0; --Size) { 6311 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6312 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6313 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6314 return false; 6315 } 6316 6317 // End the lifetime of this array now. 6318 Value = APValue(); 6319 return true; 6320 } 6321 6322 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6323 if (!RD) { 6324 if (T.isDestructedType()) { 6325 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6326 return false; 6327 } 6328 6329 Value = APValue(); 6330 return true; 6331 } 6332 6333 if (RD->getNumVBases()) { 6334 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6335 return false; 6336 } 6337 6338 const CXXDestructorDecl *DD = RD->getDestructor(); 6339 if (!DD && !RD->hasTrivialDestructor()) { 6340 Info.FFDiag(CallLoc); 6341 return false; 6342 } 6343 6344 if (!DD || DD->isTrivial() || 6345 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6346 // A trivial destructor just ends the lifetime of the object. Check for 6347 // this case before checking for a body, because we might not bother 6348 // building a body for a trivial destructor. Note that it doesn't matter 6349 // whether the destructor is constexpr in this case; all trivial 6350 // destructors are constexpr. 6351 // 6352 // If an anonymous union would be destroyed, some enclosing destructor must 6353 // have been explicitly defined, and the anonymous union destruction should 6354 // have no effect. 6355 Value = APValue(); 6356 return true; 6357 } 6358 6359 if (!Info.CheckCallLimit(CallLoc)) 6360 return false; 6361 6362 const FunctionDecl *Definition = nullptr; 6363 const Stmt *Body = DD->getBody(Definition); 6364 6365 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6366 return false; 6367 6368 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6369 6370 // We're now in the period of destruction of this object. 6371 unsigned BasesLeft = RD->getNumBases(); 6372 EvalInfo::EvaluatingDestructorRAII EvalObj( 6373 Info, 6374 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6375 if (!EvalObj.DidInsert) { 6376 // C++2a [class.dtor]p19: 6377 // the behavior is undefined if the destructor is invoked for an object 6378 // whose lifetime has ended 6379 // (Note that formally the lifetime ends when the period of destruction 6380 // begins, even though certain uses of the object remain valid until the 6381 // period of destruction ends.) 6382 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6383 return false; 6384 } 6385 6386 // FIXME: Creating an APValue just to hold a nonexistent return value is 6387 // wasteful. 6388 APValue RetVal; 6389 StmtResult Ret = {RetVal, nullptr}; 6390 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6391 return false; 6392 6393 // A union destructor does not implicitly destroy its members. 6394 if (RD->isUnion()) 6395 return true; 6396 6397 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6398 6399 // We don't have a good way to iterate fields in reverse, so collect all the 6400 // fields first and then walk them backwards. 6401 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6402 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6403 if (FD->isUnnamedBitfield()) 6404 continue; 6405 6406 LValue Subobject = This; 6407 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6408 return false; 6409 6410 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6411 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6412 FD->getType())) 6413 return false; 6414 } 6415 6416 if (BasesLeft != 0) 6417 EvalObj.startedDestroyingBases(); 6418 6419 // Destroy base classes in reverse order. 6420 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6421 --BasesLeft; 6422 6423 QualType BaseType = Base.getType(); 6424 LValue Subobject = This; 6425 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6426 BaseType->getAsCXXRecordDecl(), &Layout)) 6427 return false; 6428 6429 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6430 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6431 BaseType)) 6432 return false; 6433 } 6434 assert(BasesLeft == 0 && "NumBases was wrong?"); 6435 6436 // The period of destruction ends now. The object is gone. 6437 Value = APValue(); 6438 return true; 6439 } 6440 6441 namespace { 6442 struct DestroyObjectHandler { 6443 EvalInfo &Info; 6444 const Expr *E; 6445 const LValue &This; 6446 const AccessKinds AccessKind; 6447 6448 typedef bool result_type; 6449 bool failed() { return false; } 6450 bool found(APValue &Subobj, QualType SubobjType) { 6451 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6452 SubobjType); 6453 } 6454 bool found(APSInt &Value, QualType SubobjType) { 6455 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6456 return false; 6457 } 6458 bool found(APFloat &Value, QualType SubobjType) { 6459 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6460 return false; 6461 } 6462 }; 6463 } 6464 6465 /// Perform a destructor or pseudo-destructor call on the given object, which 6466 /// might in general not be a complete object. 6467 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6468 const LValue &This, QualType ThisType) { 6469 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6470 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6471 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6472 } 6473 6474 /// Destroy and end the lifetime of the given complete object. 6475 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6476 APValue::LValueBase LVBase, APValue &Value, 6477 QualType T) { 6478 // If we've had an unmodeled side-effect, we can't rely on mutable state 6479 // (such as the object we're about to destroy) being correct. 6480 if (Info.EvalStatus.HasSideEffects) 6481 return false; 6482 6483 LValue LV; 6484 LV.set({LVBase}); 6485 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6486 } 6487 6488 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6489 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6490 LValue &Result) { 6491 if (Info.checkingPotentialConstantExpression() || 6492 Info.SpeculativeEvaluationDepth) 6493 return false; 6494 6495 // This is permitted only within a call to std::allocator<T>::allocate. 6496 auto Caller = Info.getStdAllocatorCaller("allocate"); 6497 if (!Caller) { 6498 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6499 ? diag::note_constexpr_new_untyped 6500 : diag::note_constexpr_new); 6501 return false; 6502 } 6503 6504 QualType ElemType = Caller.ElemType; 6505 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6506 Info.FFDiag(E->getExprLoc(), 6507 diag::note_constexpr_new_not_complete_object_type) 6508 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6509 return false; 6510 } 6511 6512 APSInt ByteSize; 6513 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6514 return false; 6515 bool IsNothrow = false; 6516 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6517 EvaluateIgnoredValue(Info, E->getArg(I)); 6518 IsNothrow |= E->getType()->isNothrowT(); 6519 } 6520 6521 CharUnits ElemSize; 6522 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6523 return false; 6524 APInt Size, Remainder; 6525 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6526 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6527 if (Remainder != 0) { 6528 // This likely indicates a bug in the implementation of 'std::allocator'. 6529 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6530 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6531 return false; 6532 } 6533 6534 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6535 if (IsNothrow) { 6536 Result.setNull(Info.Ctx, E->getType()); 6537 return true; 6538 } 6539 6540 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6541 return false; 6542 } 6543 6544 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6545 ArrayType::Normal, 0); 6546 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6547 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6548 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6549 return true; 6550 } 6551 6552 static bool hasVirtualDestructor(QualType T) { 6553 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6554 if (CXXDestructorDecl *DD = RD->getDestructor()) 6555 return DD->isVirtual(); 6556 return false; 6557 } 6558 6559 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6560 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6561 if (CXXDestructorDecl *DD = RD->getDestructor()) 6562 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6563 return nullptr; 6564 } 6565 6566 /// Check that the given object is a suitable pointer to a heap allocation that 6567 /// still exists and is of the right kind for the purpose of a deletion. 6568 /// 6569 /// On success, returns the heap allocation to deallocate. On failure, produces 6570 /// a diagnostic and returns None. 6571 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6572 const LValue &Pointer, 6573 DynAlloc::Kind DeallocKind) { 6574 auto PointerAsString = [&] { 6575 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6576 }; 6577 6578 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6579 if (!DA) { 6580 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6581 << PointerAsString(); 6582 if (Pointer.Base) 6583 NoteLValueLocation(Info, Pointer.Base); 6584 return None; 6585 } 6586 6587 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6588 if (!Alloc) { 6589 Info.FFDiag(E, diag::note_constexpr_double_delete); 6590 return None; 6591 } 6592 6593 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6594 if (DeallocKind != (*Alloc)->getKind()) { 6595 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6596 << DeallocKind << (*Alloc)->getKind() << AllocType; 6597 NoteLValueLocation(Info, Pointer.Base); 6598 return None; 6599 } 6600 6601 bool Subobject = false; 6602 if (DeallocKind == DynAlloc::New) { 6603 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6604 Pointer.Designator.isOnePastTheEnd(); 6605 } else { 6606 Subobject = Pointer.Designator.Entries.size() != 1 || 6607 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6608 } 6609 if (Subobject) { 6610 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6611 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6612 return None; 6613 } 6614 6615 return Alloc; 6616 } 6617 6618 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6619 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6620 if (Info.checkingPotentialConstantExpression() || 6621 Info.SpeculativeEvaluationDepth) 6622 return false; 6623 6624 // This is permitted only within a call to std::allocator<T>::deallocate. 6625 if (!Info.getStdAllocatorCaller("deallocate")) { 6626 Info.FFDiag(E->getExprLoc()); 6627 return true; 6628 } 6629 6630 LValue Pointer; 6631 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6632 return false; 6633 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6634 EvaluateIgnoredValue(Info, E->getArg(I)); 6635 6636 if (Pointer.Designator.Invalid) 6637 return false; 6638 6639 // Deleting a null pointer has no effect. 6640 if (Pointer.isNullPointer()) 6641 return true; 6642 6643 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6644 return false; 6645 6646 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6647 return true; 6648 } 6649 6650 //===----------------------------------------------------------------------===// 6651 // Generic Evaluation 6652 //===----------------------------------------------------------------------===// 6653 namespace { 6654 6655 class BitCastBuffer { 6656 // FIXME: We're going to need bit-level granularity when we support 6657 // bit-fields. 6658 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6659 // we don't support a host or target where that is the case. Still, we should 6660 // use a more generic type in case we ever do. 6661 SmallVector<Optional<unsigned char>, 32> Bytes; 6662 6663 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6664 "Need at least 8 bit unsigned char"); 6665 6666 bool TargetIsLittleEndian; 6667 6668 public: 6669 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6670 : Bytes(Width.getQuantity()), 6671 TargetIsLittleEndian(TargetIsLittleEndian) {} 6672 6673 LLVM_NODISCARD 6674 bool readObject(CharUnits Offset, CharUnits Width, 6675 SmallVectorImpl<unsigned char> &Output) const { 6676 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6677 // If a byte of an integer is uninitialized, then the whole integer is 6678 // uninitalized. 6679 if (!Bytes[I.getQuantity()]) 6680 return false; 6681 Output.push_back(*Bytes[I.getQuantity()]); 6682 } 6683 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6684 std::reverse(Output.begin(), Output.end()); 6685 return true; 6686 } 6687 6688 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6689 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6690 std::reverse(Input.begin(), Input.end()); 6691 6692 size_t Index = 0; 6693 for (unsigned char Byte : Input) { 6694 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6695 Bytes[Offset.getQuantity() + Index] = Byte; 6696 ++Index; 6697 } 6698 } 6699 6700 size_t size() { return Bytes.size(); } 6701 }; 6702 6703 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6704 /// target would represent the value at runtime. 6705 class APValueToBufferConverter { 6706 EvalInfo &Info; 6707 BitCastBuffer Buffer; 6708 const CastExpr *BCE; 6709 6710 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6711 const CastExpr *BCE) 6712 : Info(Info), 6713 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6714 BCE(BCE) {} 6715 6716 bool visit(const APValue &Val, QualType Ty) { 6717 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6718 } 6719 6720 // Write out Val with type Ty into Buffer starting at Offset. 6721 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6722 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6723 6724 // As a special case, nullptr_t has an indeterminate value. 6725 if (Ty->isNullPtrType()) 6726 return true; 6727 6728 // Dig through Src to find the byte at SrcOffset. 6729 switch (Val.getKind()) { 6730 case APValue::Indeterminate: 6731 case APValue::None: 6732 return true; 6733 6734 case APValue::Int: 6735 return visitInt(Val.getInt(), Ty, Offset); 6736 case APValue::Float: 6737 return visitFloat(Val.getFloat(), Ty, Offset); 6738 case APValue::Array: 6739 return visitArray(Val, Ty, Offset); 6740 case APValue::Struct: 6741 return visitRecord(Val, Ty, Offset); 6742 6743 case APValue::ComplexInt: 6744 case APValue::ComplexFloat: 6745 case APValue::Vector: 6746 case APValue::FixedPoint: 6747 // FIXME: We should support these. 6748 6749 case APValue::Union: 6750 case APValue::MemberPointer: 6751 case APValue::AddrLabelDiff: { 6752 Info.FFDiag(BCE->getBeginLoc(), 6753 diag::note_constexpr_bit_cast_unsupported_type) 6754 << Ty; 6755 return false; 6756 } 6757 6758 case APValue::LValue: 6759 llvm_unreachable("LValue subobject in bit_cast?"); 6760 } 6761 llvm_unreachable("Unhandled APValue::ValueKind"); 6762 } 6763 6764 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6765 const RecordDecl *RD = Ty->getAsRecordDecl(); 6766 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6767 6768 // Visit the base classes. 6769 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6770 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6771 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6772 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6773 6774 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6775 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6776 return false; 6777 } 6778 } 6779 6780 // Visit the fields. 6781 unsigned FieldIdx = 0; 6782 for (FieldDecl *FD : RD->fields()) { 6783 if (FD->isBitField()) { 6784 Info.FFDiag(BCE->getBeginLoc(), 6785 diag::note_constexpr_bit_cast_unsupported_bitfield); 6786 return false; 6787 } 6788 6789 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6790 6791 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6792 "only bit-fields can have sub-char alignment"); 6793 CharUnits FieldOffset = 6794 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6795 QualType FieldTy = FD->getType(); 6796 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6797 return false; 6798 ++FieldIdx; 6799 } 6800 6801 return true; 6802 } 6803 6804 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6805 const auto *CAT = 6806 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6807 if (!CAT) 6808 return false; 6809 6810 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6811 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6812 unsigned ArraySize = Val.getArraySize(); 6813 // First, initialize the initialized elements. 6814 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6815 const APValue &SubObj = Val.getArrayInitializedElt(I); 6816 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6817 return false; 6818 } 6819 6820 // Next, initialize the rest of the array using the filler. 6821 if (Val.hasArrayFiller()) { 6822 const APValue &Filler = Val.getArrayFiller(); 6823 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6824 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6825 return false; 6826 } 6827 } 6828 6829 return true; 6830 } 6831 6832 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6833 APSInt AdjustedVal = Val; 6834 unsigned Width = AdjustedVal.getBitWidth(); 6835 if (Ty->isBooleanType()) { 6836 Width = Info.Ctx.getTypeSize(Ty); 6837 AdjustedVal = AdjustedVal.extend(Width); 6838 } 6839 6840 SmallVector<unsigned char, 8> Bytes(Width / 8); 6841 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6842 Buffer.writeObject(Offset, Bytes); 6843 return true; 6844 } 6845 6846 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6847 APSInt AsInt(Val.bitcastToAPInt()); 6848 return visitInt(AsInt, Ty, Offset); 6849 } 6850 6851 public: 6852 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6853 const CastExpr *BCE) { 6854 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6855 APValueToBufferConverter Converter(Info, DstSize, BCE); 6856 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6857 return None; 6858 return Converter.Buffer; 6859 } 6860 }; 6861 6862 /// Write an BitCastBuffer into an APValue. 6863 class BufferToAPValueConverter { 6864 EvalInfo &Info; 6865 const BitCastBuffer &Buffer; 6866 const CastExpr *BCE; 6867 6868 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6869 const CastExpr *BCE) 6870 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6871 6872 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6873 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6874 // Ideally this will be unreachable. 6875 llvm::NoneType unsupportedType(QualType Ty) { 6876 Info.FFDiag(BCE->getBeginLoc(), 6877 diag::note_constexpr_bit_cast_unsupported_type) 6878 << Ty; 6879 return None; 6880 } 6881 6882 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6883 Info.FFDiag(BCE->getBeginLoc(), 6884 diag::note_constexpr_bit_cast_unrepresentable_value) 6885 << Ty << Val.toString(/*Radix=*/10); 6886 return None; 6887 } 6888 6889 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6890 const EnumType *EnumSugar = nullptr) { 6891 if (T->isNullPtrType()) { 6892 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6893 return APValue((Expr *)nullptr, 6894 /*Offset=*/CharUnits::fromQuantity(NullValue), 6895 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6896 } 6897 6898 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6899 6900 // Work around floating point types that contain unused padding bytes. This 6901 // is really just `long double` on x86, which is the only fundamental type 6902 // with padding bytes. 6903 if (T->isRealFloatingType()) { 6904 const llvm::fltSemantics &Semantics = 6905 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6906 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6907 assert(NumBits % 8 == 0); 6908 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6909 if (NumBytes != SizeOf) 6910 SizeOf = NumBytes; 6911 } 6912 6913 SmallVector<uint8_t, 8> Bytes; 6914 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6915 // If this is std::byte or unsigned char, then its okay to store an 6916 // indeterminate value. 6917 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6918 bool IsUChar = 6919 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6920 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6921 if (!IsStdByte && !IsUChar) { 6922 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6923 Info.FFDiag(BCE->getExprLoc(), 6924 diag::note_constexpr_bit_cast_indet_dest) 6925 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6926 return None; 6927 } 6928 6929 return APValue::IndeterminateValue(); 6930 } 6931 6932 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6933 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6934 6935 if (T->isIntegralOrEnumerationType()) { 6936 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6937 6938 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 6939 if (IntWidth != Val.getBitWidth()) { 6940 APSInt Truncated = Val.trunc(IntWidth); 6941 if (Truncated.extend(Val.getBitWidth()) != Val) 6942 return unrepresentableValue(QualType(T, 0), Val); 6943 Val = Truncated; 6944 } 6945 6946 return APValue(Val); 6947 } 6948 6949 if (T->isRealFloatingType()) { 6950 const llvm::fltSemantics &Semantics = 6951 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6952 return APValue(APFloat(Semantics, Val)); 6953 } 6954 6955 return unsupportedType(QualType(T, 0)); 6956 } 6957 6958 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6959 const RecordDecl *RD = RTy->getAsRecordDecl(); 6960 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6961 6962 unsigned NumBases = 0; 6963 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6964 NumBases = CXXRD->getNumBases(); 6965 6966 APValue ResultVal(APValue::UninitStruct(), NumBases, 6967 std::distance(RD->field_begin(), RD->field_end())); 6968 6969 // Visit the base classes. 6970 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6971 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6972 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6973 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6974 if (BaseDecl->isEmpty() || 6975 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6976 continue; 6977 6978 Optional<APValue> SubObj = visitType( 6979 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6980 if (!SubObj) 6981 return None; 6982 ResultVal.getStructBase(I) = *SubObj; 6983 } 6984 } 6985 6986 // Visit the fields. 6987 unsigned FieldIdx = 0; 6988 for (FieldDecl *FD : RD->fields()) { 6989 // FIXME: We don't currently support bit-fields. A lot of the logic for 6990 // this is in CodeGen, so we need to factor it around. 6991 if (FD->isBitField()) { 6992 Info.FFDiag(BCE->getBeginLoc(), 6993 diag::note_constexpr_bit_cast_unsupported_bitfield); 6994 return None; 6995 } 6996 6997 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6998 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6999 7000 CharUnits FieldOffset = 7001 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7002 Offset; 7003 QualType FieldTy = FD->getType(); 7004 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7005 if (!SubObj) 7006 return None; 7007 ResultVal.getStructField(FieldIdx) = *SubObj; 7008 ++FieldIdx; 7009 } 7010 7011 return ResultVal; 7012 } 7013 7014 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7015 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7016 assert(!RepresentationType.isNull() && 7017 "enum forward decl should be caught by Sema"); 7018 const auto *AsBuiltin = 7019 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7020 // Recurse into the underlying type. Treat std::byte transparently as 7021 // unsigned char. 7022 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7023 } 7024 7025 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7026 size_t Size = Ty->getSize().getLimitedValue(); 7027 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7028 7029 APValue ArrayValue(APValue::UninitArray(), Size, Size); 7030 for (size_t I = 0; I != Size; ++I) { 7031 Optional<APValue> ElementValue = 7032 visitType(Ty->getElementType(), Offset + I * ElementWidth); 7033 if (!ElementValue) 7034 return None; 7035 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7036 } 7037 7038 return ArrayValue; 7039 } 7040 7041 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7042 return unsupportedType(QualType(Ty, 0)); 7043 } 7044 7045 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7046 QualType Can = Ty.getCanonicalType(); 7047 7048 switch (Can->getTypeClass()) { 7049 #define TYPE(Class, Base) \ 7050 case Type::Class: \ 7051 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7052 #define ABSTRACT_TYPE(Class, Base) 7053 #define NON_CANONICAL_TYPE(Class, Base) \ 7054 case Type::Class: \ 7055 llvm_unreachable("non-canonical type should be impossible!"); 7056 #define DEPENDENT_TYPE(Class, Base) \ 7057 case Type::Class: \ 7058 llvm_unreachable( \ 7059 "dependent types aren't supported in the constant evaluator!"); 7060 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7061 case Type::Class: \ 7062 llvm_unreachable("either dependent or not canonical!"); 7063 #include "clang/AST/TypeNodes.inc" 7064 } 7065 llvm_unreachable("Unhandled Type::TypeClass"); 7066 } 7067 7068 public: 7069 // Pull out a full value of type DstType. 7070 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7071 const CastExpr *BCE) { 7072 BufferToAPValueConverter Converter(Info, Buffer, BCE); 7073 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7074 } 7075 }; 7076 7077 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7078 QualType Ty, EvalInfo *Info, 7079 const ASTContext &Ctx, 7080 bool CheckingDest) { 7081 Ty = Ty.getCanonicalType(); 7082 7083 auto diag = [&](int Reason) { 7084 if (Info) 7085 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7086 << CheckingDest << (Reason == 4) << Reason; 7087 return false; 7088 }; 7089 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7090 if (Info) 7091 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7092 << NoteTy << Construct << Ty; 7093 return false; 7094 }; 7095 7096 if (Ty->isUnionType()) 7097 return diag(0); 7098 if (Ty->isPointerType()) 7099 return diag(1); 7100 if (Ty->isMemberPointerType()) 7101 return diag(2); 7102 if (Ty.isVolatileQualified()) 7103 return diag(3); 7104 7105 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7106 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7107 for (CXXBaseSpecifier &BS : CXXRD->bases()) 7108 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7109 CheckingDest)) 7110 return note(1, BS.getType(), BS.getBeginLoc()); 7111 } 7112 for (FieldDecl *FD : Record->fields()) { 7113 if (FD->getType()->isReferenceType()) 7114 return diag(4); 7115 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7116 CheckingDest)) 7117 return note(0, FD->getType(), FD->getBeginLoc()); 7118 } 7119 } 7120 7121 if (Ty->isArrayType() && 7122 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7123 Info, Ctx, CheckingDest)) 7124 return false; 7125 7126 return true; 7127 } 7128 7129 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7130 const ASTContext &Ctx, 7131 const CastExpr *BCE) { 7132 bool DestOK = checkBitCastConstexprEligibilityType( 7133 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7134 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7135 BCE->getBeginLoc(), 7136 BCE->getSubExpr()->getType(), Info, Ctx, false); 7137 return SourceOK; 7138 } 7139 7140 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7141 APValue &SourceValue, 7142 const CastExpr *BCE) { 7143 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7144 "no host or target supports non 8-bit chars"); 7145 assert(SourceValue.isLValue() && 7146 "LValueToRValueBitcast requires an lvalue operand!"); 7147 7148 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7149 return false; 7150 7151 LValue SourceLValue; 7152 APValue SourceRValue; 7153 SourceLValue.setFrom(Info.Ctx, SourceValue); 7154 if (!handleLValueToRValueConversion( 7155 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7156 SourceRValue, /*WantObjectRepresentation=*/true)) 7157 return false; 7158 7159 // Read out SourceValue into a char buffer. 7160 Optional<BitCastBuffer> Buffer = 7161 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7162 if (!Buffer) 7163 return false; 7164 7165 // Write out the buffer into a new APValue. 7166 Optional<APValue> MaybeDestValue = 7167 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7168 if (!MaybeDestValue) 7169 return false; 7170 7171 DestValue = std::move(*MaybeDestValue); 7172 return true; 7173 } 7174 7175 template <class Derived> 7176 class ExprEvaluatorBase 7177 : public ConstStmtVisitor<Derived, bool> { 7178 private: 7179 Derived &getDerived() { return static_cast<Derived&>(*this); } 7180 bool DerivedSuccess(const APValue &V, const Expr *E) { 7181 return getDerived().Success(V, E); 7182 } 7183 bool DerivedZeroInitialization(const Expr *E) { 7184 return getDerived().ZeroInitialization(E); 7185 } 7186 7187 // Check whether a conditional operator with a non-constant condition is a 7188 // potential constant expression. If neither arm is a potential constant 7189 // expression, then the conditional operator is not either. 7190 template<typename ConditionalOperator> 7191 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7192 assert(Info.checkingPotentialConstantExpression()); 7193 7194 // Speculatively evaluate both arms. 7195 SmallVector<PartialDiagnosticAt, 8> Diag; 7196 { 7197 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7198 StmtVisitorTy::Visit(E->getFalseExpr()); 7199 if (Diag.empty()) 7200 return; 7201 } 7202 7203 { 7204 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7205 Diag.clear(); 7206 StmtVisitorTy::Visit(E->getTrueExpr()); 7207 if (Diag.empty()) 7208 return; 7209 } 7210 7211 Error(E, diag::note_constexpr_conditional_never_const); 7212 } 7213 7214 7215 template<typename ConditionalOperator> 7216 bool HandleConditionalOperator(const ConditionalOperator *E) { 7217 bool BoolResult; 7218 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7219 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7220 CheckPotentialConstantConditional(E); 7221 return false; 7222 } 7223 if (Info.noteFailure()) { 7224 StmtVisitorTy::Visit(E->getTrueExpr()); 7225 StmtVisitorTy::Visit(E->getFalseExpr()); 7226 } 7227 return false; 7228 } 7229 7230 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7231 return StmtVisitorTy::Visit(EvalExpr); 7232 } 7233 7234 protected: 7235 EvalInfo &Info; 7236 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7237 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7238 7239 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7240 return Info.CCEDiag(E, D); 7241 } 7242 7243 bool ZeroInitialization(const Expr *E) { return Error(E); } 7244 7245 public: 7246 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7247 7248 EvalInfo &getEvalInfo() { return Info; } 7249 7250 /// Report an evaluation error. This should only be called when an error is 7251 /// first discovered. When propagating an error, just return false. 7252 bool Error(const Expr *E, diag::kind D) { 7253 Info.FFDiag(E, D); 7254 return false; 7255 } 7256 bool Error(const Expr *E) { 7257 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7258 } 7259 7260 bool VisitStmt(const Stmt *) { 7261 llvm_unreachable("Expression evaluator should not be called on stmts"); 7262 } 7263 bool VisitExpr(const Expr *E) { 7264 return Error(E); 7265 } 7266 7267 bool VisitConstantExpr(const ConstantExpr *E) { 7268 if (E->hasAPValueResult()) 7269 return DerivedSuccess(E->getAPValueResult(), E); 7270 7271 return StmtVisitorTy::Visit(E->getSubExpr()); 7272 } 7273 7274 bool VisitParenExpr(const ParenExpr *E) 7275 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7276 bool VisitUnaryExtension(const UnaryOperator *E) 7277 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7278 bool VisitUnaryPlus(const UnaryOperator *E) 7279 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7280 bool VisitChooseExpr(const ChooseExpr *E) 7281 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7282 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7283 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7284 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7285 { return StmtVisitorTy::Visit(E->getReplacement()); } 7286 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7287 TempVersionRAII RAII(*Info.CurrentCall); 7288 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7289 return StmtVisitorTy::Visit(E->getExpr()); 7290 } 7291 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7292 TempVersionRAII RAII(*Info.CurrentCall); 7293 // The initializer may not have been parsed yet, or might be erroneous. 7294 if (!E->getExpr()) 7295 return Error(E); 7296 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7297 return StmtVisitorTy::Visit(E->getExpr()); 7298 } 7299 7300 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7301 FullExpressionRAII Scope(Info); 7302 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7303 } 7304 7305 // Temporaries are registered when created, so we don't care about 7306 // CXXBindTemporaryExpr. 7307 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7308 return StmtVisitorTy::Visit(E->getSubExpr()); 7309 } 7310 7311 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7312 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7313 return static_cast<Derived*>(this)->VisitCastExpr(E); 7314 } 7315 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7316 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7317 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7318 return static_cast<Derived*>(this)->VisitCastExpr(E); 7319 } 7320 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7321 return static_cast<Derived*>(this)->VisitCastExpr(E); 7322 } 7323 7324 bool VisitBinaryOperator(const BinaryOperator *E) { 7325 switch (E->getOpcode()) { 7326 default: 7327 return Error(E); 7328 7329 case BO_Comma: 7330 VisitIgnoredValue(E->getLHS()); 7331 return StmtVisitorTy::Visit(E->getRHS()); 7332 7333 case BO_PtrMemD: 7334 case BO_PtrMemI: { 7335 LValue Obj; 7336 if (!HandleMemberPointerAccess(Info, E, Obj)) 7337 return false; 7338 APValue Result; 7339 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7340 return false; 7341 return DerivedSuccess(Result, E); 7342 } 7343 } 7344 } 7345 7346 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7347 return StmtVisitorTy::Visit(E->getSemanticForm()); 7348 } 7349 7350 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7351 // Evaluate and cache the common expression. We treat it as a temporary, 7352 // even though it's not quite the same thing. 7353 LValue CommonLV; 7354 if (!Evaluate(Info.CurrentCall->createTemporary( 7355 E->getOpaqueValue(), 7356 getStorageType(Info.Ctx, E->getOpaqueValue()), 7357 ScopeKind::FullExpression, CommonLV), 7358 Info, E->getCommon())) 7359 return false; 7360 7361 return HandleConditionalOperator(E); 7362 } 7363 7364 bool VisitConditionalOperator(const ConditionalOperator *E) { 7365 bool IsBcpCall = false; 7366 // If the condition (ignoring parens) is a __builtin_constant_p call, 7367 // the result is a constant expression if it can be folded without 7368 // side-effects. This is an important GNU extension. See GCC PR38377 7369 // for discussion. 7370 if (const CallExpr *CallCE = 7371 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7372 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7373 IsBcpCall = true; 7374 7375 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7376 // constant expression; we can't check whether it's potentially foldable. 7377 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7378 // it would return 'false' in this mode. 7379 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7380 return false; 7381 7382 FoldConstant Fold(Info, IsBcpCall); 7383 if (!HandleConditionalOperator(E)) { 7384 Fold.keepDiagnostics(); 7385 return false; 7386 } 7387 7388 return true; 7389 } 7390 7391 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7392 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7393 return DerivedSuccess(*Value, E); 7394 7395 const Expr *Source = E->getSourceExpr(); 7396 if (!Source) 7397 return Error(E); 7398 if (Source == E) { // sanity checking. 7399 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7400 return Error(E); 7401 } 7402 return StmtVisitorTy::Visit(Source); 7403 } 7404 7405 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7406 for (const Expr *SemE : E->semantics()) { 7407 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7408 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7409 // result expression: there could be two different LValues that would 7410 // refer to the same object in that case, and we can't model that. 7411 if (SemE == E->getResultExpr()) 7412 return Error(E); 7413 7414 // Unique OVEs get evaluated if and when we encounter them when 7415 // emitting the rest of the semantic form, rather than eagerly. 7416 if (OVE->isUnique()) 7417 continue; 7418 7419 LValue LV; 7420 if (!Evaluate(Info.CurrentCall->createTemporary( 7421 OVE, getStorageType(Info.Ctx, OVE), 7422 ScopeKind::FullExpression, LV), 7423 Info, OVE->getSourceExpr())) 7424 return false; 7425 } else if (SemE == E->getResultExpr()) { 7426 if (!StmtVisitorTy::Visit(SemE)) 7427 return false; 7428 } else { 7429 if (!EvaluateIgnoredValue(Info, SemE)) 7430 return false; 7431 } 7432 } 7433 return true; 7434 } 7435 7436 bool VisitCallExpr(const CallExpr *E) { 7437 APValue Result; 7438 if (!handleCallExpr(E, Result, nullptr)) 7439 return false; 7440 return DerivedSuccess(Result, E); 7441 } 7442 7443 bool handleCallExpr(const CallExpr *E, APValue &Result, 7444 const LValue *ResultSlot) { 7445 CallScopeRAII CallScope(Info); 7446 7447 const Expr *Callee = E->getCallee()->IgnoreParens(); 7448 QualType CalleeType = Callee->getType(); 7449 7450 const FunctionDecl *FD = nullptr; 7451 LValue *This = nullptr, ThisVal; 7452 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7453 bool HasQualifier = false; 7454 7455 CallRef Call; 7456 7457 // Extract function decl and 'this' pointer from the callee. 7458 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7459 const CXXMethodDecl *Member = nullptr; 7460 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7461 // Explicit bound member calls, such as x.f() or p->g(); 7462 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7463 return false; 7464 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7465 if (!Member) 7466 return Error(Callee); 7467 This = &ThisVal; 7468 HasQualifier = ME->hasQualifier(); 7469 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7470 // Indirect bound member calls ('.*' or '->*'). 7471 const ValueDecl *D = 7472 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7473 if (!D) 7474 return false; 7475 Member = dyn_cast<CXXMethodDecl>(D); 7476 if (!Member) 7477 return Error(Callee); 7478 This = &ThisVal; 7479 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7480 if (!Info.getLangOpts().CPlusPlus20) 7481 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7482 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7483 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7484 } else 7485 return Error(Callee); 7486 FD = Member; 7487 } else if (CalleeType->isFunctionPointerType()) { 7488 LValue CalleeLV; 7489 if (!EvaluatePointer(Callee, CalleeLV, Info)) 7490 return false; 7491 7492 if (!CalleeLV.getLValueOffset().isZero()) 7493 return Error(Callee); 7494 FD = dyn_cast_or_null<FunctionDecl>( 7495 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7496 if (!FD) 7497 return Error(Callee); 7498 // Don't call function pointers which have been cast to some other type. 7499 // Per DR (no number yet), the caller and callee can differ in noexcept. 7500 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7501 CalleeType->getPointeeType(), FD->getType())) { 7502 return Error(E); 7503 } 7504 7505 // For an (overloaded) assignment expression, evaluate the RHS before the 7506 // LHS. 7507 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7508 if (OCE && OCE->isAssignmentOp()) { 7509 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7510 Call = Info.CurrentCall->createCall(FD); 7511 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7512 Info, FD, /*RightToLeft=*/true)) 7513 return false; 7514 } 7515 7516 // Overloaded operator calls to member functions are represented as normal 7517 // calls with '*this' as the first argument. 7518 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7519 if (MD && !MD->isStatic()) { 7520 // FIXME: When selecting an implicit conversion for an overloaded 7521 // operator delete, we sometimes try to evaluate calls to conversion 7522 // operators without a 'this' parameter! 7523 if (Args.empty()) 7524 return Error(E); 7525 7526 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7527 return false; 7528 This = &ThisVal; 7529 Args = Args.slice(1); 7530 } else if (MD && MD->isLambdaStaticInvoker()) { 7531 // Map the static invoker for the lambda back to the call operator. 7532 // Conveniently, we don't have to slice out the 'this' argument (as is 7533 // being done for the non-static case), since a static member function 7534 // doesn't have an implicit argument passed in. 7535 const CXXRecordDecl *ClosureClass = MD->getParent(); 7536 assert( 7537 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7538 "Number of captures must be zero for conversion to function-ptr"); 7539 7540 const CXXMethodDecl *LambdaCallOp = 7541 ClosureClass->getLambdaCallOperator(); 7542 7543 // Set 'FD', the function that will be called below, to the call 7544 // operator. If the closure object represents a generic lambda, find 7545 // the corresponding specialization of the call operator. 7546 7547 if (ClosureClass->isGenericLambda()) { 7548 assert(MD->isFunctionTemplateSpecialization() && 7549 "A generic lambda's static-invoker function must be a " 7550 "template specialization"); 7551 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7552 FunctionTemplateDecl *CallOpTemplate = 7553 LambdaCallOp->getDescribedFunctionTemplate(); 7554 void *InsertPos = nullptr; 7555 FunctionDecl *CorrespondingCallOpSpecialization = 7556 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7557 assert(CorrespondingCallOpSpecialization && 7558 "We must always have a function call operator specialization " 7559 "that corresponds to our static invoker specialization"); 7560 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7561 } else 7562 FD = LambdaCallOp; 7563 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7564 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7565 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7566 LValue Ptr; 7567 if (!HandleOperatorNewCall(Info, E, Ptr)) 7568 return false; 7569 Ptr.moveInto(Result); 7570 return CallScope.destroy(); 7571 } else { 7572 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7573 } 7574 } 7575 } else 7576 return Error(E); 7577 7578 // Evaluate the arguments now if we've not already done so. 7579 if (!Call) { 7580 Call = Info.CurrentCall->createCall(FD); 7581 if (!EvaluateArgs(Args, Call, Info, FD)) 7582 return false; 7583 } 7584 7585 SmallVector<QualType, 4> CovariantAdjustmentPath; 7586 if (This) { 7587 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7588 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7589 // Perform virtual dispatch, if necessary. 7590 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7591 CovariantAdjustmentPath); 7592 if (!FD) 7593 return false; 7594 } else { 7595 // Check that the 'this' pointer points to an object of the right type. 7596 // FIXME: If this is an assignment operator call, we may need to change 7597 // the active union member before we check this. 7598 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7599 return false; 7600 } 7601 } 7602 7603 // Destructor calls are different enough that they have their own codepath. 7604 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7605 assert(This && "no 'this' pointer for destructor call"); 7606 return HandleDestruction(Info, E, *This, 7607 Info.Ctx.getRecordType(DD->getParent())) && 7608 CallScope.destroy(); 7609 } 7610 7611 const FunctionDecl *Definition = nullptr; 7612 Stmt *Body = FD->getBody(Definition); 7613 7614 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7615 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7616 Body, Info, Result, ResultSlot)) 7617 return false; 7618 7619 if (!CovariantAdjustmentPath.empty() && 7620 !HandleCovariantReturnAdjustment(Info, E, Result, 7621 CovariantAdjustmentPath)) 7622 return false; 7623 7624 return CallScope.destroy(); 7625 } 7626 7627 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7628 return StmtVisitorTy::Visit(E->getInitializer()); 7629 } 7630 bool VisitInitListExpr(const InitListExpr *E) { 7631 if (E->getNumInits() == 0) 7632 return DerivedZeroInitialization(E); 7633 if (E->getNumInits() == 1) 7634 return StmtVisitorTy::Visit(E->getInit(0)); 7635 return Error(E); 7636 } 7637 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7638 return DerivedZeroInitialization(E); 7639 } 7640 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7641 return DerivedZeroInitialization(E); 7642 } 7643 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7644 return DerivedZeroInitialization(E); 7645 } 7646 7647 /// A member expression where the object is a prvalue is itself a prvalue. 7648 bool VisitMemberExpr(const MemberExpr *E) { 7649 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7650 "missing temporary materialization conversion"); 7651 assert(!E->isArrow() && "missing call to bound member function?"); 7652 7653 APValue Val; 7654 if (!Evaluate(Val, Info, E->getBase())) 7655 return false; 7656 7657 QualType BaseTy = E->getBase()->getType(); 7658 7659 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7660 if (!FD) return Error(E); 7661 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7662 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7663 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7664 7665 // Note: there is no lvalue base here. But this case should only ever 7666 // happen in C or in C++98, where we cannot be evaluating a constexpr 7667 // constructor, which is the only case the base matters. 7668 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7669 SubobjectDesignator Designator(BaseTy); 7670 Designator.addDeclUnchecked(FD); 7671 7672 APValue Result; 7673 return extractSubobject(Info, E, Obj, Designator, Result) && 7674 DerivedSuccess(Result, E); 7675 } 7676 7677 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7678 APValue Val; 7679 if (!Evaluate(Val, Info, E->getBase())) 7680 return false; 7681 7682 if (Val.isVector()) { 7683 SmallVector<uint32_t, 4> Indices; 7684 E->getEncodedElementAccess(Indices); 7685 if (Indices.size() == 1) { 7686 // Return scalar. 7687 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7688 } else { 7689 // Construct new APValue vector. 7690 SmallVector<APValue, 4> Elts; 7691 for (unsigned I = 0; I < Indices.size(); ++I) { 7692 Elts.push_back(Val.getVectorElt(Indices[I])); 7693 } 7694 APValue VecResult(Elts.data(), Indices.size()); 7695 return DerivedSuccess(VecResult, E); 7696 } 7697 } 7698 7699 return false; 7700 } 7701 7702 bool VisitCastExpr(const CastExpr *E) { 7703 switch (E->getCastKind()) { 7704 default: 7705 break; 7706 7707 case CK_AtomicToNonAtomic: { 7708 APValue AtomicVal; 7709 // This does not need to be done in place even for class/array types: 7710 // atomic-to-non-atomic conversion implies copying the object 7711 // representation. 7712 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7713 return false; 7714 return DerivedSuccess(AtomicVal, E); 7715 } 7716 7717 case CK_NoOp: 7718 case CK_UserDefinedConversion: 7719 return StmtVisitorTy::Visit(E->getSubExpr()); 7720 7721 case CK_LValueToRValue: { 7722 LValue LVal; 7723 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7724 return false; 7725 APValue RVal; 7726 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7727 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7728 LVal, RVal)) 7729 return false; 7730 return DerivedSuccess(RVal, E); 7731 } 7732 case CK_LValueToRValueBitCast: { 7733 APValue DestValue, SourceValue; 7734 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7735 return false; 7736 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7737 return false; 7738 return DerivedSuccess(DestValue, E); 7739 } 7740 7741 case CK_AddressSpaceConversion: { 7742 APValue Value; 7743 if (!Evaluate(Value, Info, E->getSubExpr())) 7744 return false; 7745 return DerivedSuccess(Value, E); 7746 } 7747 } 7748 7749 return Error(E); 7750 } 7751 7752 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7753 return VisitUnaryPostIncDec(UO); 7754 } 7755 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7756 return VisitUnaryPostIncDec(UO); 7757 } 7758 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7759 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7760 return Error(UO); 7761 7762 LValue LVal; 7763 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7764 return false; 7765 APValue RVal; 7766 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7767 UO->isIncrementOp(), &RVal)) 7768 return false; 7769 return DerivedSuccess(RVal, UO); 7770 } 7771 7772 bool VisitStmtExpr(const StmtExpr *E) { 7773 // We will have checked the full-expressions inside the statement expression 7774 // when they were completed, and don't need to check them again now. 7775 if (Info.checkingForUndefinedBehavior()) 7776 return Error(E); 7777 7778 const CompoundStmt *CS = E->getSubStmt(); 7779 if (CS->body_empty()) 7780 return true; 7781 7782 BlockScopeRAII Scope(Info); 7783 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7784 BE = CS->body_end(); 7785 /**/; ++BI) { 7786 if (BI + 1 == BE) { 7787 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7788 if (!FinalExpr) { 7789 Info.FFDiag((*BI)->getBeginLoc(), 7790 diag::note_constexpr_stmt_expr_unsupported); 7791 return false; 7792 } 7793 return this->Visit(FinalExpr) && Scope.destroy(); 7794 } 7795 7796 APValue ReturnValue; 7797 StmtResult Result = { ReturnValue, nullptr }; 7798 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7799 if (ESR != ESR_Succeeded) { 7800 // FIXME: If the statement-expression terminated due to 'return', 7801 // 'break', or 'continue', it would be nice to propagate that to 7802 // the outer statement evaluation rather than bailing out. 7803 if (ESR != ESR_Failed) 7804 Info.FFDiag((*BI)->getBeginLoc(), 7805 diag::note_constexpr_stmt_expr_unsupported); 7806 return false; 7807 } 7808 } 7809 7810 llvm_unreachable("Return from function from the loop above."); 7811 } 7812 7813 /// Visit a value which is evaluated, but whose value is ignored. 7814 void VisitIgnoredValue(const Expr *E) { 7815 EvaluateIgnoredValue(Info, E); 7816 } 7817 7818 /// Potentially visit a MemberExpr's base expression. 7819 void VisitIgnoredBaseExpression(const Expr *E) { 7820 // While MSVC doesn't evaluate the base expression, it does diagnose the 7821 // presence of side-effecting behavior. 7822 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7823 return; 7824 VisitIgnoredValue(E); 7825 } 7826 }; 7827 7828 } // namespace 7829 7830 //===----------------------------------------------------------------------===// 7831 // Common base class for lvalue and temporary evaluation. 7832 //===----------------------------------------------------------------------===// 7833 namespace { 7834 template<class Derived> 7835 class LValueExprEvaluatorBase 7836 : public ExprEvaluatorBase<Derived> { 7837 protected: 7838 LValue &Result; 7839 bool InvalidBaseOK; 7840 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7841 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7842 7843 bool Success(APValue::LValueBase B) { 7844 Result.set(B); 7845 return true; 7846 } 7847 7848 bool evaluatePointer(const Expr *E, LValue &Result) { 7849 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7850 } 7851 7852 public: 7853 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7854 : ExprEvaluatorBaseTy(Info), Result(Result), 7855 InvalidBaseOK(InvalidBaseOK) {} 7856 7857 bool Success(const APValue &V, const Expr *E) { 7858 Result.setFrom(this->Info.Ctx, V); 7859 return true; 7860 } 7861 7862 bool VisitMemberExpr(const MemberExpr *E) { 7863 // Handle non-static data members. 7864 QualType BaseTy; 7865 bool EvalOK; 7866 if (E->isArrow()) { 7867 EvalOK = evaluatePointer(E->getBase(), Result); 7868 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7869 } else if (E->getBase()->isRValue()) { 7870 assert(E->getBase()->getType()->isRecordType()); 7871 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7872 BaseTy = E->getBase()->getType(); 7873 } else { 7874 EvalOK = this->Visit(E->getBase()); 7875 BaseTy = E->getBase()->getType(); 7876 } 7877 if (!EvalOK) { 7878 if (!InvalidBaseOK) 7879 return false; 7880 Result.setInvalid(E); 7881 return true; 7882 } 7883 7884 const ValueDecl *MD = E->getMemberDecl(); 7885 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7886 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7887 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7888 (void)BaseTy; 7889 if (!HandleLValueMember(this->Info, E, Result, FD)) 7890 return false; 7891 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7892 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7893 return false; 7894 } else 7895 return this->Error(E); 7896 7897 if (MD->getType()->isReferenceType()) { 7898 APValue RefValue; 7899 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7900 RefValue)) 7901 return false; 7902 return Success(RefValue, E); 7903 } 7904 return true; 7905 } 7906 7907 bool VisitBinaryOperator(const BinaryOperator *E) { 7908 switch (E->getOpcode()) { 7909 default: 7910 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7911 7912 case BO_PtrMemD: 7913 case BO_PtrMemI: 7914 return HandleMemberPointerAccess(this->Info, E, Result); 7915 } 7916 } 7917 7918 bool VisitCastExpr(const CastExpr *E) { 7919 switch (E->getCastKind()) { 7920 default: 7921 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7922 7923 case CK_DerivedToBase: 7924 case CK_UncheckedDerivedToBase: 7925 if (!this->Visit(E->getSubExpr())) 7926 return false; 7927 7928 // Now figure out the necessary offset to add to the base LV to get from 7929 // the derived class to the base class. 7930 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7931 Result); 7932 } 7933 } 7934 }; 7935 } 7936 7937 //===----------------------------------------------------------------------===// 7938 // LValue Evaluation 7939 // 7940 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7941 // function designators (in C), decl references to void objects (in C), and 7942 // temporaries (if building with -Wno-address-of-temporary). 7943 // 7944 // LValue evaluation produces values comprising a base expression of one of the 7945 // following types: 7946 // - Declarations 7947 // * VarDecl 7948 // * FunctionDecl 7949 // - Literals 7950 // * CompoundLiteralExpr in C (and in global scope in C++) 7951 // * StringLiteral 7952 // * PredefinedExpr 7953 // * ObjCStringLiteralExpr 7954 // * ObjCEncodeExpr 7955 // * AddrLabelExpr 7956 // * BlockExpr 7957 // * CallExpr for a MakeStringConstant builtin 7958 // - typeid(T) expressions, as TypeInfoLValues 7959 // - Locals and temporaries 7960 // * MaterializeTemporaryExpr 7961 // * Any Expr, with a CallIndex indicating the function in which the temporary 7962 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7963 // from the AST (FIXME). 7964 // * A MaterializeTemporaryExpr that has static storage duration, with no 7965 // CallIndex, for a lifetime-extended temporary. 7966 // * The ConstantExpr that is currently being evaluated during evaluation of an 7967 // immediate invocation. 7968 // plus an offset in bytes. 7969 //===----------------------------------------------------------------------===// 7970 namespace { 7971 class LValueExprEvaluator 7972 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7973 public: 7974 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7975 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7976 7977 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7978 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7979 7980 bool VisitDeclRefExpr(const DeclRefExpr *E); 7981 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7982 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7983 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7984 bool VisitMemberExpr(const MemberExpr *E); 7985 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7986 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7987 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7988 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7989 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7990 bool VisitUnaryDeref(const UnaryOperator *E); 7991 bool VisitUnaryReal(const UnaryOperator *E); 7992 bool VisitUnaryImag(const UnaryOperator *E); 7993 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7994 return VisitUnaryPreIncDec(UO); 7995 } 7996 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7997 return VisitUnaryPreIncDec(UO); 7998 } 7999 bool VisitBinAssign(const BinaryOperator *BO); 8000 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8001 8002 bool VisitCastExpr(const CastExpr *E) { 8003 switch (E->getCastKind()) { 8004 default: 8005 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8006 8007 case CK_LValueBitCast: 8008 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8009 if (!Visit(E->getSubExpr())) 8010 return false; 8011 Result.Designator.setInvalid(); 8012 return true; 8013 8014 case CK_BaseToDerived: 8015 if (!Visit(E->getSubExpr())) 8016 return false; 8017 return HandleBaseToDerivedCast(Info, E, Result); 8018 8019 case CK_Dynamic: 8020 if (!Visit(E->getSubExpr())) 8021 return false; 8022 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8023 } 8024 } 8025 }; 8026 } // end anonymous namespace 8027 8028 /// Evaluate an expression as an lvalue. This can be legitimately called on 8029 /// expressions which are not glvalues, in three cases: 8030 /// * function designators in C, and 8031 /// * "extern void" objects 8032 /// * @selector() expressions in Objective-C 8033 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8034 bool InvalidBaseOK) { 8035 assert(E->isGLValue() || E->getType()->isFunctionType() || 8036 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8037 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8038 } 8039 8040 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8041 const NamedDecl *D = E->getDecl(); 8042 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8043 return Success(cast<ValueDecl>(D)); 8044 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8045 return VisitVarDecl(E, VD); 8046 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8047 return Visit(BD->getBinding()); 8048 return Error(E); 8049 } 8050 8051 8052 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8053 8054 // If we are within a lambda's call operator, check whether the 'VD' referred 8055 // to within 'E' actually represents a lambda-capture that maps to a 8056 // data-member/field within the closure object, and if so, evaluate to the 8057 // field or what the field refers to. 8058 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8059 isa<DeclRefExpr>(E) && 8060 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8061 // We don't always have a complete capture-map when checking or inferring if 8062 // the function call operator meets the requirements of a constexpr function 8063 // - but we don't need to evaluate the captures to determine constexprness 8064 // (dcl.constexpr C++17). 8065 if (Info.checkingPotentialConstantExpression()) 8066 return false; 8067 8068 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8069 // Start with 'Result' referring to the complete closure object... 8070 Result = *Info.CurrentCall->This; 8071 // ... then update it to refer to the field of the closure object 8072 // that represents the capture. 8073 if (!HandleLValueMember(Info, E, Result, FD)) 8074 return false; 8075 // And if the field is of reference type, update 'Result' to refer to what 8076 // the field refers to. 8077 if (FD->getType()->isReferenceType()) { 8078 APValue RVal; 8079 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8080 RVal)) 8081 return false; 8082 Result.setFrom(Info.Ctx, RVal); 8083 } 8084 return true; 8085 } 8086 } 8087 8088 CallStackFrame *Frame = nullptr; 8089 unsigned Version = 0; 8090 if (VD->hasLocalStorage()) { 8091 // Only if a local variable was declared in the function currently being 8092 // evaluated, do we expect to be able to find its value in the current 8093 // frame. (Otherwise it was likely declared in an enclosing context and 8094 // could either have a valid evaluatable value (for e.g. a constexpr 8095 // variable) or be ill-formed (and trigger an appropriate evaluation 8096 // diagnostic)). 8097 CallStackFrame *CurrFrame = Info.CurrentCall; 8098 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8099 // Function parameters are stored in some caller's frame. (Usually the 8100 // immediate caller, but for an inherited constructor they may be more 8101 // distant.) 8102 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8103 if (CurrFrame->Arguments) { 8104 VD = CurrFrame->Arguments.getOrigParam(PVD); 8105 Frame = 8106 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8107 Version = CurrFrame->Arguments.Version; 8108 } 8109 } else { 8110 Frame = CurrFrame; 8111 Version = CurrFrame->getCurrentTemporaryVersion(VD); 8112 } 8113 } 8114 } 8115 8116 if (!VD->getType()->isReferenceType()) { 8117 if (Frame) { 8118 Result.set({VD, Frame->Index, Version}); 8119 return true; 8120 } 8121 return Success(VD); 8122 } 8123 8124 if (!Info.getLangOpts().CPlusPlus11) { 8125 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8126 << VD << VD->getType(); 8127 Info.Note(VD->getLocation(), diag::note_declared_at); 8128 } 8129 8130 APValue *V; 8131 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8132 return false; 8133 if (!V->hasValue()) { 8134 // FIXME: Is it possible for V to be indeterminate here? If so, we should 8135 // adjust the diagnostic to say that. 8136 if (!Info.checkingPotentialConstantExpression()) 8137 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8138 return false; 8139 } 8140 return Success(*V, E); 8141 } 8142 8143 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8144 const MaterializeTemporaryExpr *E) { 8145 // Walk through the expression to find the materialized temporary itself. 8146 SmallVector<const Expr *, 2> CommaLHSs; 8147 SmallVector<SubobjectAdjustment, 2> Adjustments; 8148 const Expr *Inner = 8149 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8150 8151 // If we passed any comma operators, evaluate their LHSs. 8152 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8153 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8154 return false; 8155 8156 // A materialized temporary with static storage duration can appear within the 8157 // result of a constant expression evaluation, so we need to preserve its 8158 // value for use outside this evaluation. 8159 APValue *Value; 8160 if (E->getStorageDuration() == SD_Static) { 8161 // FIXME: What about SD_Thread? 8162 Value = E->getOrCreateValue(true); 8163 *Value = APValue(); 8164 Result.set(E); 8165 } else { 8166 Value = &Info.CurrentCall->createTemporary( 8167 E, E->getType(), 8168 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8169 : ScopeKind::Block, 8170 Result); 8171 } 8172 8173 QualType Type = Inner->getType(); 8174 8175 // Materialize the temporary itself. 8176 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8177 *Value = APValue(); 8178 return false; 8179 } 8180 8181 // Adjust our lvalue to refer to the desired subobject. 8182 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8183 --I; 8184 switch (Adjustments[I].Kind) { 8185 case SubobjectAdjustment::DerivedToBaseAdjustment: 8186 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8187 Type, Result)) 8188 return false; 8189 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8190 break; 8191 8192 case SubobjectAdjustment::FieldAdjustment: 8193 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8194 return false; 8195 Type = Adjustments[I].Field->getType(); 8196 break; 8197 8198 case SubobjectAdjustment::MemberPointerAdjustment: 8199 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8200 Adjustments[I].Ptr.RHS)) 8201 return false; 8202 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8203 break; 8204 } 8205 } 8206 8207 return true; 8208 } 8209 8210 bool 8211 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8212 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8213 "lvalue compound literal in c++?"); 8214 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8215 // only see this when folding in C, so there's no standard to follow here. 8216 return Success(E); 8217 } 8218 8219 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8220 TypeInfoLValue TypeInfo; 8221 8222 if (!E->isPotentiallyEvaluated()) { 8223 if (E->isTypeOperand()) 8224 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8225 else 8226 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8227 } else { 8228 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8229 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8230 << E->getExprOperand()->getType() 8231 << E->getExprOperand()->getSourceRange(); 8232 } 8233 8234 if (!Visit(E->getExprOperand())) 8235 return false; 8236 8237 Optional<DynamicType> DynType = 8238 ComputeDynamicType(Info, E, Result, AK_TypeId); 8239 if (!DynType) 8240 return false; 8241 8242 TypeInfo = 8243 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8244 } 8245 8246 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8247 } 8248 8249 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8250 return Success(E->getGuidDecl()); 8251 } 8252 8253 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8254 // Handle static data members. 8255 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8256 VisitIgnoredBaseExpression(E->getBase()); 8257 return VisitVarDecl(E, VD); 8258 } 8259 8260 // Handle static member functions. 8261 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8262 if (MD->isStatic()) { 8263 VisitIgnoredBaseExpression(E->getBase()); 8264 return Success(MD); 8265 } 8266 } 8267 8268 // Handle non-static data members. 8269 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8270 } 8271 8272 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8273 // FIXME: Deal with vectors as array subscript bases. 8274 if (E->getBase()->getType()->isVectorType()) 8275 return Error(E); 8276 8277 APSInt Index; 8278 bool Success = true; 8279 8280 // C++17's rules require us to evaluate the LHS first, regardless of which 8281 // side is the base. 8282 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8283 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8284 : !EvaluateInteger(SubExpr, Index, Info)) { 8285 if (!Info.noteFailure()) 8286 return false; 8287 Success = false; 8288 } 8289 } 8290 8291 return Success && 8292 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8293 } 8294 8295 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8296 return evaluatePointer(E->getSubExpr(), Result); 8297 } 8298 8299 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8300 if (!Visit(E->getSubExpr())) 8301 return false; 8302 // __real is a no-op on scalar lvalues. 8303 if (E->getSubExpr()->getType()->isAnyComplexType()) 8304 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8305 return true; 8306 } 8307 8308 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8309 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8310 "lvalue __imag__ on scalar?"); 8311 if (!Visit(E->getSubExpr())) 8312 return false; 8313 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8314 return true; 8315 } 8316 8317 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8318 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8319 return Error(UO); 8320 8321 if (!this->Visit(UO->getSubExpr())) 8322 return false; 8323 8324 return handleIncDec( 8325 this->Info, UO, Result, UO->getSubExpr()->getType(), 8326 UO->isIncrementOp(), nullptr); 8327 } 8328 8329 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8330 const CompoundAssignOperator *CAO) { 8331 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8332 return Error(CAO); 8333 8334 bool Success = true; 8335 8336 // C++17 onwards require that we evaluate the RHS first. 8337 APValue RHS; 8338 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8339 if (!Info.noteFailure()) 8340 return false; 8341 Success = false; 8342 } 8343 8344 // The overall lvalue result is the result of evaluating the LHS. 8345 if (!this->Visit(CAO->getLHS()) || !Success) 8346 return false; 8347 8348 return handleCompoundAssignment( 8349 this->Info, CAO, 8350 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8351 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8352 } 8353 8354 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8355 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8356 return Error(E); 8357 8358 bool Success = true; 8359 8360 // C++17 onwards require that we evaluate the RHS first. 8361 APValue NewVal; 8362 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8363 if (!Info.noteFailure()) 8364 return false; 8365 Success = false; 8366 } 8367 8368 if (!this->Visit(E->getLHS()) || !Success) 8369 return false; 8370 8371 if (Info.getLangOpts().CPlusPlus20 && 8372 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8373 return false; 8374 8375 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8376 NewVal); 8377 } 8378 8379 //===----------------------------------------------------------------------===// 8380 // Pointer Evaluation 8381 //===----------------------------------------------------------------------===// 8382 8383 /// Attempts to compute the number of bytes available at the pointer 8384 /// returned by a function with the alloc_size attribute. Returns true if we 8385 /// were successful. Places an unsigned number into `Result`. 8386 /// 8387 /// This expects the given CallExpr to be a call to a function with an 8388 /// alloc_size attribute. 8389 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8390 const CallExpr *Call, 8391 llvm::APInt &Result) { 8392 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8393 8394 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8395 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8396 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8397 if (Call->getNumArgs() <= SizeArgNo) 8398 return false; 8399 8400 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8401 Expr::EvalResult ExprResult; 8402 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8403 return false; 8404 Into = ExprResult.Val.getInt(); 8405 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8406 return false; 8407 Into = Into.zextOrSelf(BitsInSizeT); 8408 return true; 8409 }; 8410 8411 APSInt SizeOfElem; 8412 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8413 return false; 8414 8415 if (!AllocSize->getNumElemsParam().isValid()) { 8416 Result = std::move(SizeOfElem); 8417 return true; 8418 } 8419 8420 APSInt NumberOfElems; 8421 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8422 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8423 return false; 8424 8425 bool Overflow; 8426 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8427 if (Overflow) 8428 return false; 8429 8430 Result = std::move(BytesAvailable); 8431 return true; 8432 } 8433 8434 /// Convenience function. LVal's base must be a call to an alloc_size 8435 /// function. 8436 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8437 const LValue &LVal, 8438 llvm::APInt &Result) { 8439 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8440 "Can't get the size of a non alloc_size function"); 8441 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8442 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8443 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8444 } 8445 8446 /// Attempts to evaluate the given LValueBase as the result of a call to 8447 /// a function with the alloc_size attribute. If it was possible to do so, this 8448 /// function will return true, make Result's Base point to said function call, 8449 /// and mark Result's Base as invalid. 8450 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8451 LValue &Result) { 8452 if (Base.isNull()) 8453 return false; 8454 8455 // Because we do no form of static analysis, we only support const variables. 8456 // 8457 // Additionally, we can't support parameters, nor can we support static 8458 // variables (in the latter case, use-before-assign isn't UB; in the former, 8459 // we have no clue what they'll be assigned to). 8460 const auto *VD = 8461 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8462 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8463 return false; 8464 8465 const Expr *Init = VD->getAnyInitializer(); 8466 if (!Init) 8467 return false; 8468 8469 const Expr *E = Init->IgnoreParens(); 8470 if (!tryUnwrapAllocSizeCall(E)) 8471 return false; 8472 8473 // Store E instead of E unwrapped so that the type of the LValue's base is 8474 // what the user wanted. 8475 Result.setInvalid(E); 8476 8477 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8478 Result.addUnsizedArray(Info, E, Pointee); 8479 return true; 8480 } 8481 8482 namespace { 8483 class PointerExprEvaluator 8484 : public ExprEvaluatorBase<PointerExprEvaluator> { 8485 LValue &Result; 8486 bool InvalidBaseOK; 8487 8488 bool Success(const Expr *E) { 8489 Result.set(E); 8490 return true; 8491 } 8492 8493 bool evaluateLValue(const Expr *E, LValue &Result) { 8494 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8495 } 8496 8497 bool evaluatePointer(const Expr *E, LValue &Result) { 8498 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8499 } 8500 8501 bool visitNonBuiltinCallExpr(const CallExpr *E); 8502 public: 8503 8504 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8505 : ExprEvaluatorBaseTy(info), Result(Result), 8506 InvalidBaseOK(InvalidBaseOK) {} 8507 8508 bool Success(const APValue &V, const Expr *E) { 8509 Result.setFrom(Info.Ctx, V); 8510 return true; 8511 } 8512 bool ZeroInitialization(const Expr *E) { 8513 Result.setNull(Info.Ctx, E->getType()); 8514 return true; 8515 } 8516 8517 bool VisitBinaryOperator(const BinaryOperator *E); 8518 bool VisitCastExpr(const CastExpr* E); 8519 bool VisitUnaryAddrOf(const UnaryOperator *E); 8520 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8521 { return Success(E); } 8522 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8523 if (E->isExpressibleAsConstantInitializer()) 8524 return Success(E); 8525 if (Info.noteFailure()) 8526 EvaluateIgnoredValue(Info, E->getSubExpr()); 8527 return Error(E); 8528 } 8529 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8530 { return Success(E); } 8531 bool VisitCallExpr(const CallExpr *E); 8532 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8533 bool VisitBlockExpr(const BlockExpr *E) { 8534 if (!E->getBlockDecl()->hasCaptures()) 8535 return Success(E); 8536 return Error(E); 8537 } 8538 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8539 // Can't look at 'this' when checking a potential constant expression. 8540 if (Info.checkingPotentialConstantExpression()) 8541 return false; 8542 if (!Info.CurrentCall->This) { 8543 if (Info.getLangOpts().CPlusPlus11) 8544 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8545 else 8546 Info.FFDiag(E); 8547 return false; 8548 } 8549 Result = *Info.CurrentCall->This; 8550 // If we are inside a lambda's call operator, the 'this' expression refers 8551 // to the enclosing '*this' object (either by value or reference) which is 8552 // either copied into the closure object's field that represents the '*this' 8553 // or refers to '*this'. 8554 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8555 // Ensure we actually have captured 'this'. (an error will have 8556 // been previously reported if not). 8557 if (!Info.CurrentCall->LambdaThisCaptureField) 8558 return false; 8559 8560 // Update 'Result' to refer to the data member/field of the closure object 8561 // that represents the '*this' capture. 8562 if (!HandleLValueMember(Info, E, Result, 8563 Info.CurrentCall->LambdaThisCaptureField)) 8564 return false; 8565 // If we captured '*this' by reference, replace the field with its referent. 8566 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8567 ->isPointerType()) { 8568 APValue RVal; 8569 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8570 RVal)) 8571 return false; 8572 8573 Result.setFrom(Info.Ctx, RVal); 8574 } 8575 } 8576 return true; 8577 } 8578 8579 bool VisitCXXNewExpr(const CXXNewExpr *E); 8580 8581 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8582 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8583 APValue LValResult = E->EvaluateInContext( 8584 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8585 Result.setFrom(Info.Ctx, LValResult); 8586 return true; 8587 } 8588 8589 // FIXME: Missing: @protocol, @selector 8590 }; 8591 } // end anonymous namespace 8592 8593 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8594 bool InvalidBaseOK) { 8595 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8596 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8597 } 8598 8599 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8600 if (E->getOpcode() != BO_Add && 8601 E->getOpcode() != BO_Sub) 8602 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8603 8604 const Expr *PExp = E->getLHS(); 8605 const Expr *IExp = E->getRHS(); 8606 if (IExp->getType()->isPointerType()) 8607 std::swap(PExp, IExp); 8608 8609 bool EvalPtrOK = evaluatePointer(PExp, Result); 8610 if (!EvalPtrOK && !Info.noteFailure()) 8611 return false; 8612 8613 llvm::APSInt Offset; 8614 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8615 return false; 8616 8617 if (E->getOpcode() == BO_Sub) 8618 negateAsSigned(Offset); 8619 8620 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8621 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8622 } 8623 8624 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8625 return evaluateLValue(E->getSubExpr(), Result); 8626 } 8627 8628 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8629 const Expr *SubExpr = E->getSubExpr(); 8630 8631 switch (E->getCastKind()) { 8632 default: 8633 break; 8634 case CK_BitCast: 8635 case CK_CPointerToObjCPointerCast: 8636 case CK_BlockPointerToObjCPointerCast: 8637 case CK_AnyPointerToBlockPointerCast: 8638 case CK_AddressSpaceConversion: 8639 if (!Visit(SubExpr)) 8640 return false; 8641 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8642 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8643 // also static_casts, but we disallow them as a resolution to DR1312. 8644 if (!E->getType()->isVoidPointerType()) { 8645 if (!Result.InvalidBase && !Result.Designator.Invalid && 8646 !Result.IsNullPtr && 8647 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8648 E->getType()->getPointeeType()) && 8649 Info.getStdAllocatorCaller("allocate")) { 8650 // Inside a call to std::allocator::allocate and friends, we permit 8651 // casting from void* back to cv1 T* for a pointer that points to a 8652 // cv2 T. 8653 } else { 8654 Result.Designator.setInvalid(); 8655 if (SubExpr->getType()->isVoidPointerType()) 8656 CCEDiag(E, diag::note_constexpr_invalid_cast) 8657 << 3 << SubExpr->getType(); 8658 else 8659 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8660 } 8661 } 8662 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8663 ZeroInitialization(E); 8664 return true; 8665 8666 case CK_DerivedToBase: 8667 case CK_UncheckedDerivedToBase: 8668 if (!evaluatePointer(E->getSubExpr(), Result)) 8669 return false; 8670 if (!Result.Base && Result.Offset.isZero()) 8671 return true; 8672 8673 // Now figure out the necessary offset to add to the base LV to get from 8674 // the derived class to the base class. 8675 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8676 castAs<PointerType>()->getPointeeType(), 8677 Result); 8678 8679 case CK_BaseToDerived: 8680 if (!Visit(E->getSubExpr())) 8681 return false; 8682 if (!Result.Base && Result.Offset.isZero()) 8683 return true; 8684 return HandleBaseToDerivedCast(Info, E, Result); 8685 8686 case CK_Dynamic: 8687 if (!Visit(E->getSubExpr())) 8688 return false; 8689 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8690 8691 case CK_NullToPointer: 8692 VisitIgnoredValue(E->getSubExpr()); 8693 return ZeroInitialization(E); 8694 8695 case CK_IntegralToPointer: { 8696 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8697 8698 APValue Value; 8699 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8700 break; 8701 8702 if (Value.isInt()) { 8703 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8704 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8705 Result.Base = (Expr*)nullptr; 8706 Result.InvalidBase = false; 8707 Result.Offset = CharUnits::fromQuantity(N); 8708 Result.Designator.setInvalid(); 8709 Result.IsNullPtr = false; 8710 return true; 8711 } else { 8712 // Cast is of an lvalue, no need to change value. 8713 Result.setFrom(Info.Ctx, Value); 8714 return true; 8715 } 8716 } 8717 8718 case CK_ArrayToPointerDecay: { 8719 if (SubExpr->isGLValue()) { 8720 if (!evaluateLValue(SubExpr, Result)) 8721 return false; 8722 } else { 8723 APValue &Value = Info.CurrentCall->createTemporary( 8724 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8725 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8726 return false; 8727 } 8728 // The result is a pointer to the first element of the array. 8729 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8730 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8731 Result.addArray(Info, E, CAT); 8732 else 8733 Result.addUnsizedArray(Info, E, AT->getElementType()); 8734 return true; 8735 } 8736 8737 case CK_FunctionToPointerDecay: 8738 return evaluateLValue(SubExpr, Result); 8739 8740 case CK_LValueToRValue: { 8741 LValue LVal; 8742 if (!evaluateLValue(E->getSubExpr(), LVal)) 8743 return false; 8744 8745 APValue RVal; 8746 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8747 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8748 LVal, RVal)) 8749 return InvalidBaseOK && 8750 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8751 return Success(RVal, E); 8752 } 8753 } 8754 8755 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8756 } 8757 8758 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8759 UnaryExprOrTypeTrait ExprKind) { 8760 // C++ [expr.alignof]p3: 8761 // When alignof is applied to a reference type, the result is the 8762 // alignment of the referenced type. 8763 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8764 T = Ref->getPointeeType(); 8765 8766 if (T.getQualifiers().hasUnaligned()) 8767 return CharUnits::One(); 8768 8769 const bool AlignOfReturnsPreferred = 8770 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8771 8772 // __alignof is defined to return the preferred alignment. 8773 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8774 // as well. 8775 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8776 return Info.Ctx.toCharUnitsFromBits( 8777 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8778 // alignof and _Alignof are defined to return the ABI alignment. 8779 else if (ExprKind == UETT_AlignOf) 8780 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8781 else 8782 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8783 } 8784 8785 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8786 UnaryExprOrTypeTrait ExprKind) { 8787 E = E->IgnoreParens(); 8788 8789 // The kinds of expressions that we have special-case logic here for 8790 // should be kept up to date with the special checks for those 8791 // expressions in Sema. 8792 8793 // alignof decl is always accepted, even if it doesn't make sense: we default 8794 // to 1 in those cases. 8795 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8796 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8797 /*RefAsPointee*/true); 8798 8799 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8800 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8801 /*RefAsPointee*/true); 8802 8803 return GetAlignOfType(Info, E->getType(), ExprKind); 8804 } 8805 8806 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8807 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8808 return Info.Ctx.getDeclAlign(VD); 8809 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8810 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8811 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8812 } 8813 8814 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8815 /// __builtin_is_aligned and __builtin_assume_aligned. 8816 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8817 EvalInfo &Info, APSInt &Alignment) { 8818 if (!EvaluateInteger(E, Alignment, Info)) 8819 return false; 8820 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8821 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8822 return false; 8823 } 8824 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8825 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8826 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8827 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8828 << MaxValue << ForType << Alignment; 8829 return false; 8830 } 8831 // Ensure both alignment and source value have the same bit width so that we 8832 // don't assert when computing the resulting value. 8833 APSInt ExtAlignment = 8834 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8835 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8836 "Alignment should not be changed by ext/trunc"); 8837 Alignment = ExtAlignment; 8838 assert(Alignment.getBitWidth() == SrcWidth); 8839 return true; 8840 } 8841 8842 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8843 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8844 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8845 return true; 8846 8847 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8848 return false; 8849 8850 Result.setInvalid(E); 8851 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8852 Result.addUnsizedArray(Info, E, PointeeTy); 8853 return true; 8854 } 8855 8856 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8857 if (IsStringLiteralCall(E)) 8858 return Success(E); 8859 8860 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8861 return VisitBuiltinCallExpr(E, BuiltinOp); 8862 8863 return visitNonBuiltinCallExpr(E); 8864 } 8865 8866 // Determine if T is a character type for which we guarantee that 8867 // sizeof(T) == 1. 8868 static bool isOneByteCharacterType(QualType T) { 8869 return T->isCharType() || T->isChar8Type(); 8870 } 8871 8872 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8873 unsigned BuiltinOp) { 8874 switch (BuiltinOp) { 8875 case Builtin::BI__builtin_addressof: 8876 return evaluateLValue(E->getArg(0), Result); 8877 case Builtin::BI__builtin_assume_aligned: { 8878 // We need to be very careful here because: if the pointer does not have the 8879 // asserted alignment, then the behavior is undefined, and undefined 8880 // behavior is non-constant. 8881 if (!evaluatePointer(E->getArg(0), Result)) 8882 return false; 8883 8884 LValue OffsetResult(Result); 8885 APSInt Alignment; 8886 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8887 Alignment)) 8888 return false; 8889 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8890 8891 if (E->getNumArgs() > 2) { 8892 APSInt Offset; 8893 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8894 return false; 8895 8896 int64_t AdditionalOffset = -Offset.getZExtValue(); 8897 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8898 } 8899 8900 // If there is a base object, then it must have the correct alignment. 8901 if (OffsetResult.Base) { 8902 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8903 8904 if (BaseAlignment < Align) { 8905 Result.Designator.setInvalid(); 8906 // FIXME: Add support to Diagnostic for long / long long. 8907 CCEDiag(E->getArg(0), 8908 diag::note_constexpr_baa_insufficient_alignment) << 0 8909 << (unsigned)BaseAlignment.getQuantity() 8910 << (unsigned)Align.getQuantity(); 8911 return false; 8912 } 8913 } 8914 8915 // The offset must also have the correct alignment. 8916 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8917 Result.Designator.setInvalid(); 8918 8919 (OffsetResult.Base 8920 ? CCEDiag(E->getArg(0), 8921 diag::note_constexpr_baa_insufficient_alignment) << 1 8922 : CCEDiag(E->getArg(0), 8923 diag::note_constexpr_baa_value_insufficient_alignment)) 8924 << (int)OffsetResult.Offset.getQuantity() 8925 << (unsigned)Align.getQuantity(); 8926 return false; 8927 } 8928 8929 return true; 8930 } 8931 case Builtin::BI__builtin_align_up: 8932 case Builtin::BI__builtin_align_down: { 8933 if (!evaluatePointer(E->getArg(0), Result)) 8934 return false; 8935 APSInt Alignment; 8936 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8937 Alignment)) 8938 return false; 8939 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8940 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8941 // For align_up/align_down, we can return the same value if the alignment 8942 // is known to be greater or equal to the requested value. 8943 if (PtrAlign.getQuantity() >= Alignment) 8944 return true; 8945 8946 // The alignment could be greater than the minimum at run-time, so we cannot 8947 // infer much about the resulting pointer value. One case is possible: 8948 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8949 // can infer the correct index if the requested alignment is smaller than 8950 // the base alignment so we can perform the computation on the offset. 8951 if (BaseAlignment.getQuantity() >= Alignment) { 8952 assert(Alignment.getBitWidth() <= 64 && 8953 "Cannot handle > 64-bit address-space"); 8954 uint64_t Alignment64 = Alignment.getZExtValue(); 8955 CharUnits NewOffset = CharUnits::fromQuantity( 8956 BuiltinOp == Builtin::BI__builtin_align_down 8957 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8958 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8959 Result.adjustOffset(NewOffset - Result.Offset); 8960 // TODO: diagnose out-of-bounds values/only allow for arrays? 8961 return true; 8962 } 8963 // Otherwise, we cannot constant-evaluate the result. 8964 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8965 << Alignment; 8966 return false; 8967 } 8968 case Builtin::BI__builtin_operator_new: 8969 return HandleOperatorNewCall(Info, E, Result); 8970 case Builtin::BI__builtin_launder: 8971 return evaluatePointer(E->getArg(0), Result); 8972 case Builtin::BIstrchr: 8973 case Builtin::BIwcschr: 8974 case Builtin::BImemchr: 8975 case Builtin::BIwmemchr: 8976 if (Info.getLangOpts().CPlusPlus11) 8977 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8978 << /*isConstexpr*/0 << /*isConstructor*/0 8979 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8980 else 8981 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8982 LLVM_FALLTHROUGH; 8983 case Builtin::BI__builtin_strchr: 8984 case Builtin::BI__builtin_wcschr: 8985 case Builtin::BI__builtin_memchr: 8986 case Builtin::BI__builtin_char_memchr: 8987 case Builtin::BI__builtin_wmemchr: { 8988 if (!Visit(E->getArg(0))) 8989 return false; 8990 APSInt Desired; 8991 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8992 return false; 8993 uint64_t MaxLength = uint64_t(-1); 8994 if (BuiltinOp != Builtin::BIstrchr && 8995 BuiltinOp != Builtin::BIwcschr && 8996 BuiltinOp != Builtin::BI__builtin_strchr && 8997 BuiltinOp != Builtin::BI__builtin_wcschr) { 8998 APSInt N; 8999 if (!EvaluateInteger(E->getArg(2), N, Info)) 9000 return false; 9001 MaxLength = N.getExtValue(); 9002 } 9003 // We cannot find the value if there are no candidates to match against. 9004 if (MaxLength == 0u) 9005 return ZeroInitialization(E); 9006 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9007 Result.Designator.Invalid) 9008 return false; 9009 QualType CharTy = Result.Designator.getType(Info.Ctx); 9010 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9011 BuiltinOp == Builtin::BI__builtin_memchr; 9012 assert(IsRawByte || 9013 Info.Ctx.hasSameUnqualifiedType( 9014 CharTy, E->getArg(0)->getType()->getPointeeType())); 9015 // Pointers to const void may point to objects of incomplete type. 9016 if (IsRawByte && CharTy->isIncompleteType()) { 9017 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9018 return false; 9019 } 9020 // Give up on byte-oriented matching against multibyte elements. 9021 // FIXME: We can compare the bytes in the correct order. 9022 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9023 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9024 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9025 << CharTy; 9026 return false; 9027 } 9028 // Figure out what value we're actually looking for (after converting to 9029 // the corresponding unsigned type if necessary). 9030 uint64_t DesiredVal; 9031 bool StopAtNull = false; 9032 switch (BuiltinOp) { 9033 case Builtin::BIstrchr: 9034 case Builtin::BI__builtin_strchr: 9035 // strchr compares directly to the passed integer, and therefore 9036 // always fails if given an int that is not a char. 9037 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9038 E->getArg(1)->getType(), 9039 Desired), 9040 Desired)) 9041 return ZeroInitialization(E); 9042 StopAtNull = true; 9043 LLVM_FALLTHROUGH; 9044 case Builtin::BImemchr: 9045 case Builtin::BI__builtin_memchr: 9046 case Builtin::BI__builtin_char_memchr: 9047 // memchr compares by converting both sides to unsigned char. That's also 9048 // correct for strchr if we get this far (to cope with plain char being 9049 // unsigned in the strchr case). 9050 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9051 break; 9052 9053 case Builtin::BIwcschr: 9054 case Builtin::BI__builtin_wcschr: 9055 StopAtNull = true; 9056 LLVM_FALLTHROUGH; 9057 case Builtin::BIwmemchr: 9058 case Builtin::BI__builtin_wmemchr: 9059 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9060 DesiredVal = Desired.getZExtValue(); 9061 break; 9062 } 9063 9064 for (; MaxLength; --MaxLength) { 9065 APValue Char; 9066 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9067 !Char.isInt()) 9068 return false; 9069 if (Char.getInt().getZExtValue() == DesiredVal) 9070 return true; 9071 if (StopAtNull && !Char.getInt()) 9072 break; 9073 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9074 return false; 9075 } 9076 // Not found: return nullptr. 9077 return ZeroInitialization(E); 9078 } 9079 9080 case Builtin::BImemcpy: 9081 case Builtin::BImemmove: 9082 case Builtin::BIwmemcpy: 9083 case Builtin::BIwmemmove: 9084 if (Info.getLangOpts().CPlusPlus11) 9085 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9086 << /*isConstexpr*/0 << /*isConstructor*/0 9087 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9088 else 9089 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9090 LLVM_FALLTHROUGH; 9091 case Builtin::BI__builtin_memcpy: 9092 case Builtin::BI__builtin_memmove: 9093 case Builtin::BI__builtin_wmemcpy: 9094 case Builtin::BI__builtin_wmemmove: { 9095 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9096 BuiltinOp == Builtin::BIwmemmove || 9097 BuiltinOp == Builtin::BI__builtin_wmemcpy || 9098 BuiltinOp == Builtin::BI__builtin_wmemmove; 9099 bool Move = BuiltinOp == Builtin::BImemmove || 9100 BuiltinOp == Builtin::BIwmemmove || 9101 BuiltinOp == Builtin::BI__builtin_memmove || 9102 BuiltinOp == Builtin::BI__builtin_wmemmove; 9103 9104 // The result of mem* is the first argument. 9105 if (!Visit(E->getArg(0))) 9106 return false; 9107 LValue Dest = Result; 9108 9109 LValue Src; 9110 if (!EvaluatePointer(E->getArg(1), Src, Info)) 9111 return false; 9112 9113 APSInt N; 9114 if (!EvaluateInteger(E->getArg(2), N, Info)) 9115 return false; 9116 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9117 9118 // If the size is zero, we treat this as always being a valid no-op. 9119 // (Even if one of the src and dest pointers is null.) 9120 if (!N) 9121 return true; 9122 9123 // Otherwise, if either of the operands is null, we can't proceed. Don't 9124 // try to determine the type of the copied objects, because there aren't 9125 // any. 9126 if (!Src.Base || !Dest.Base) { 9127 APValue Val; 9128 (!Src.Base ? Src : Dest).moveInto(Val); 9129 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9130 << Move << WChar << !!Src.Base 9131 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9132 return false; 9133 } 9134 if (Src.Designator.Invalid || Dest.Designator.Invalid) 9135 return false; 9136 9137 // We require that Src and Dest are both pointers to arrays of 9138 // trivially-copyable type. (For the wide version, the designator will be 9139 // invalid if the designated object is not a wchar_t.) 9140 QualType T = Dest.Designator.getType(Info.Ctx); 9141 QualType SrcT = Src.Designator.getType(Info.Ctx); 9142 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9143 // FIXME: Consider using our bit_cast implementation to support this. 9144 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9145 return false; 9146 } 9147 if (T->isIncompleteType()) { 9148 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9149 return false; 9150 } 9151 if (!T.isTriviallyCopyableType(Info.Ctx)) { 9152 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9153 return false; 9154 } 9155 9156 // Figure out how many T's we're copying. 9157 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9158 if (!WChar) { 9159 uint64_t Remainder; 9160 llvm::APInt OrigN = N; 9161 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9162 if (Remainder) { 9163 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9164 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9165 << (unsigned)TSize; 9166 return false; 9167 } 9168 } 9169 9170 // Check that the copying will remain within the arrays, just so that we 9171 // can give a more meaningful diagnostic. This implicitly also checks that 9172 // N fits into 64 bits. 9173 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9174 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9175 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9176 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9177 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9178 << N.toString(10, /*Signed*/false); 9179 return false; 9180 } 9181 uint64_t NElems = N.getZExtValue(); 9182 uint64_t NBytes = NElems * TSize; 9183 9184 // Check for overlap. 9185 int Direction = 1; 9186 if (HasSameBase(Src, Dest)) { 9187 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9188 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9189 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9190 // Dest is inside the source region. 9191 if (!Move) { 9192 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9193 return false; 9194 } 9195 // For memmove and friends, copy backwards. 9196 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9197 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9198 return false; 9199 Direction = -1; 9200 } else if (!Move && SrcOffset >= DestOffset && 9201 SrcOffset - DestOffset < NBytes) { 9202 // Src is inside the destination region for memcpy: invalid. 9203 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9204 return false; 9205 } 9206 } 9207 9208 while (true) { 9209 APValue Val; 9210 // FIXME: Set WantObjectRepresentation to true if we're copying a 9211 // char-like type? 9212 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9213 !handleAssignment(Info, E, Dest, T, Val)) 9214 return false; 9215 // Do not iterate past the last element; if we're copying backwards, that 9216 // might take us off the start of the array. 9217 if (--NElems == 0) 9218 return true; 9219 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9220 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9221 return false; 9222 } 9223 } 9224 9225 default: 9226 break; 9227 } 9228 9229 return visitNonBuiltinCallExpr(E); 9230 } 9231 9232 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9233 APValue &Result, const InitListExpr *ILE, 9234 QualType AllocType); 9235 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9236 APValue &Result, 9237 const CXXConstructExpr *CCE, 9238 QualType AllocType); 9239 9240 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9241 if (!Info.getLangOpts().CPlusPlus20) 9242 Info.CCEDiag(E, diag::note_constexpr_new); 9243 9244 // We cannot speculatively evaluate a delete expression. 9245 if (Info.SpeculativeEvaluationDepth) 9246 return false; 9247 9248 FunctionDecl *OperatorNew = E->getOperatorNew(); 9249 9250 bool IsNothrow = false; 9251 bool IsPlacement = false; 9252 if (OperatorNew->isReservedGlobalPlacementOperator() && 9253 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9254 // FIXME Support array placement new. 9255 assert(E->getNumPlacementArgs() == 1); 9256 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9257 return false; 9258 if (Result.Designator.Invalid) 9259 return false; 9260 IsPlacement = true; 9261 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9262 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9263 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9264 return false; 9265 } else if (E->getNumPlacementArgs()) { 9266 // The only new-placement list we support is of the form (std::nothrow). 9267 // 9268 // FIXME: There is no restriction on this, but it's not clear that any 9269 // other form makes any sense. We get here for cases such as: 9270 // 9271 // new (std::align_val_t{N}) X(int) 9272 // 9273 // (which should presumably be valid only if N is a multiple of 9274 // alignof(int), and in any case can't be deallocated unless N is 9275 // alignof(X) and X has new-extended alignment). 9276 if (E->getNumPlacementArgs() != 1 || 9277 !E->getPlacementArg(0)->getType()->isNothrowT()) 9278 return Error(E, diag::note_constexpr_new_placement); 9279 9280 LValue Nothrow; 9281 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9282 return false; 9283 IsNothrow = true; 9284 } 9285 9286 const Expr *Init = E->getInitializer(); 9287 const InitListExpr *ResizedArrayILE = nullptr; 9288 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9289 bool ValueInit = false; 9290 9291 QualType AllocType = E->getAllocatedType(); 9292 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9293 const Expr *Stripped = *ArraySize; 9294 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9295 Stripped = ICE->getSubExpr()) 9296 if (ICE->getCastKind() != CK_NoOp && 9297 ICE->getCastKind() != CK_IntegralCast) 9298 break; 9299 9300 llvm::APSInt ArrayBound; 9301 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9302 return false; 9303 9304 // C++ [expr.new]p9: 9305 // The expression is erroneous if: 9306 // -- [...] its value before converting to size_t [or] applying the 9307 // second standard conversion sequence is less than zero 9308 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9309 if (IsNothrow) 9310 return ZeroInitialization(E); 9311 9312 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9313 << ArrayBound << (*ArraySize)->getSourceRange(); 9314 return false; 9315 } 9316 9317 // -- its value is such that the size of the allocated object would 9318 // exceed the implementation-defined limit 9319 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9320 ArrayBound) > 9321 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9322 if (IsNothrow) 9323 return ZeroInitialization(E); 9324 9325 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9326 << ArrayBound << (*ArraySize)->getSourceRange(); 9327 return false; 9328 } 9329 9330 // -- the new-initializer is a braced-init-list and the number of 9331 // array elements for which initializers are provided [...] 9332 // exceeds the number of elements to initialize 9333 if (!Init) { 9334 // No initialization is performed. 9335 } else if (isa<CXXScalarValueInitExpr>(Init) || 9336 isa<ImplicitValueInitExpr>(Init)) { 9337 ValueInit = true; 9338 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9339 ResizedArrayCCE = CCE; 9340 } else { 9341 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9342 assert(CAT && "unexpected type for array initializer"); 9343 9344 unsigned Bits = 9345 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9346 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9347 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9348 if (InitBound.ugt(AllocBound)) { 9349 if (IsNothrow) 9350 return ZeroInitialization(E); 9351 9352 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9353 << AllocBound.toString(10, /*Signed=*/false) 9354 << InitBound.toString(10, /*Signed=*/false) 9355 << (*ArraySize)->getSourceRange(); 9356 return false; 9357 } 9358 9359 // If the sizes differ, we must have an initializer list, and we need 9360 // special handling for this case when we initialize. 9361 if (InitBound != AllocBound) 9362 ResizedArrayILE = cast<InitListExpr>(Init); 9363 } 9364 9365 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9366 ArrayType::Normal, 0); 9367 } else { 9368 assert(!AllocType->isArrayType() && 9369 "array allocation with non-array new"); 9370 } 9371 9372 APValue *Val; 9373 if (IsPlacement) { 9374 AccessKinds AK = AK_Construct; 9375 struct FindObjectHandler { 9376 EvalInfo &Info; 9377 const Expr *E; 9378 QualType AllocType; 9379 const AccessKinds AccessKind; 9380 APValue *Value; 9381 9382 typedef bool result_type; 9383 bool failed() { return false; } 9384 bool found(APValue &Subobj, QualType SubobjType) { 9385 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9386 // old name of the object to be used to name the new object. 9387 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9388 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9389 SubobjType << AllocType; 9390 return false; 9391 } 9392 Value = &Subobj; 9393 return true; 9394 } 9395 bool found(APSInt &Value, QualType SubobjType) { 9396 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9397 return false; 9398 } 9399 bool found(APFloat &Value, QualType SubobjType) { 9400 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9401 return false; 9402 } 9403 } Handler = {Info, E, AllocType, AK, nullptr}; 9404 9405 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9406 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9407 return false; 9408 9409 Val = Handler.Value; 9410 9411 // [basic.life]p1: 9412 // The lifetime of an object o of type T ends when [...] the storage 9413 // which the object occupies is [...] reused by an object that is not 9414 // nested within o (6.6.2). 9415 *Val = APValue(); 9416 } else { 9417 // Perform the allocation and obtain a pointer to the resulting object. 9418 Val = Info.createHeapAlloc(E, AllocType, Result); 9419 if (!Val) 9420 return false; 9421 } 9422 9423 if (ValueInit) { 9424 ImplicitValueInitExpr VIE(AllocType); 9425 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9426 return false; 9427 } else if (ResizedArrayILE) { 9428 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9429 AllocType)) 9430 return false; 9431 } else if (ResizedArrayCCE) { 9432 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9433 AllocType)) 9434 return false; 9435 } else if (Init) { 9436 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9437 return false; 9438 } else if (!getDefaultInitValue(AllocType, *Val)) { 9439 return false; 9440 } 9441 9442 // Array new returns a pointer to the first element, not a pointer to the 9443 // array. 9444 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9445 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9446 9447 return true; 9448 } 9449 //===----------------------------------------------------------------------===// 9450 // Member Pointer Evaluation 9451 //===----------------------------------------------------------------------===// 9452 9453 namespace { 9454 class MemberPointerExprEvaluator 9455 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9456 MemberPtr &Result; 9457 9458 bool Success(const ValueDecl *D) { 9459 Result = MemberPtr(D); 9460 return true; 9461 } 9462 public: 9463 9464 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9465 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9466 9467 bool Success(const APValue &V, const Expr *E) { 9468 Result.setFrom(V); 9469 return true; 9470 } 9471 bool ZeroInitialization(const Expr *E) { 9472 return Success((const ValueDecl*)nullptr); 9473 } 9474 9475 bool VisitCastExpr(const CastExpr *E); 9476 bool VisitUnaryAddrOf(const UnaryOperator *E); 9477 }; 9478 } // end anonymous namespace 9479 9480 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9481 EvalInfo &Info) { 9482 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9483 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9484 } 9485 9486 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9487 switch (E->getCastKind()) { 9488 default: 9489 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9490 9491 case CK_NullToMemberPointer: 9492 VisitIgnoredValue(E->getSubExpr()); 9493 return ZeroInitialization(E); 9494 9495 case CK_BaseToDerivedMemberPointer: { 9496 if (!Visit(E->getSubExpr())) 9497 return false; 9498 if (E->path_empty()) 9499 return true; 9500 // Base-to-derived member pointer casts store the path in derived-to-base 9501 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9502 // the wrong end of the derived->base arc, so stagger the path by one class. 9503 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9504 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9505 PathI != PathE; ++PathI) { 9506 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9507 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9508 if (!Result.castToDerived(Derived)) 9509 return Error(E); 9510 } 9511 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9512 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9513 return Error(E); 9514 return true; 9515 } 9516 9517 case CK_DerivedToBaseMemberPointer: 9518 if (!Visit(E->getSubExpr())) 9519 return false; 9520 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9521 PathE = E->path_end(); PathI != PathE; ++PathI) { 9522 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9523 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9524 if (!Result.castToBase(Base)) 9525 return Error(E); 9526 } 9527 return true; 9528 } 9529 } 9530 9531 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9532 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9533 // member can be formed. 9534 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9535 } 9536 9537 //===----------------------------------------------------------------------===// 9538 // Record Evaluation 9539 //===----------------------------------------------------------------------===// 9540 9541 namespace { 9542 class RecordExprEvaluator 9543 : public ExprEvaluatorBase<RecordExprEvaluator> { 9544 const LValue &This; 9545 APValue &Result; 9546 public: 9547 9548 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9549 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9550 9551 bool Success(const APValue &V, const Expr *E) { 9552 Result = V; 9553 return true; 9554 } 9555 bool ZeroInitialization(const Expr *E) { 9556 return ZeroInitialization(E, E->getType()); 9557 } 9558 bool ZeroInitialization(const Expr *E, QualType T); 9559 9560 bool VisitCallExpr(const CallExpr *E) { 9561 return handleCallExpr(E, Result, &This); 9562 } 9563 bool VisitCastExpr(const CastExpr *E); 9564 bool VisitInitListExpr(const InitListExpr *E); 9565 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9566 return VisitCXXConstructExpr(E, E->getType()); 9567 } 9568 bool VisitLambdaExpr(const LambdaExpr *E); 9569 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9570 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9571 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9572 bool VisitBinCmp(const BinaryOperator *E); 9573 }; 9574 } 9575 9576 /// Perform zero-initialization on an object of non-union class type. 9577 /// C++11 [dcl.init]p5: 9578 /// To zero-initialize an object or reference of type T means: 9579 /// [...] 9580 /// -- if T is a (possibly cv-qualified) non-union class type, 9581 /// each non-static data member and each base-class subobject is 9582 /// zero-initialized 9583 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9584 const RecordDecl *RD, 9585 const LValue &This, APValue &Result) { 9586 assert(!RD->isUnion() && "Expected non-union class type"); 9587 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9588 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9589 std::distance(RD->field_begin(), RD->field_end())); 9590 9591 if (RD->isInvalidDecl()) return false; 9592 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9593 9594 if (CD) { 9595 unsigned Index = 0; 9596 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9597 End = CD->bases_end(); I != End; ++I, ++Index) { 9598 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9599 LValue Subobject = This; 9600 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9601 return false; 9602 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9603 Result.getStructBase(Index))) 9604 return false; 9605 } 9606 } 9607 9608 for (const auto *I : RD->fields()) { 9609 // -- if T is a reference type, no initialization is performed. 9610 if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9611 continue; 9612 9613 LValue Subobject = This; 9614 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9615 return false; 9616 9617 ImplicitValueInitExpr VIE(I->getType()); 9618 if (!EvaluateInPlace( 9619 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9620 return false; 9621 } 9622 9623 return true; 9624 } 9625 9626 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9627 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9628 if (RD->isInvalidDecl()) return false; 9629 if (RD->isUnion()) { 9630 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9631 // object's first non-static named data member is zero-initialized 9632 RecordDecl::field_iterator I = RD->field_begin(); 9633 while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9634 ++I; 9635 if (I == RD->field_end()) { 9636 Result = APValue((const FieldDecl*)nullptr); 9637 return true; 9638 } 9639 9640 LValue Subobject = This; 9641 if (!HandleLValueMember(Info, E, Subobject, *I)) 9642 return false; 9643 Result = APValue(*I); 9644 ImplicitValueInitExpr VIE(I->getType()); 9645 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9646 } 9647 9648 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9649 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9650 return false; 9651 } 9652 9653 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9654 } 9655 9656 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9657 switch (E->getCastKind()) { 9658 default: 9659 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9660 9661 case CK_ConstructorConversion: 9662 return Visit(E->getSubExpr()); 9663 9664 case CK_DerivedToBase: 9665 case CK_UncheckedDerivedToBase: { 9666 APValue DerivedObject; 9667 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9668 return false; 9669 if (!DerivedObject.isStruct()) 9670 return Error(E->getSubExpr()); 9671 9672 // Derived-to-base rvalue conversion: just slice off the derived part. 9673 APValue *Value = &DerivedObject; 9674 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9675 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9676 PathE = E->path_end(); PathI != PathE; ++PathI) { 9677 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9678 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9679 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9680 RD = Base; 9681 } 9682 Result = *Value; 9683 return true; 9684 } 9685 } 9686 } 9687 9688 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9689 if (E->isTransparent()) 9690 return Visit(E->getInit(0)); 9691 9692 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9693 if (RD->isInvalidDecl()) return false; 9694 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9695 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9696 9697 EvalInfo::EvaluatingConstructorRAII EvalObj( 9698 Info, 9699 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9700 CXXRD && CXXRD->getNumBases()); 9701 9702 if (RD->isUnion()) { 9703 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9704 Result = APValue(Field); 9705 if (!Field) 9706 return true; 9707 9708 // If the initializer list for a union does not contain any elements, the 9709 // first element of the union is value-initialized. 9710 // FIXME: The element should be initialized from an initializer list. 9711 // Is this difference ever observable for initializer lists which 9712 // we don't build? 9713 ImplicitValueInitExpr VIE(Field->getType()); 9714 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9715 9716 LValue Subobject = This; 9717 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9718 return false; 9719 9720 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9721 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9722 isa<CXXDefaultInitExpr>(InitExpr)); 9723 9724 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9725 } 9726 9727 if (!Result.hasValue()) 9728 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9729 std::distance(RD->field_begin(), RD->field_end())); 9730 unsigned ElementNo = 0; 9731 bool Success = true; 9732 9733 // Initialize base classes. 9734 if (CXXRD && CXXRD->getNumBases()) { 9735 for (const auto &Base : CXXRD->bases()) { 9736 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9737 const Expr *Init = E->getInit(ElementNo); 9738 9739 LValue Subobject = This; 9740 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9741 return false; 9742 9743 APValue &FieldVal = Result.getStructBase(ElementNo); 9744 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9745 if (!Info.noteFailure()) 9746 return false; 9747 Success = false; 9748 } 9749 ++ElementNo; 9750 } 9751 9752 EvalObj.finishedConstructingBases(); 9753 } 9754 9755 // Initialize members. 9756 for (const auto *Field : RD->fields()) { 9757 // Anonymous bit-fields are not considered members of the class for 9758 // purposes of aggregate initialization. 9759 if (Field->isUnnamedBitfield()) 9760 continue; 9761 9762 LValue Subobject = This; 9763 9764 bool HaveInit = ElementNo < E->getNumInits(); 9765 9766 // FIXME: Diagnostics here should point to the end of the initializer 9767 // list, not the start. 9768 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9769 Subobject, Field, &Layout)) 9770 return false; 9771 9772 // Perform an implicit value-initialization for members beyond the end of 9773 // the initializer list. 9774 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9775 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9776 9777 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9778 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9779 isa<CXXDefaultInitExpr>(Init)); 9780 9781 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9782 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9783 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9784 FieldVal, Field))) { 9785 if (!Info.noteFailure()) 9786 return false; 9787 Success = false; 9788 } 9789 } 9790 9791 EvalObj.finishedConstructingFields(); 9792 9793 return Success; 9794 } 9795 9796 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9797 QualType T) { 9798 // Note that E's type is not necessarily the type of our class here; we might 9799 // be initializing an array element instead. 9800 const CXXConstructorDecl *FD = E->getConstructor(); 9801 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9802 9803 bool ZeroInit = E->requiresZeroInitialization(); 9804 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9805 // If we've already performed zero-initialization, we're already done. 9806 if (Result.hasValue()) 9807 return true; 9808 9809 if (ZeroInit) 9810 return ZeroInitialization(E, T); 9811 9812 return getDefaultInitValue(T, Result); 9813 } 9814 9815 const FunctionDecl *Definition = nullptr; 9816 auto Body = FD->getBody(Definition); 9817 9818 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9819 return false; 9820 9821 // Avoid materializing a temporary for an elidable copy/move constructor. 9822 if (E->isElidable() && !ZeroInit) 9823 if (const MaterializeTemporaryExpr *ME 9824 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9825 return Visit(ME->getSubExpr()); 9826 9827 if (ZeroInit && !ZeroInitialization(E, T)) 9828 return false; 9829 9830 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9831 return HandleConstructorCall(E, This, Args, 9832 cast<CXXConstructorDecl>(Definition), Info, 9833 Result); 9834 } 9835 9836 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9837 const CXXInheritedCtorInitExpr *E) { 9838 if (!Info.CurrentCall) { 9839 assert(Info.checkingPotentialConstantExpression()); 9840 return false; 9841 } 9842 9843 const CXXConstructorDecl *FD = E->getConstructor(); 9844 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9845 return false; 9846 9847 const FunctionDecl *Definition = nullptr; 9848 auto Body = FD->getBody(Definition); 9849 9850 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9851 return false; 9852 9853 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9854 cast<CXXConstructorDecl>(Definition), Info, 9855 Result); 9856 } 9857 9858 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9859 const CXXStdInitializerListExpr *E) { 9860 const ConstantArrayType *ArrayType = 9861 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9862 9863 LValue Array; 9864 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9865 return false; 9866 9867 // Get a pointer to the first element of the array. 9868 Array.addArray(Info, E, ArrayType); 9869 9870 auto InvalidType = [&] { 9871 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9872 << E->getType(); 9873 return false; 9874 }; 9875 9876 // FIXME: Perform the checks on the field types in SemaInit. 9877 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9878 RecordDecl::field_iterator Field = Record->field_begin(); 9879 if (Field == Record->field_end()) 9880 return InvalidType(); 9881 9882 // Start pointer. 9883 if (!Field->getType()->isPointerType() || 9884 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9885 ArrayType->getElementType())) 9886 return InvalidType(); 9887 9888 // FIXME: What if the initializer_list type has base classes, etc? 9889 Result = APValue(APValue::UninitStruct(), 0, 2); 9890 Array.moveInto(Result.getStructField(0)); 9891 9892 if (++Field == Record->field_end()) 9893 return InvalidType(); 9894 9895 if (Field->getType()->isPointerType() && 9896 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9897 ArrayType->getElementType())) { 9898 // End pointer. 9899 if (!HandleLValueArrayAdjustment(Info, E, Array, 9900 ArrayType->getElementType(), 9901 ArrayType->getSize().getZExtValue())) 9902 return false; 9903 Array.moveInto(Result.getStructField(1)); 9904 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9905 // Length. 9906 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9907 else 9908 return InvalidType(); 9909 9910 if (++Field != Record->field_end()) 9911 return InvalidType(); 9912 9913 return true; 9914 } 9915 9916 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9917 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9918 if (ClosureClass->isInvalidDecl()) 9919 return false; 9920 9921 const size_t NumFields = 9922 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9923 9924 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9925 E->capture_init_end()) && 9926 "The number of lambda capture initializers should equal the number of " 9927 "fields within the closure type"); 9928 9929 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9930 // Iterate through all the lambda's closure object's fields and initialize 9931 // them. 9932 auto *CaptureInitIt = E->capture_init_begin(); 9933 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9934 bool Success = true; 9935 for (const auto *Field : ClosureClass->fields()) { 9936 assert(CaptureInitIt != E->capture_init_end()); 9937 // Get the initializer for this field 9938 Expr *const CurFieldInit = *CaptureInitIt++; 9939 9940 // If there is no initializer, either this is a VLA or an error has 9941 // occurred. 9942 if (!CurFieldInit) 9943 return Error(E); 9944 9945 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9946 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9947 if (!Info.keepEvaluatingAfterFailure()) 9948 return false; 9949 Success = false; 9950 } 9951 ++CaptureIt; 9952 } 9953 return Success; 9954 } 9955 9956 static bool EvaluateRecord(const Expr *E, const LValue &This, 9957 APValue &Result, EvalInfo &Info) { 9958 assert(E->isRValue() && E->getType()->isRecordType() && 9959 "can't evaluate expression as a record rvalue"); 9960 return RecordExprEvaluator(Info, This, Result).Visit(E); 9961 } 9962 9963 //===----------------------------------------------------------------------===// 9964 // Temporary Evaluation 9965 // 9966 // Temporaries are represented in the AST as rvalues, but generally behave like 9967 // lvalues. The full-object of which the temporary is a subobject is implicitly 9968 // materialized so that a reference can bind to it. 9969 //===----------------------------------------------------------------------===// 9970 namespace { 9971 class TemporaryExprEvaluator 9972 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9973 public: 9974 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9975 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9976 9977 /// Visit an expression which constructs the value of this temporary. 9978 bool VisitConstructExpr(const Expr *E) { 9979 APValue &Value = Info.CurrentCall->createTemporary( 9980 E, E->getType(), ScopeKind::FullExpression, Result); 9981 return EvaluateInPlace(Value, Info, Result, E); 9982 } 9983 9984 bool VisitCastExpr(const CastExpr *E) { 9985 switch (E->getCastKind()) { 9986 default: 9987 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9988 9989 case CK_ConstructorConversion: 9990 return VisitConstructExpr(E->getSubExpr()); 9991 } 9992 } 9993 bool VisitInitListExpr(const InitListExpr *E) { 9994 return VisitConstructExpr(E); 9995 } 9996 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9997 return VisitConstructExpr(E); 9998 } 9999 bool VisitCallExpr(const CallExpr *E) { 10000 return VisitConstructExpr(E); 10001 } 10002 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10003 return VisitConstructExpr(E); 10004 } 10005 bool VisitLambdaExpr(const LambdaExpr *E) { 10006 return VisitConstructExpr(E); 10007 } 10008 }; 10009 } // end anonymous namespace 10010 10011 /// Evaluate an expression of record type as a temporary. 10012 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10013 assert(E->isRValue() && E->getType()->isRecordType()); 10014 return TemporaryExprEvaluator(Info, Result).Visit(E); 10015 } 10016 10017 //===----------------------------------------------------------------------===// 10018 // Vector Evaluation 10019 //===----------------------------------------------------------------------===// 10020 10021 namespace { 10022 class VectorExprEvaluator 10023 : public ExprEvaluatorBase<VectorExprEvaluator> { 10024 APValue &Result; 10025 public: 10026 10027 VectorExprEvaluator(EvalInfo &info, APValue &Result) 10028 : ExprEvaluatorBaseTy(info), Result(Result) {} 10029 10030 bool Success(ArrayRef<APValue> V, const Expr *E) { 10031 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10032 // FIXME: remove this APValue copy. 10033 Result = APValue(V.data(), V.size()); 10034 return true; 10035 } 10036 bool Success(const APValue &V, const Expr *E) { 10037 assert(V.isVector()); 10038 Result = V; 10039 return true; 10040 } 10041 bool ZeroInitialization(const Expr *E); 10042 10043 bool VisitUnaryReal(const UnaryOperator *E) 10044 { return Visit(E->getSubExpr()); } 10045 bool VisitCastExpr(const CastExpr* E); 10046 bool VisitInitListExpr(const InitListExpr *E); 10047 bool VisitUnaryImag(const UnaryOperator *E); 10048 bool VisitBinaryOperator(const BinaryOperator *E); 10049 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10050 // conditional select), shufflevector, ExtVectorElementExpr 10051 }; 10052 } // end anonymous namespace 10053 10054 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10055 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10056 return VectorExprEvaluator(Info, Result).Visit(E); 10057 } 10058 10059 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10060 const VectorType *VTy = E->getType()->castAs<VectorType>(); 10061 unsigned NElts = VTy->getNumElements(); 10062 10063 const Expr *SE = E->getSubExpr(); 10064 QualType SETy = SE->getType(); 10065 10066 switch (E->getCastKind()) { 10067 case CK_VectorSplat: { 10068 APValue Val = APValue(); 10069 if (SETy->isIntegerType()) { 10070 APSInt IntResult; 10071 if (!EvaluateInteger(SE, IntResult, Info)) 10072 return false; 10073 Val = APValue(std::move(IntResult)); 10074 } else if (SETy->isRealFloatingType()) { 10075 APFloat FloatResult(0.0); 10076 if (!EvaluateFloat(SE, FloatResult, Info)) 10077 return false; 10078 Val = APValue(std::move(FloatResult)); 10079 } else { 10080 return Error(E); 10081 } 10082 10083 // Splat and create vector APValue. 10084 SmallVector<APValue, 4> Elts(NElts, Val); 10085 return Success(Elts, E); 10086 } 10087 case CK_BitCast: { 10088 // Evaluate the operand into an APInt we can extract from. 10089 llvm::APInt SValInt; 10090 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10091 return false; 10092 // Extract the elements 10093 QualType EltTy = VTy->getElementType(); 10094 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10095 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10096 SmallVector<APValue, 4> Elts; 10097 if (EltTy->isRealFloatingType()) { 10098 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10099 unsigned FloatEltSize = EltSize; 10100 if (&Sem == &APFloat::x87DoubleExtended()) 10101 FloatEltSize = 80; 10102 for (unsigned i = 0; i < NElts; i++) { 10103 llvm::APInt Elt; 10104 if (BigEndian) 10105 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10106 else 10107 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10108 Elts.push_back(APValue(APFloat(Sem, Elt))); 10109 } 10110 } else if (EltTy->isIntegerType()) { 10111 for (unsigned i = 0; i < NElts; i++) { 10112 llvm::APInt Elt; 10113 if (BigEndian) 10114 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10115 else 10116 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10117 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 10118 } 10119 } else { 10120 return Error(E); 10121 } 10122 return Success(Elts, E); 10123 } 10124 default: 10125 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10126 } 10127 } 10128 10129 bool 10130 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10131 const VectorType *VT = E->getType()->castAs<VectorType>(); 10132 unsigned NumInits = E->getNumInits(); 10133 unsigned NumElements = VT->getNumElements(); 10134 10135 QualType EltTy = VT->getElementType(); 10136 SmallVector<APValue, 4> Elements; 10137 10138 // The number of initializers can be less than the number of 10139 // vector elements. For OpenCL, this can be due to nested vector 10140 // initialization. For GCC compatibility, missing trailing elements 10141 // should be initialized with zeroes. 10142 unsigned CountInits = 0, CountElts = 0; 10143 while (CountElts < NumElements) { 10144 // Handle nested vector initialization. 10145 if (CountInits < NumInits 10146 && E->getInit(CountInits)->getType()->isVectorType()) { 10147 APValue v; 10148 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10149 return Error(E); 10150 unsigned vlen = v.getVectorLength(); 10151 for (unsigned j = 0; j < vlen; j++) 10152 Elements.push_back(v.getVectorElt(j)); 10153 CountElts += vlen; 10154 } else if (EltTy->isIntegerType()) { 10155 llvm::APSInt sInt(32); 10156 if (CountInits < NumInits) { 10157 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10158 return false; 10159 } else // trailing integer zero. 10160 sInt = Info.Ctx.MakeIntValue(0, EltTy); 10161 Elements.push_back(APValue(sInt)); 10162 CountElts++; 10163 } else { 10164 llvm::APFloat f(0.0); 10165 if (CountInits < NumInits) { 10166 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10167 return false; 10168 } else // trailing float zero. 10169 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10170 Elements.push_back(APValue(f)); 10171 CountElts++; 10172 } 10173 CountInits++; 10174 } 10175 return Success(Elements, E); 10176 } 10177 10178 bool 10179 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10180 const auto *VT = E->getType()->castAs<VectorType>(); 10181 QualType EltTy = VT->getElementType(); 10182 APValue ZeroElement; 10183 if (EltTy->isIntegerType()) 10184 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10185 else 10186 ZeroElement = 10187 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10188 10189 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10190 return Success(Elements, E); 10191 } 10192 10193 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10194 VisitIgnoredValue(E->getSubExpr()); 10195 return ZeroInitialization(E); 10196 } 10197 10198 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10199 BinaryOperatorKind Op = E->getOpcode(); 10200 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10201 "Operation not supported on vector types"); 10202 10203 if (Op == BO_Comma) 10204 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10205 10206 Expr *LHS = E->getLHS(); 10207 Expr *RHS = E->getRHS(); 10208 10209 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10210 "Must both be vector types"); 10211 // Checking JUST the types are the same would be fine, except shifts don't 10212 // need to have their types be the same (since you always shift by an int). 10213 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10214 E->getType()->getAs<VectorType>()->getNumElements() && 10215 RHS->getType()->getAs<VectorType>()->getNumElements() == 10216 E->getType()->getAs<VectorType>()->getNumElements() && 10217 "All operands must be the same size."); 10218 10219 APValue LHSValue; 10220 APValue RHSValue; 10221 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10222 if (!LHSOK && !Info.noteFailure()) 10223 return false; 10224 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10225 return false; 10226 10227 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10228 return false; 10229 10230 return Success(LHSValue, E); 10231 } 10232 10233 //===----------------------------------------------------------------------===// 10234 // Array Evaluation 10235 //===----------------------------------------------------------------------===// 10236 10237 namespace { 10238 class ArrayExprEvaluator 10239 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10240 const LValue &This; 10241 APValue &Result; 10242 public: 10243 10244 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10245 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10246 10247 bool Success(const APValue &V, const Expr *E) { 10248 assert(V.isArray() && "expected array"); 10249 Result = V; 10250 return true; 10251 } 10252 10253 bool ZeroInitialization(const Expr *E) { 10254 const ConstantArrayType *CAT = 10255 Info.Ctx.getAsConstantArrayType(E->getType()); 10256 if (!CAT) { 10257 if (E->getType()->isIncompleteArrayType()) { 10258 // We can be asked to zero-initialize a flexible array member; this 10259 // is represented as an ImplicitValueInitExpr of incomplete array 10260 // type. In this case, the array has zero elements. 10261 Result = APValue(APValue::UninitArray(), 0, 0); 10262 return true; 10263 } 10264 // FIXME: We could handle VLAs here. 10265 return Error(E); 10266 } 10267 10268 Result = APValue(APValue::UninitArray(), 0, 10269 CAT->getSize().getZExtValue()); 10270 if (!Result.hasArrayFiller()) return true; 10271 10272 // Zero-initialize all elements. 10273 LValue Subobject = This; 10274 Subobject.addArray(Info, E, CAT); 10275 ImplicitValueInitExpr VIE(CAT->getElementType()); 10276 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10277 } 10278 10279 bool VisitCallExpr(const CallExpr *E) { 10280 return handleCallExpr(E, Result, &This); 10281 } 10282 bool VisitInitListExpr(const InitListExpr *E, 10283 QualType AllocType = QualType()); 10284 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10285 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10286 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10287 const LValue &Subobject, 10288 APValue *Value, QualType Type); 10289 bool VisitStringLiteral(const StringLiteral *E, 10290 QualType AllocType = QualType()) { 10291 expandStringLiteral(Info, E, Result, AllocType); 10292 return true; 10293 } 10294 }; 10295 } // end anonymous namespace 10296 10297 static bool EvaluateArray(const Expr *E, const LValue &This, 10298 APValue &Result, EvalInfo &Info) { 10299 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10300 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10301 } 10302 10303 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10304 APValue &Result, const InitListExpr *ILE, 10305 QualType AllocType) { 10306 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10307 "not an array rvalue"); 10308 return ArrayExprEvaluator(Info, This, Result) 10309 .VisitInitListExpr(ILE, AllocType); 10310 } 10311 10312 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10313 APValue &Result, 10314 const CXXConstructExpr *CCE, 10315 QualType AllocType) { 10316 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10317 "not an array rvalue"); 10318 return ArrayExprEvaluator(Info, This, Result) 10319 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10320 } 10321 10322 // Return true iff the given array filler may depend on the element index. 10323 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10324 // For now, just allow non-class value-initialization and initialization 10325 // lists comprised of them. 10326 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10327 return false; 10328 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10329 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10330 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10331 return true; 10332 } 10333 return false; 10334 } 10335 return true; 10336 } 10337 10338 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10339 QualType AllocType) { 10340 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10341 AllocType.isNull() ? E->getType() : AllocType); 10342 if (!CAT) 10343 return Error(E); 10344 10345 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10346 // an appropriately-typed string literal enclosed in braces. 10347 if (E->isStringLiteralInit()) { 10348 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10349 // FIXME: Support ObjCEncodeExpr here once we support it in 10350 // ArrayExprEvaluator generally. 10351 if (!SL) 10352 return Error(E); 10353 return VisitStringLiteral(SL, AllocType); 10354 } 10355 10356 bool Success = true; 10357 10358 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10359 "zero-initialized array shouldn't have any initialized elts"); 10360 APValue Filler; 10361 if (Result.isArray() && Result.hasArrayFiller()) 10362 Filler = Result.getArrayFiller(); 10363 10364 unsigned NumEltsToInit = E->getNumInits(); 10365 unsigned NumElts = CAT->getSize().getZExtValue(); 10366 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10367 10368 // If the initializer might depend on the array index, run it for each 10369 // array element. 10370 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10371 NumEltsToInit = NumElts; 10372 10373 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10374 << NumEltsToInit << ".\n"); 10375 10376 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10377 10378 // If the array was previously zero-initialized, preserve the 10379 // zero-initialized values. 10380 if (Filler.hasValue()) { 10381 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10382 Result.getArrayInitializedElt(I) = Filler; 10383 if (Result.hasArrayFiller()) 10384 Result.getArrayFiller() = Filler; 10385 } 10386 10387 LValue Subobject = This; 10388 Subobject.addArray(Info, E, CAT); 10389 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10390 const Expr *Init = 10391 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10392 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10393 Info, Subobject, Init) || 10394 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10395 CAT->getElementType(), 1)) { 10396 if (!Info.noteFailure()) 10397 return false; 10398 Success = false; 10399 } 10400 } 10401 10402 if (!Result.hasArrayFiller()) 10403 return Success; 10404 10405 // If we get here, we have a trivial filler, which we can just evaluate 10406 // once and splat over the rest of the array elements. 10407 assert(FillerExpr && "no array filler for incomplete init list"); 10408 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10409 FillerExpr) && Success; 10410 } 10411 10412 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10413 LValue CommonLV; 10414 if (E->getCommonExpr() && 10415 !Evaluate(Info.CurrentCall->createTemporary( 10416 E->getCommonExpr(), 10417 getStorageType(Info.Ctx, E->getCommonExpr()), 10418 ScopeKind::FullExpression, CommonLV), 10419 Info, E->getCommonExpr()->getSourceExpr())) 10420 return false; 10421 10422 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10423 10424 uint64_t Elements = CAT->getSize().getZExtValue(); 10425 Result = APValue(APValue::UninitArray(), Elements, Elements); 10426 10427 LValue Subobject = This; 10428 Subobject.addArray(Info, E, CAT); 10429 10430 bool Success = true; 10431 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10432 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10433 Info, Subobject, E->getSubExpr()) || 10434 !HandleLValueArrayAdjustment(Info, E, Subobject, 10435 CAT->getElementType(), 1)) { 10436 if (!Info.noteFailure()) 10437 return false; 10438 Success = false; 10439 } 10440 } 10441 10442 return Success; 10443 } 10444 10445 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10446 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10447 } 10448 10449 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10450 const LValue &Subobject, 10451 APValue *Value, 10452 QualType Type) { 10453 bool HadZeroInit = Value->hasValue(); 10454 10455 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10456 unsigned N = CAT->getSize().getZExtValue(); 10457 10458 // Preserve the array filler if we had prior zero-initialization. 10459 APValue Filler = 10460 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10461 : APValue(); 10462 10463 *Value = APValue(APValue::UninitArray(), N, N); 10464 10465 if (HadZeroInit) 10466 for (unsigned I = 0; I != N; ++I) 10467 Value->getArrayInitializedElt(I) = Filler; 10468 10469 // Initialize the elements. 10470 LValue ArrayElt = Subobject; 10471 ArrayElt.addArray(Info, E, CAT); 10472 for (unsigned I = 0; I != N; ++I) 10473 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10474 CAT->getElementType()) || 10475 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10476 CAT->getElementType(), 1)) 10477 return false; 10478 10479 return true; 10480 } 10481 10482 if (!Type->isRecordType()) 10483 return Error(E); 10484 10485 return RecordExprEvaluator(Info, Subobject, *Value) 10486 .VisitCXXConstructExpr(E, Type); 10487 } 10488 10489 //===----------------------------------------------------------------------===// 10490 // Integer Evaluation 10491 // 10492 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10493 // types and back in constant folding. Integer values are thus represented 10494 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10495 //===----------------------------------------------------------------------===// 10496 10497 namespace { 10498 class IntExprEvaluator 10499 : public ExprEvaluatorBase<IntExprEvaluator> { 10500 APValue &Result; 10501 public: 10502 IntExprEvaluator(EvalInfo &info, APValue &result) 10503 : ExprEvaluatorBaseTy(info), Result(result) {} 10504 10505 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10506 assert(E->getType()->isIntegralOrEnumerationType() && 10507 "Invalid evaluation result."); 10508 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10509 "Invalid evaluation result."); 10510 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10511 "Invalid evaluation result."); 10512 Result = APValue(SI); 10513 return true; 10514 } 10515 bool Success(const llvm::APSInt &SI, const Expr *E) { 10516 return Success(SI, E, Result); 10517 } 10518 10519 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10520 assert(E->getType()->isIntegralOrEnumerationType() && 10521 "Invalid evaluation result."); 10522 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10523 "Invalid evaluation result."); 10524 Result = APValue(APSInt(I)); 10525 Result.getInt().setIsUnsigned( 10526 E->getType()->isUnsignedIntegerOrEnumerationType()); 10527 return true; 10528 } 10529 bool Success(const llvm::APInt &I, const Expr *E) { 10530 return Success(I, E, Result); 10531 } 10532 10533 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10534 assert(E->getType()->isIntegralOrEnumerationType() && 10535 "Invalid evaluation result."); 10536 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10537 return true; 10538 } 10539 bool Success(uint64_t Value, const Expr *E) { 10540 return Success(Value, E, Result); 10541 } 10542 10543 bool Success(CharUnits Size, const Expr *E) { 10544 return Success(Size.getQuantity(), E); 10545 } 10546 10547 bool Success(const APValue &V, const Expr *E) { 10548 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10549 Result = V; 10550 return true; 10551 } 10552 return Success(V.getInt(), E); 10553 } 10554 10555 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10556 10557 //===--------------------------------------------------------------------===// 10558 // Visitor Methods 10559 //===--------------------------------------------------------------------===// 10560 10561 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10562 return Success(E->getValue(), E); 10563 } 10564 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10565 return Success(E->getValue(), E); 10566 } 10567 10568 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10569 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10570 if (CheckReferencedDecl(E, E->getDecl())) 10571 return true; 10572 10573 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10574 } 10575 bool VisitMemberExpr(const MemberExpr *E) { 10576 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10577 VisitIgnoredBaseExpression(E->getBase()); 10578 return true; 10579 } 10580 10581 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10582 } 10583 10584 bool VisitCallExpr(const CallExpr *E); 10585 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10586 bool VisitBinaryOperator(const BinaryOperator *E); 10587 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10588 bool VisitUnaryOperator(const UnaryOperator *E); 10589 10590 bool VisitCastExpr(const CastExpr* E); 10591 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10592 10593 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10594 return Success(E->getValue(), E); 10595 } 10596 10597 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10598 return Success(E->getValue(), E); 10599 } 10600 10601 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10602 if (Info.ArrayInitIndex == uint64_t(-1)) { 10603 // We were asked to evaluate this subexpression independent of the 10604 // enclosing ArrayInitLoopExpr. We can't do that. 10605 Info.FFDiag(E); 10606 return false; 10607 } 10608 return Success(Info.ArrayInitIndex, E); 10609 } 10610 10611 // Note, GNU defines __null as an integer, not a pointer. 10612 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10613 return ZeroInitialization(E); 10614 } 10615 10616 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10617 return Success(E->getValue(), E); 10618 } 10619 10620 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10621 return Success(E->getValue(), E); 10622 } 10623 10624 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10625 return Success(E->getValue(), E); 10626 } 10627 10628 bool VisitUnaryReal(const UnaryOperator *E); 10629 bool VisitUnaryImag(const UnaryOperator *E); 10630 10631 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10632 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10633 bool VisitSourceLocExpr(const SourceLocExpr *E); 10634 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10635 bool VisitRequiresExpr(const RequiresExpr *E); 10636 // FIXME: Missing: array subscript of vector, member of vector 10637 }; 10638 10639 class FixedPointExprEvaluator 10640 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10641 APValue &Result; 10642 10643 public: 10644 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10645 : ExprEvaluatorBaseTy(info), Result(result) {} 10646 10647 bool Success(const llvm::APInt &I, const Expr *E) { 10648 return Success( 10649 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10650 } 10651 10652 bool Success(uint64_t Value, const Expr *E) { 10653 return Success( 10654 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10655 } 10656 10657 bool Success(const APValue &V, const Expr *E) { 10658 return Success(V.getFixedPoint(), E); 10659 } 10660 10661 bool Success(const APFixedPoint &V, const Expr *E) { 10662 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10663 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10664 "Invalid evaluation result."); 10665 Result = APValue(V); 10666 return true; 10667 } 10668 10669 //===--------------------------------------------------------------------===// 10670 // Visitor Methods 10671 //===--------------------------------------------------------------------===// 10672 10673 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10674 return Success(E->getValue(), E); 10675 } 10676 10677 bool VisitCastExpr(const CastExpr *E); 10678 bool VisitUnaryOperator(const UnaryOperator *E); 10679 bool VisitBinaryOperator(const BinaryOperator *E); 10680 }; 10681 } // end anonymous namespace 10682 10683 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10684 /// produce either the integer value or a pointer. 10685 /// 10686 /// GCC has a heinous extension which folds casts between pointer types and 10687 /// pointer-sized integral types. We support this by allowing the evaluation of 10688 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10689 /// Some simple arithmetic on such values is supported (they are treated much 10690 /// like char*). 10691 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10692 EvalInfo &Info) { 10693 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10694 return IntExprEvaluator(Info, Result).Visit(E); 10695 } 10696 10697 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10698 APValue Val; 10699 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10700 return false; 10701 if (!Val.isInt()) { 10702 // FIXME: It would be better to produce the diagnostic for casting 10703 // a pointer to an integer. 10704 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10705 return false; 10706 } 10707 Result = Val.getInt(); 10708 return true; 10709 } 10710 10711 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10712 APValue Evaluated = E->EvaluateInContext( 10713 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10714 return Success(Evaluated, E); 10715 } 10716 10717 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10718 EvalInfo &Info) { 10719 if (E->getType()->isFixedPointType()) { 10720 APValue Val; 10721 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10722 return false; 10723 if (!Val.isFixedPoint()) 10724 return false; 10725 10726 Result = Val.getFixedPoint(); 10727 return true; 10728 } 10729 return false; 10730 } 10731 10732 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10733 EvalInfo &Info) { 10734 if (E->getType()->isIntegerType()) { 10735 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10736 APSInt Val; 10737 if (!EvaluateInteger(E, Val, Info)) 10738 return false; 10739 Result = APFixedPoint(Val, FXSema); 10740 return true; 10741 } else if (E->getType()->isFixedPointType()) { 10742 return EvaluateFixedPoint(E, Result, Info); 10743 } 10744 return false; 10745 } 10746 10747 /// Check whether the given declaration can be directly converted to an integral 10748 /// rvalue. If not, no diagnostic is produced; there are other things we can 10749 /// try. 10750 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10751 // Enums are integer constant exprs. 10752 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10753 // Check for signedness/width mismatches between E type and ECD value. 10754 bool SameSign = (ECD->getInitVal().isSigned() 10755 == E->getType()->isSignedIntegerOrEnumerationType()); 10756 bool SameWidth = (ECD->getInitVal().getBitWidth() 10757 == Info.Ctx.getIntWidth(E->getType())); 10758 if (SameSign && SameWidth) 10759 return Success(ECD->getInitVal(), E); 10760 else { 10761 // Get rid of mismatch (otherwise Success assertions will fail) 10762 // by computing a new value matching the type of E. 10763 llvm::APSInt Val = ECD->getInitVal(); 10764 if (!SameSign) 10765 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10766 if (!SameWidth) 10767 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10768 return Success(Val, E); 10769 } 10770 } 10771 return false; 10772 } 10773 10774 /// Values returned by __builtin_classify_type, chosen to match the values 10775 /// produced by GCC's builtin. 10776 enum class GCCTypeClass { 10777 None = -1, 10778 Void = 0, 10779 Integer = 1, 10780 // GCC reserves 2 for character types, but instead classifies them as 10781 // integers. 10782 Enum = 3, 10783 Bool = 4, 10784 Pointer = 5, 10785 // GCC reserves 6 for references, but appears to never use it (because 10786 // expressions never have reference type, presumably). 10787 PointerToDataMember = 7, 10788 RealFloat = 8, 10789 Complex = 9, 10790 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10791 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10792 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10793 // uses 12 for that purpose, same as for a class or struct. Maybe it 10794 // internally implements a pointer to member as a struct? Who knows. 10795 PointerToMemberFunction = 12, // Not a bug, see above. 10796 ClassOrStruct = 12, 10797 Union = 13, 10798 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10799 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10800 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10801 // literals. 10802 }; 10803 10804 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10805 /// as GCC. 10806 static GCCTypeClass 10807 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10808 assert(!T->isDependentType() && "unexpected dependent type"); 10809 10810 QualType CanTy = T.getCanonicalType(); 10811 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10812 10813 switch (CanTy->getTypeClass()) { 10814 #define TYPE(ID, BASE) 10815 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10816 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10817 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10818 #include "clang/AST/TypeNodes.inc" 10819 case Type::Auto: 10820 case Type::DeducedTemplateSpecialization: 10821 llvm_unreachable("unexpected non-canonical or dependent type"); 10822 10823 case Type::Builtin: 10824 switch (BT->getKind()) { 10825 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10826 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10827 case BuiltinType::ID: return GCCTypeClass::Integer; 10828 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10829 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10830 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10831 case BuiltinType::ID: break; 10832 #include "clang/AST/BuiltinTypes.def" 10833 case BuiltinType::Void: 10834 return GCCTypeClass::Void; 10835 10836 case BuiltinType::Bool: 10837 return GCCTypeClass::Bool; 10838 10839 case BuiltinType::Char_U: 10840 case BuiltinType::UChar: 10841 case BuiltinType::WChar_U: 10842 case BuiltinType::Char8: 10843 case BuiltinType::Char16: 10844 case BuiltinType::Char32: 10845 case BuiltinType::UShort: 10846 case BuiltinType::UInt: 10847 case BuiltinType::ULong: 10848 case BuiltinType::ULongLong: 10849 case BuiltinType::UInt128: 10850 return GCCTypeClass::Integer; 10851 10852 case BuiltinType::UShortAccum: 10853 case BuiltinType::UAccum: 10854 case BuiltinType::ULongAccum: 10855 case BuiltinType::UShortFract: 10856 case BuiltinType::UFract: 10857 case BuiltinType::ULongFract: 10858 case BuiltinType::SatUShortAccum: 10859 case BuiltinType::SatUAccum: 10860 case BuiltinType::SatULongAccum: 10861 case BuiltinType::SatUShortFract: 10862 case BuiltinType::SatUFract: 10863 case BuiltinType::SatULongFract: 10864 return GCCTypeClass::None; 10865 10866 case BuiltinType::NullPtr: 10867 10868 case BuiltinType::ObjCId: 10869 case BuiltinType::ObjCClass: 10870 case BuiltinType::ObjCSel: 10871 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10872 case BuiltinType::Id: 10873 #include "clang/Basic/OpenCLImageTypes.def" 10874 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10875 case BuiltinType::Id: 10876 #include "clang/Basic/OpenCLExtensionTypes.def" 10877 case BuiltinType::OCLSampler: 10878 case BuiltinType::OCLEvent: 10879 case BuiltinType::OCLClkEvent: 10880 case BuiltinType::OCLQueue: 10881 case BuiltinType::OCLReserveID: 10882 #define SVE_TYPE(Name, Id, SingletonId) \ 10883 case BuiltinType::Id: 10884 #include "clang/Basic/AArch64SVEACLETypes.def" 10885 return GCCTypeClass::None; 10886 10887 case BuiltinType::Dependent: 10888 llvm_unreachable("unexpected dependent type"); 10889 }; 10890 llvm_unreachable("unexpected placeholder type"); 10891 10892 case Type::Enum: 10893 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10894 10895 case Type::Pointer: 10896 case Type::ConstantArray: 10897 case Type::VariableArray: 10898 case Type::IncompleteArray: 10899 case Type::FunctionNoProto: 10900 case Type::FunctionProto: 10901 return GCCTypeClass::Pointer; 10902 10903 case Type::MemberPointer: 10904 return CanTy->isMemberDataPointerType() 10905 ? GCCTypeClass::PointerToDataMember 10906 : GCCTypeClass::PointerToMemberFunction; 10907 10908 case Type::Complex: 10909 return GCCTypeClass::Complex; 10910 10911 case Type::Record: 10912 return CanTy->isUnionType() ? GCCTypeClass::Union 10913 : GCCTypeClass::ClassOrStruct; 10914 10915 case Type::Atomic: 10916 // GCC classifies _Atomic T the same as T. 10917 return EvaluateBuiltinClassifyType( 10918 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10919 10920 case Type::BlockPointer: 10921 case Type::Vector: 10922 case Type::ExtVector: 10923 case Type::ConstantMatrix: 10924 case Type::ObjCObject: 10925 case Type::ObjCInterface: 10926 case Type::ObjCObjectPointer: 10927 case Type::Pipe: 10928 case Type::ExtInt: 10929 // GCC classifies vectors as None. We follow its lead and classify all 10930 // other types that don't fit into the regular classification the same way. 10931 return GCCTypeClass::None; 10932 10933 case Type::LValueReference: 10934 case Type::RValueReference: 10935 llvm_unreachable("invalid type for expression"); 10936 } 10937 10938 llvm_unreachable("unexpected type class"); 10939 } 10940 10941 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10942 /// as GCC. 10943 static GCCTypeClass 10944 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10945 // If no argument was supplied, default to None. This isn't 10946 // ideal, however it is what gcc does. 10947 if (E->getNumArgs() == 0) 10948 return GCCTypeClass::None; 10949 10950 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10951 // being an ICE, but still folds it to a constant using the type of the first 10952 // argument. 10953 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10954 } 10955 10956 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10957 /// __builtin_constant_p when applied to the given pointer. 10958 /// 10959 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10960 /// or it points to the first character of a string literal. 10961 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10962 APValue::LValueBase Base = LV.getLValueBase(); 10963 if (Base.isNull()) { 10964 // A null base is acceptable. 10965 return true; 10966 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10967 if (!isa<StringLiteral>(E)) 10968 return false; 10969 return LV.getLValueOffset().isZero(); 10970 } else if (Base.is<TypeInfoLValue>()) { 10971 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10972 // evaluate to true. 10973 return true; 10974 } else { 10975 // Any other base is not constant enough for GCC. 10976 return false; 10977 } 10978 } 10979 10980 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10981 /// GCC as we can manage. 10982 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10983 // This evaluation is not permitted to have side-effects, so evaluate it in 10984 // a speculative evaluation context. 10985 SpeculativeEvaluationRAII SpeculativeEval(Info); 10986 10987 // Constant-folding is always enabled for the operand of __builtin_constant_p 10988 // (even when the enclosing evaluation context otherwise requires a strict 10989 // language-specific constant expression). 10990 FoldConstant Fold(Info, true); 10991 10992 QualType ArgType = Arg->getType(); 10993 10994 // __builtin_constant_p always has one operand. The rules which gcc follows 10995 // are not precisely documented, but are as follows: 10996 // 10997 // - If the operand is of integral, floating, complex or enumeration type, 10998 // and can be folded to a known value of that type, it returns 1. 10999 // - If the operand can be folded to a pointer to the first character 11000 // of a string literal (or such a pointer cast to an integral type) 11001 // or to a null pointer or an integer cast to a pointer, it returns 1. 11002 // 11003 // Otherwise, it returns 0. 11004 // 11005 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11006 // its support for this did not work prior to GCC 9 and is not yet well 11007 // understood. 11008 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11009 ArgType->isAnyComplexType() || ArgType->isPointerType() || 11010 ArgType->isNullPtrType()) { 11011 APValue V; 11012 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11013 Fold.keepDiagnostics(); 11014 return false; 11015 } 11016 11017 // For a pointer (possibly cast to integer), there are special rules. 11018 if (V.getKind() == APValue::LValue) 11019 return EvaluateBuiltinConstantPForLValue(V); 11020 11021 // Otherwise, any constant value is good enough. 11022 return V.hasValue(); 11023 } 11024 11025 // Anything else isn't considered to be sufficiently constant. 11026 return false; 11027 } 11028 11029 /// Retrieves the "underlying object type" of the given expression, 11030 /// as used by __builtin_object_size. 11031 static QualType getObjectType(APValue::LValueBase B) { 11032 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11033 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11034 return VD->getType(); 11035 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11036 if (isa<CompoundLiteralExpr>(E)) 11037 return E->getType(); 11038 } else if (B.is<TypeInfoLValue>()) { 11039 return B.getTypeInfoType(); 11040 } else if (B.is<DynamicAllocLValue>()) { 11041 return B.getDynamicAllocType(); 11042 } 11043 11044 return QualType(); 11045 } 11046 11047 /// A more selective version of E->IgnoreParenCasts for 11048 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11049 /// to change the type of E. 11050 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11051 /// 11052 /// Always returns an RValue with a pointer representation. 11053 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11054 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11055 11056 auto *NoParens = E->IgnoreParens(); 11057 auto *Cast = dyn_cast<CastExpr>(NoParens); 11058 if (Cast == nullptr) 11059 return NoParens; 11060 11061 // We only conservatively allow a few kinds of casts, because this code is 11062 // inherently a simple solution that seeks to support the common case. 11063 auto CastKind = Cast->getCastKind(); 11064 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11065 CastKind != CK_AddressSpaceConversion) 11066 return NoParens; 11067 11068 auto *SubExpr = Cast->getSubExpr(); 11069 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11070 return NoParens; 11071 return ignorePointerCastsAndParens(SubExpr); 11072 } 11073 11074 /// Checks to see if the given LValue's Designator is at the end of the LValue's 11075 /// record layout. e.g. 11076 /// struct { struct { int a, b; } fst, snd; } obj; 11077 /// obj.fst // no 11078 /// obj.snd // yes 11079 /// obj.fst.a // no 11080 /// obj.fst.b // no 11081 /// obj.snd.a // no 11082 /// obj.snd.b // yes 11083 /// 11084 /// Please note: this function is specialized for how __builtin_object_size 11085 /// views "objects". 11086 /// 11087 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11088 /// correct result, it will always return true. 11089 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11090 assert(!LVal.Designator.Invalid); 11091 11092 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11093 const RecordDecl *Parent = FD->getParent(); 11094 Invalid = Parent->isInvalidDecl(); 11095 if (Invalid || Parent->isUnion()) 11096 return true; 11097 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11098 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11099 }; 11100 11101 auto &Base = LVal.getLValueBase(); 11102 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11103 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11104 bool Invalid; 11105 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11106 return Invalid; 11107 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11108 for (auto *FD : IFD->chain()) { 11109 bool Invalid; 11110 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11111 return Invalid; 11112 } 11113 } 11114 } 11115 11116 unsigned I = 0; 11117 QualType BaseType = getType(Base); 11118 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11119 // If we don't know the array bound, conservatively assume we're looking at 11120 // the final array element. 11121 ++I; 11122 if (BaseType->isIncompleteArrayType()) 11123 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11124 else 11125 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11126 } 11127 11128 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11129 const auto &Entry = LVal.Designator.Entries[I]; 11130 if (BaseType->isArrayType()) { 11131 // Because __builtin_object_size treats arrays as objects, we can ignore 11132 // the index iff this is the last array in the Designator. 11133 if (I + 1 == E) 11134 return true; 11135 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11136 uint64_t Index = Entry.getAsArrayIndex(); 11137 if (Index + 1 != CAT->getSize()) 11138 return false; 11139 BaseType = CAT->getElementType(); 11140 } else if (BaseType->isAnyComplexType()) { 11141 const auto *CT = BaseType->castAs<ComplexType>(); 11142 uint64_t Index = Entry.getAsArrayIndex(); 11143 if (Index != 1) 11144 return false; 11145 BaseType = CT->getElementType(); 11146 } else if (auto *FD = getAsField(Entry)) { 11147 bool Invalid; 11148 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11149 return Invalid; 11150 BaseType = FD->getType(); 11151 } else { 11152 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11153 return false; 11154 } 11155 } 11156 return true; 11157 } 11158 11159 /// Tests to see if the LValue has a user-specified designator (that isn't 11160 /// necessarily valid). Note that this always returns 'true' if the LValue has 11161 /// an unsized array as its first designator entry, because there's currently no 11162 /// way to tell if the user typed *foo or foo[0]. 11163 static bool refersToCompleteObject(const LValue &LVal) { 11164 if (LVal.Designator.Invalid) 11165 return false; 11166 11167 if (!LVal.Designator.Entries.empty()) 11168 return LVal.Designator.isMostDerivedAnUnsizedArray(); 11169 11170 if (!LVal.InvalidBase) 11171 return true; 11172 11173 // If `E` is a MemberExpr, then the first part of the designator is hiding in 11174 // the LValueBase. 11175 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11176 return !E || !isa<MemberExpr>(E); 11177 } 11178 11179 /// Attempts to detect a user writing into a piece of memory that's impossible 11180 /// to figure out the size of by just using types. 11181 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11182 const SubobjectDesignator &Designator = LVal.Designator; 11183 // Notes: 11184 // - Users can only write off of the end when we have an invalid base. Invalid 11185 // bases imply we don't know where the memory came from. 11186 // - We used to be a bit more aggressive here; we'd only be conservative if 11187 // the array at the end was flexible, or if it had 0 or 1 elements. This 11188 // broke some common standard library extensions (PR30346), but was 11189 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11190 // with some sort of list. OTOH, it seems that GCC is always 11191 // conservative with the last element in structs (if it's an array), so our 11192 // current behavior is more compatible than an explicit list approach would 11193 // be. 11194 return LVal.InvalidBase && 11195 Designator.Entries.size() == Designator.MostDerivedPathLength && 11196 Designator.MostDerivedIsArrayElement && 11197 isDesignatorAtObjectEnd(Ctx, LVal); 11198 } 11199 11200 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11201 /// Fails if the conversion would cause loss of precision. 11202 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11203 CharUnits &Result) { 11204 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11205 if (Int.ugt(CharUnitsMax)) 11206 return false; 11207 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11208 return true; 11209 } 11210 11211 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11212 /// determine how many bytes exist from the beginning of the object to either 11213 /// the end of the current subobject, or the end of the object itself, depending 11214 /// on what the LValue looks like + the value of Type. 11215 /// 11216 /// If this returns false, the value of Result is undefined. 11217 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11218 unsigned Type, const LValue &LVal, 11219 CharUnits &EndOffset) { 11220 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11221 11222 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11223 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11224 return false; 11225 return HandleSizeof(Info, ExprLoc, Ty, Result); 11226 }; 11227 11228 // We want to evaluate the size of the entire object. This is a valid fallback 11229 // for when Type=1 and the designator is invalid, because we're asked for an 11230 // upper-bound. 11231 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11232 // Type=3 wants a lower bound, so we can't fall back to this. 11233 if (Type == 3 && !DetermineForCompleteObject) 11234 return false; 11235 11236 llvm::APInt APEndOffset; 11237 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11238 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11239 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11240 11241 if (LVal.InvalidBase) 11242 return false; 11243 11244 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11245 return CheckedHandleSizeof(BaseTy, EndOffset); 11246 } 11247 11248 // We want to evaluate the size of a subobject. 11249 const SubobjectDesignator &Designator = LVal.Designator; 11250 11251 // The following is a moderately common idiom in C: 11252 // 11253 // struct Foo { int a; char c[1]; }; 11254 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11255 // strcpy(&F->c[0], Bar); 11256 // 11257 // In order to not break too much legacy code, we need to support it. 11258 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11259 // If we can resolve this to an alloc_size call, we can hand that back, 11260 // because we know for certain how many bytes there are to write to. 11261 llvm::APInt APEndOffset; 11262 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11263 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11264 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11265 11266 // If we cannot determine the size of the initial allocation, then we can't 11267 // given an accurate upper-bound. However, we are still able to give 11268 // conservative lower-bounds for Type=3. 11269 if (Type == 1) 11270 return false; 11271 } 11272 11273 CharUnits BytesPerElem; 11274 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11275 return false; 11276 11277 // According to the GCC documentation, we want the size of the subobject 11278 // denoted by the pointer. But that's not quite right -- what we actually 11279 // want is the size of the immediately-enclosing array, if there is one. 11280 int64_t ElemsRemaining; 11281 if (Designator.MostDerivedIsArrayElement && 11282 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11283 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11284 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11285 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11286 } else { 11287 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11288 } 11289 11290 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11291 return true; 11292 } 11293 11294 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11295 /// returns true and stores the result in @p Size. 11296 /// 11297 /// If @p WasError is non-null, this will report whether the failure to evaluate 11298 /// is to be treated as an Error in IntExprEvaluator. 11299 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11300 EvalInfo &Info, uint64_t &Size) { 11301 // Determine the denoted object. 11302 LValue LVal; 11303 { 11304 // The operand of __builtin_object_size is never evaluated for side-effects. 11305 // If there are any, but we can determine the pointed-to object anyway, then 11306 // ignore the side-effects. 11307 SpeculativeEvaluationRAII SpeculativeEval(Info); 11308 IgnoreSideEffectsRAII Fold(Info); 11309 11310 if (E->isGLValue()) { 11311 // It's possible for us to be given GLValues if we're called via 11312 // Expr::tryEvaluateObjectSize. 11313 APValue RVal; 11314 if (!EvaluateAsRValue(Info, E, RVal)) 11315 return false; 11316 LVal.setFrom(Info.Ctx, RVal); 11317 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11318 /*InvalidBaseOK=*/true)) 11319 return false; 11320 } 11321 11322 // If we point to before the start of the object, there are no accessible 11323 // bytes. 11324 if (LVal.getLValueOffset().isNegative()) { 11325 Size = 0; 11326 return true; 11327 } 11328 11329 CharUnits EndOffset; 11330 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11331 return false; 11332 11333 // If we've fallen outside of the end offset, just pretend there's nothing to 11334 // write to/read from. 11335 if (EndOffset <= LVal.getLValueOffset()) 11336 Size = 0; 11337 else 11338 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11339 return true; 11340 } 11341 11342 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11343 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11344 return VisitBuiltinCallExpr(E, BuiltinOp); 11345 11346 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11347 } 11348 11349 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11350 APValue &Val, APSInt &Alignment) { 11351 QualType SrcTy = E->getArg(0)->getType(); 11352 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11353 return false; 11354 // Even though we are evaluating integer expressions we could get a pointer 11355 // argument for the __builtin_is_aligned() case. 11356 if (SrcTy->isPointerType()) { 11357 LValue Ptr; 11358 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11359 return false; 11360 Ptr.moveInto(Val); 11361 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11362 Info.FFDiag(E->getArg(0)); 11363 return false; 11364 } else { 11365 APSInt SrcInt; 11366 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11367 return false; 11368 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11369 "Bit widths must be the same"); 11370 Val = APValue(SrcInt); 11371 } 11372 assert(Val.hasValue()); 11373 return true; 11374 } 11375 11376 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11377 unsigned BuiltinOp) { 11378 switch (BuiltinOp) { 11379 default: 11380 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11381 11382 case Builtin::BI__builtin_dynamic_object_size: 11383 case Builtin::BI__builtin_object_size: { 11384 // The type was checked when we built the expression. 11385 unsigned Type = 11386 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11387 assert(Type <= 3 && "unexpected type"); 11388 11389 uint64_t Size; 11390 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11391 return Success(Size, E); 11392 11393 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11394 return Success((Type & 2) ? 0 : -1, E); 11395 11396 // Expression had no side effects, but we couldn't statically determine the 11397 // size of the referenced object. 11398 switch (Info.EvalMode) { 11399 case EvalInfo::EM_ConstantExpression: 11400 case EvalInfo::EM_ConstantFold: 11401 case EvalInfo::EM_IgnoreSideEffects: 11402 // Leave it to IR generation. 11403 return Error(E); 11404 case EvalInfo::EM_ConstantExpressionUnevaluated: 11405 // Reduce it to a constant now. 11406 return Success((Type & 2) ? 0 : -1, E); 11407 } 11408 11409 llvm_unreachable("unexpected EvalMode"); 11410 } 11411 11412 case Builtin::BI__builtin_os_log_format_buffer_size: { 11413 analyze_os_log::OSLogBufferLayout Layout; 11414 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11415 return Success(Layout.size().getQuantity(), E); 11416 } 11417 11418 case Builtin::BI__builtin_is_aligned: { 11419 APValue Src; 11420 APSInt Alignment; 11421 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11422 return false; 11423 if (Src.isLValue()) { 11424 // If we evaluated a pointer, check the minimum known alignment. 11425 LValue Ptr; 11426 Ptr.setFrom(Info.Ctx, Src); 11427 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11428 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11429 // We can return true if the known alignment at the computed offset is 11430 // greater than the requested alignment. 11431 assert(PtrAlign.isPowerOfTwo()); 11432 assert(Alignment.isPowerOf2()); 11433 if (PtrAlign.getQuantity() >= Alignment) 11434 return Success(1, E); 11435 // If the alignment is not known to be sufficient, some cases could still 11436 // be aligned at run time. However, if the requested alignment is less or 11437 // equal to the base alignment and the offset is not aligned, we know that 11438 // the run-time value can never be aligned. 11439 if (BaseAlignment.getQuantity() >= Alignment && 11440 PtrAlign.getQuantity() < Alignment) 11441 return Success(0, E); 11442 // Otherwise we can't infer whether the value is sufficiently aligned. 11443 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11444 // in cases where we can't fully evaluate the pointer. 11445 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11446 << Alignment; 11447 return false; 11448 } 11449 assert(Src.isInt()); 11450 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11451 } 11452 case Builtin::BI__builtin_align_up: { 11453 APValue Src; 11454 APSInt Alignment; 11455 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11456 return false; 11457 if (!Src.isInt()) 11458 return Error(E); 11459 APSInt AlignedVal = 11460 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11461 Src.getInt().isUnsigned()); 11462 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11463 return Success(AlignedVal, E); 11464 } 11465 case Builtin::BI__builtin_align_down: { 11466 APValue Src; 11467 APSInt Alignment; 11468 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11469 return false; 11470 if (!Src.isInt()) 11471 return Error(E); 11472 APSInt AlignedVal = 11473 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11474 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11475 return Success(AlignedVal, E); 11476 } 11477 11478 case Builtin::BI__builtin_bitreverse8: 11479 case Builtin::BI__builtin_bitreverse16: 11480 case Builtin::BI__builtin_bitreverse32: 11481 case Builtin::BI__builtin_bitreverse64: { 11482 APSInt Val; 11483 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11484 return false; 11485 11486 return Success(Val.reverseBits(), E); 11487 } 11488 11489 case Builtin::BI__builtin_bswap16: 11490 case Builtin::BI__builtin_bswap32: 11491 case Builtin::BI__builtin_bswap64: { 11492 APSInt Val; 11493 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11494 return false; 11495 11496 return Success(Val.byteSwap(), E); 11497 } 11498 11499 case Builtin::BI__builtin_classify_type: 11500 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11501 11502 case Builtin::BI__builtin_clrsb: 11503 case Builtin::BI__builtin_clrsbl: 11504 case Builtin::BI__builtin_clrsbll: { 11505 APSInt Val; 11506 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11507 return false; 11508 11509 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11510 } 11511 11512 case Builtin::BI__builtin_clz: 11513 case Builtin::BI__builtin_clzl: 11514 case Builtin::BI__builtin_clzll: 11515 case Builtin::BI__builtin_clzs: { 11516 APSInt Val; 11517 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11518 return false; 11519 if (!Val) 11520 return Error(E); 11521 11522 return Success(Val.countLeadingZeros(), E); 11523 } 11524 11525 case Builtin::BI__builtin_constant_p: { 11526 const Expr *Arg = E->getArg(0); 11527 if (EvaluateBuiltinConstantP(Info, Arg)) 11528 return Success(true, E); 11529 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11530 // Outside a constant context, eagerly evaluate to false in the presence 11531 // of side-effects in order to avoid -Wunsequenced false-positives in 11532 // a branch on __builtin_constant_p(expr). 11533 return Success(false, E); 11534 } 11535 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11536 return false; 11537 } 11538 11539 case Builtin::BI__builtin_is_constant_evaluated: { 11540 const auto *Callee = Info.CurrentCall->getCallee(); 11541 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11542 (Info.CallStackDepth == 1 || 11543 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11544 Callee->getIdentifier() && 11545 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11546 // FIXME: Find a better way to avoid duplicated diagnostics. 11547 if (Info.EvalStatus.Diag) 11548 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11549 : Info.CurrentCall->CallLoc, 11550 diag::warn_is_constant_evaluated_always_true_constexpr) 11551 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11552 : "std::is_constant_evaluated"); 11553 } 11554 11555 return Success(Info.InConstantContext, E); 11556 } 11557 11558 case Builtin::BI__builtin_ctz: 11559 case Builtin::BI__builtin_ctzl: 11560 case Builtin::BI__builtin_ctzll: 11561 case Builtin::BI__builtin_ctzs: { 11562 APSInt Val; 11563 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11564 return false; 11565 if (!Val) 11566 return Error(E); 11567 11568 return Success(Val.countTrailingZeros(), E); 11569 } 11570 11571 case Builtin::BI__builtin_eh_return_data_regno: { 11572 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11573 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11574 return Success(Operand, E); 11575 } 11576 11577 case Builtin::BI__builtin_expect: 11578 case Builtin::BI__builtin_expect_with_probability: 11579 return Visit(E->getArg(0)); 11580 11581 case Builtin::BI__builtin_ffs: 11582 case Builtin::BI__builtin_ffsl: 11583 case Builtin::BI__builtin_ffsll: { 11584 APSInt Val; 11585 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11586 return false; 11587 11588 unsigned N = Val.countTrailingZeros(); 11589 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11590 } 11591 11592 case Builtin::BI__builtin_fpclassify: { 11593 APFloat Val(0.0); 11594 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11595 return false; 11596 unsigned Arg; 11597 switch (Val.getCategory()) { 11598 case APFloat::fcNaN: Arg = 0; break; 11599 case APFloat::fcInfinity: Arg = 1; break; 11600 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11601 case APFloat::fcZero: Arg = 4; break; 11602 } 11603 return Visit(E->getArg(Arg)); 11604 } 11605 11606 case Builtin::BI__builtin_isinf_sign: { 11607 APFloat Val(0.0); 11608 return EvaluateFloat(E->getArg(0), Val, Info) && 11609 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11610 } 11611 11612 case Builtin::BI__builtin_isinf: { 11613 APFloat Val(0.0); 11614 return EvaluateFloat(E->getArg(0), Val, Info) && 11615 Success(Val.isInfinity() ? 1 : 0, E); 11616 } 11617 11618 case Builtin::BI__builtin_isfinite: { 11619 APFloat Val(0.0); 11620 return EvaluateFloat(E->getArg(0), Val, Info) && 11621 Success(Val.isFinite() ? 1 : 0, E); 11622 } 11623 11624 case Builtin::BI__builtin_isnan: { 11625 APFloat Val(0.0); 11626 return EvaluateFloat(E->getArg(0), Val, Info) && 11627 Success(Val.isNaN() ? 1 : 0, E); 11628 } 11629 11630 case Builtin::BI__builtin_isnormal: { 11631 APFloat Val(0.0); 11632 return EvaluateFloat(E->getArg(0), Val, Info) && 11633 Success(Val.isNormal() ? 1 : 0, E); 11634 } 11635 11636 case Builtin::BI__builtin_parity: 11637 case Builtin::BI__builtin_parityl: 11638 case Builtin::BI__builtin_parityll: { 11639 APSInt Val; 11640 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11641 return false; 11642 11643 return Success(Val.countPopulation() % 2, E); 11644 } 11645 11646 case Builtin::BI__builtin_popcount: 11647 case Builtin::BI__builtin_popcountl: 11648 case Builtin::BI__builtin_popcountll: { 11649 APSInt Val; 11650 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11651 return false; 11652 11653 return Success(Val.countPopulation(), E); 11654 } 11655 11656 case Builtin::BI__builtin_rotateleft8: 11657 case Builtin::BI__builtin_rotateleft16: 11658 case Builtin::BI__builtin_rotateleft32: 11659 case Builtin::BI__builtin_rotateleft64: 11660 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11661 case Builtin::BI_rotl16: 11662 case Builtin::BI_rotl: 11663 case Builtin::BI_lrotl: 11664 case Builtin::BI_rotl64: { 11665 APSInt Val, Amt; 11666 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11667 !EvaluateInteger(E->getArg(1), Amt, Info)) 11668 return false; 11669 11670 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11671 } 11672 11673 case Builtin::BI__builtin_rotateright8: 11674 case Builtin::BI__builtin_rotateright16: 11675 case Builtin::BI__builtin_rotateright32: 11676 case Builtin::BI__builtin_rotateright64: 11677 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11678 case Builtin::BI_rotr16: 11679 case Builtin::BI_rotr: 11680 case Builtin::BI_lrotr: 11681 case Builtin::BI_rotr64: { 11682 APSInt Val, Amt; 11683 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11684 !EvaluateInteger(E->getArg(1), Amt, Info)) 11685 return false; 11686 11687 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11688 } 11689 11690 case Builtin::BIstrlen: 11691 case Builtin::BIwcslen: 11692 // A call to strlen is not a constant expression. 11693 if (Info.getLangOpts().CPlusPlus11) 11694 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11695 << /*isConstexpr*/0 << /*isConstructor*/0 11696 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11697 else 11698 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11699 LLVM_FALLTHROUGH; 11700 case Builtin::BI__builtin_strlen: 11701 case Builtin::BI__builtin_wcslen: { 11702 // As an extension, we support __builtin_strlen() as a constant expression, 11703 // and support folding strlen() to a constant. 11704 LValue String; 11705 if (!EvaluatePointer(E->getArg(0), String, Info)) 11706 return false; 11707 11708 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11709 11710 // Fast path: if it's a string literal, search the string value. 11711 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11712 String.getLValueBase().dyn_cast<const Expr *>())) { 11713 // The string literal may have embedded null characters. Find the first 11714 // one and truncate there. 11715 StringRef Str = S->getBytes(); 11716 int64_t Off = String.Offset.getQuantity(); 11717 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11718 S->getCharByteWidth() == 1 && 11719 // FIXME: Add fast-path for wchar_t too. 11720 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11721 Str = Str.substr(Off); 11722 11723 StringRef::size_type Pos = Str.find(0); 11724 if (Pos != StringRef::npos) 11725 Str = Str.substr(0, Pos); 11726 11727 return Success(Str.size(), E); 11728 } 11729 11730 // Fall through to slow path to issue appropriate diagnostic. 11731 } 11732 11733 // Slow path: scan the bytes of the string looking for the terminating 0. 11734 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11735 APValue Char; 11736 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11737 !Char.isInt()) 11738 return false; 11739 if (!Char.getInt()) 11740 return Success(Strlen, E); 11741 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11742 return false; 11743 } 11744 } 11745 11746 case Builtin::BIstrcmp: 11747 case Builtin::BIwcscmp: 11748 case Builtin::BIstrncmp: 11749 case Builtin::BIwcsncmp: 11750 case Builtin::BImemcmp: 11751 case Builtin::BIbcmp: 11752 case Builtin::BIwmemcmp: 11753 // A call to strlen is not a constant expression. 11754 if (Info.getLangOpts().CPlusPlus11) 11755 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11756 << /*isConstexpr*/0 << /*isConstructor*/0 11757 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11758 else 11759 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11760 LLVM_FALLTHROUGH; 11761 case Builtin::BI__builtin_strcmp: 11762 case Builtin::BI__builtin_wcscmp: 11763 case Builtin::BI__builtin_strncmp: 11764 case Builtin::BI__builtin_wcsncmp: 11765 case Builtin::BI__builtin_memcmp: 11766 case Builtin::BI__builtin_bcmp: 11767 case Builtin::BI__builtin_wmemcmp: { 11768 LValue String1, String2; 11769 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11770 !EvaluatePointer(E->getArg(1), String2, Info)) 11771 return false; 11772 11773 uint64_t MaxLength = uint64_t(-1); 11774 if (BuiltinOp != Builtin::BIstrcmp && 11775 BuiltinOp != Builtin::BIwcscmp && 11776 BuiltinOp != Builtin::BI__builtin_strcmp && 11777 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11778 APSInt N; 11779 if (!EvaluateInteger(E->getArg(2), N, Info)) 11780 return false; 11781 MaxLength = N.getExtValue(); 11782 } 11783 11784 // Empty substrings compare equal by definition. 11785 if (MaxLength == 0u) 11786 return Success(0, E); 11787 11788 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11789 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11790 String1.Designator.Invalid || String2.Designator.Invalid) 11791 return false; 11792 11793 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11794 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11795 11796 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11797 BuiltinOp == Builtin::BIbcmp || 11798 BuiltinOp == Builtin::BI__builtin_memcmp || 11799 BuiltinOp == Builtin::BI__builtin_bcmp; 11800 11801 assert(IsRawByte || 11802 (Info.Ctx.hasSameUnqualifiedType( 11803 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11804 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11805 11806 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11807 // 'char8_t', but no other types. 11808 if (IsRawByte && 11809 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11810 // FIXME: Consider using our bit_cast implementation to support this. 11811 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11812 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11813 << CharTy1 << CharTy2; 11814 return false; 11815 } 11816 11817 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11818 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11819 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11820 Char1.isInt() && Char2.isInt(); 11821 }; 11822 const auto &AdvanceElems = [&] { 11823 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11824 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11825 }; 11826 11827 bool StopAtNull = 11828 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11829 BuiltinOp != Builtin::BIwmemcmp && 11830 BuiltinOp != Builtin::BI__builtin_memcmp && 11831 BuiltinOp != Builtin::BI__builtin_bcmp && 11832 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11833 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11834 BuiltinOp == Builtin::BIwcsncmp || 11835 BuiltinOp == Builtin::BIwmemcmp || 11836 BuiltinOp == Builtin::BI__builtin_wcscmp || 11837 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11838 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11839 11840 for (; MaxLength; --MaxLength) { 11841 APValue Char1, Char2; 11842 if (!ReadCurElems(Char1, Char2)) 11843 return false; 11844 if (Char1.getInt().ne(Char2.getInt())) { 11845 if (IsWide) // wmemcmp compares with wchar_t signedness. 11846 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11847 // memcmp always compares unsigned chars. 11848 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11849 } 11850 if (StopAtNull && !Char1.getInt()) 11851 return Success(0, E); 11852 assert(!(StopAtNull && !Char2.getInt())); 11853 if (!AdvanceElems()) 11854 return false; 11855 } 11856 // We hit the strncmp / memcmp limit. 11857 return Success(0, E); 11858 } 11859 11860 case Builtin::BI__atomic_always_lock_free: 11861 case Builtin::BI__atomic_is_lock_free: 11862 case Builtin::BI__c11_atomic_is_lock_free: { 11863 APSInt SizeVal; 11864 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11865 return false; 11866 11867 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11868 // of two less than or equal to the maximum inline atomic width, we know it 11869 // is lock-free. If the size isn't a power of two, or greater than the 11870 // maximum alignment where we promote atomics, we know it is not lock-free 11871 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11872 // the answer can only be determined at runtime; for example, 16-byte 11873 // atomics have lock-free implementations on some, but not all, 11874 // x86-64 processors. 11875 11876 // Check power-of-two. 11877 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11878 if (Size.isPowerOfTwo()) { 11879 // Check against inlining width. 11880 unsigned InlineWidthBits = 11881 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11882 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11883 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11884 Size == CharUnits::One() || 11885 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11886 Expr::NPC_NeverValueDependent)) 11887 // OK, we will inline appropriately-aligned operations of this size, 11888 // and _Atomic(T) is appropriately-aligned. 11889 return Success(1, E); 11890 11891 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11892 castAs<PointerType>()->getPointeeType(); 11893 if (!PointeeType->isIncompleteType() && 11894 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11895 // OK, we will inline operations on this object. 11896 return Success(1, E); 11897 } 11898 } 11899 } 11900 11901 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11902 Success(0, E) : Error(E); 11903 } 11904 case Builtin::BIomp_is_initial_device: 11905 // We can decide statically which value the runtime would return if called. 11906 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11907 case Builtin::BI__builtin_add_overflow: 11908 case Builtin::BI__builtin_sub_overflow: 11909 case Builtin::BI__builtin_mul_overflow: 11910 case Builtin::BI__builtin_sadd_overflow: 11911 case Builtin::BI__builtin_uadd_overflow: 11912 case Builtin::BI__builtin_uaddl_overflow: 11913 case Builtin::BI__builtin_uaddll_overflow: 11914 case Builtin::BI__builtin_usub_overflow: 11915 case Builtin::BI__builtin_usubl_overflow: 11916 case Builtin::BI__builtin_usubll_overflow: 11917 case Builtin::BI__builtin_umul_overflow: 11918 case Builtin::BI__builtin_umull_overflow: 11919 case Builtin::BI__builtin_umulll_overflow: 11920 case Builtin::BI__builtin_saddl_overflow: 11921 case Builtin::BI__builtin_saddll_overflow: 11922 case Builtin::BI__builtin_ssub_overflow: 11923 case Builtin::BI__builtin_ssubl_overflow: 11924 case Builtin::BI__builtin_ssubll_overflow: 11925 case Builtin::BI__builtin_smul_overflow: 11926 case Builtin::BI__builtin_smull_overflow: 11927 case Builtin::BI__builtin_smulll_overflow: { 11928 LValue ResultLValue; 11929 APSInt LHS, RHS; 11930 11931 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11932 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11933 !EvaluateInteger(E->getArg(1), RHS, Info) || 11934 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11935 return false; 11936 11937 APSInt Result; 11938 bool DidOverflow = false; 11939 11940 // If the types don't have to match, enlarge all 3 to the largest of them. 11941 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11942 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11943 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11944 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11945 ResultType->isSignedIntegerOrEnumerationType(); 11946 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11947 ResultType->isSignedIntegerOrEnumerationType(); 11948 uint64_t LHSSize = LHS.getBitWidth(); 11949 uint64_t RHSSize = RHS.getBitWidth(); 11950 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11951 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11952 11953 // Add an additional bit if the signedness isn't uniformly agreed to. We 11954 // could do this ONLY if there is a signed and an unsigned that both have 11955 // MaxBits, but the code to check that is pretty nasty. The issue will be 11956 // caught in the shrink-to-result later anyway. 11957 if (IsSigned && !AllSigned) 11958 ++MaxBits; 11959 11960 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11961 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11962 Result = APSInt(MaxBits, !IsSigned); 11963 } 11964 11965 // Find largest int. 11966 switch (BuiltinOp) { 11967 default: 11968 llvm_unreachable("Invalid value for BuiltinOp"); 11969 case Builtin::BI__builtin_add_overflow: 11970 case Builtin::BI__builtin_sadd_overflow: 11971 case Builtin::BI__builtin_saddl_overflow: 11972 case Builtin::BI__builtin_saddll_overflow: 11973 case Builtin::BI__builtin_uadd_overflow: 11974 case Builtin::BI__builtin_uaddl_overflow: 11975 case Builtin::BI__builtin_uaddll_overflow: 11976 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11977 : LHS.uadd_ov(RHS, DidOverflow); 11978 break; 11979 case Builtin::BI__builtin_sub_overflow: 11980 case Builtin::BI__builtin_ssub_overflow: 11981 case Builtin::BI__builtin_ssubl_overflow: 11982 case Builtin::BI__builtin_ssubll_overflow: 11983 case Builtin::BI__builtin_usub_overflow: 11984 case Builtin::BI__builtin_usubl_overflow: 11985 case Builtin::BI__builtin_usubll_overflow: 11986 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11987 : LHS.usub_ov(RHS, DidOverflow); 11988 break; 11989 case Builtin::BI__builtin_mul_overflow: 11990 case Builtin::BI__builtin_smul_overflow: 11991 case Builtin::BI__builtin_smull_overflow: 11992 case Builtin::BI__builtin_smulll_overflow: 11993 case Builtin::BI__builtin_umul_overflow: 11994 case Builtin::BI__builtin_umull_overflow: 11995 case Builtin::BI__builtin_umulll_overflow: 11996 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11997 : LHS.umul_ov(RHS, DidOverflow); 11998 break; 11999 } 12000 12001 // In the case where multiple sizes are allowed, truncate and see if 12002 // the values are the same. 12003 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12004 BuiltinOp == Builtin::BI__builtin_sub_overflow || 12005 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12006 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12007 // since it will give us the behavior of a TruncOrSelf in the case where 12008 // its parameter <= its size. We previously set Result to be at least the 12009 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12010 // will work exactly like TruncOrSelf. 12011 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12012 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12013 12014 if (!APSInt::isSameValue(Temp, Result)) 12015 DidOverflow = true; 12016 Result = Temp; 12017 } 12018 12019 APValue APV{Result}; 12020 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12021 return false; 12022 return Success(DidOverflow, E); 12023 } 12024 } 12025 } 12026 12027 /// Determine whether this is a pointer past the end of the complete 12028 /// object referred to by the lvalue. 12029 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12030 const LValue &LV) { 12031 // A null pointer can be viewed as being "past the end" but we don't 12032 // choose to look at it that way here. 12033 if (!LV.getLValueBase()) 12034 return false; 12035 12036 // If the designator is valid and refers to a subobject, we're not pointing 12037 // past the end. 12038 if (!LV.getLValueDesignator().Invalid && 12039 !LV.getLValueDesignator().isOnePastTheEnd()) 12040 return false; 12041 12042 // A pointer to an incomplete type might be past-the-end if the type's size is 12043 // zero. We cannot tell because the type is incomplete. 12044 QualType Ty = getType(LV.getLValueBase()); 12045 if (Ty->isIncompleteType()) 12046 return true; 12047 12048 // We're a past-the-end pointer if we point to the byte after the object, 12049 // no matter what our type or path is. 12050 auto Size = Ctx.getTypeSizeInChars(Ty); 12051 return LV.getLValueOffset() == Size; 12052 } 12053 12054 namespace { 12055 12056 /// Data recursive integer evaluator of certain binary operators. 12057 /// 12058 /// We use a data recursive algorithm for binary operators so that we are able 12059 /// to handle extreme cases of chained binary operators without causing stack 12060 /// overflow. 12061 class DataRecursiveIntBinOpEvaluator { 12062 struct EvalResult { 12063 APValue Val; 12064 bool Failed; 12065 12066 EvalResult() : Failed(false) { } 12067 12068 void swap(EvalResult &RHS) { 12069 Val.swap(RHS.Val); 12070 Failed = RHS.Failed; 12071 RHS.Failed = false; 12072 } 12073 }; 12074 12075 struct Job { 12076 const Expr *E; 12077 EvalResult LHSResult; // meaningful only for binary operator expression. 12078 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12079 12080 Job() = default; 12081 Job(Job &&) = default; 12082 12083 void startSpeculativeEval(EvalInfo &Info) { 12084 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12085 } 12086 12087 private: 12088 SpeculativeEvaluationRAII SpecEvalRAII; 12089 }; 12090 12091 SmallVector<Job, 16> Queue; 12092 12093 IntExprEvaluator &IntEval; 12094 EvalInfo &Info; 12095 APValue &FinalResult; 12096 12097 public: 12098 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12099 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12100 12101 /// True if \param E is a binary operator that we are going to handle 12102 /// data recursively. 12103 /// We handle binary operators that are comma, logical, or that have operands 12104 /// with integral or enumeration type. 12105 static bool shouldEnqueue(const BinaryOperator *E) { 12106 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12107 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12108 E->getLHS()->getType()->isIntegralOrEnumerationType() && 12109 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12110 } 12111 12112 bool Traverse(const BinaryOperator *E) { 12113 enqueue(E); 12114 EvalResult PrevResult; 12115 while (!Queue.empty()) 12116 process(PrevResult); 12117 12118 if (PrevResult.Failed) return false; 12119 12120 FinalResult.swap(PrevResult.Val); 12121 return true; 12122 } 12123 12124 private: 12125 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12126 return IntEval.Success(Value, E, Result); 12127 } 12128 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12129 return IntEval.Success(Value, E, Result); 12130 } 12131 bool Error(const Expr *E) { 12132 return IntEval.Error(E); 12133 } 12134 bool Error(const Expr *E, diag::kind D) { 12135 return IntEval.Error(E, D); 12136 } 12137 12138 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12139 return Info.CCEDiag(E, D); 12140 } 12141 12142 // Returns true if visiting the RHS is necessary, false otherwise. 12143 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12144 bool &SuppressRHSDiags); 12145 12146 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12147 const BinaryOperator *E, APValue &Result); 12148 12149 void EvaluateExpr(const Expr *E, EvalResult &Result) { 12150 Result.Failed = !Evaluate(Result.Val, Info, E); 12151 if (Result.Failed) 12152 Result.Val = APValue(); 12153 } 12154 12155 void process(EvalResult &Result); 12156 12157 void enqueue(const Expr *E) { 12158 E = E->IgnoreParens(); 12159 Queue.resize(Queue.size()+1); 12160 Queue.back().E = E; 12161 Queue.back().Kind = Job::AnyExprKind; 12162 } 12163 }; 12164 12165 } 12166 12167 bool DataRecursiveIntBinOpEvaluator:: 12168 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12169 bool &SuppressRHSDiags) { 12170 if (E->getOpcode() == BO_Comma) { 12171 // Ignore LHS but note if we could not evaluate it. 12172 if (LHSResult.Failed) 12173 return Info.noteSideEffect(); 12174 return true; 12175 } 12176 12177 if (E->isLogicalOp()) { 12178 bool LHSAsBool; 12179 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12180 // We were able to evaluate the LHS, see if we can get away with not 12181 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12182 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12183 Success(LHSAsBool, E, LHSResult.Val); 12184 return false; // Ignore RHS 12185 } 12186 } else { 12187 LHSResult.Failed = true; 12188 12189 // Since we weren't able to evaluate the left hand side, it 12190 // might have had side effects. 12191 if (!Info.noteSideEffect()) 12192 return false; 12193 12194 // We can't evaluate the LHS; however, sometimes the result 12195 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12196 // Don't ignore RHS and suppress diagnostics from this arm. 12197 SuppressRHSDiags = true; 12198 } 12199 12200 return true; 12201 } 12202 12203 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12204 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12205 12206 if (LHSResult.Failed && !Info.noteFailure()) 12207 return false; // Ignore RHS; 12208 12209 return true; 12210 } 12211 12212 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12213 bool IsSub) { 12214 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12215 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12216 // offsets. 12217 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12218 CharUnits &Offset = LVal.getLValueOffset(); 12219 uint64_t Offset64 = Offset.getQuantity(); 12220 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12221 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12222 : Offset64 + Index64); 12223 } 12224 12225 bool DataRecursiveIntBinOpEvaluator:: 12226 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12227 const BinaryOperator *E, APValue &Result) { 12228 if (E->getOpcode() == BO_Comma) { 12229 if (RHSResult.Failed) 12230 return false; 12231 Result = RHSResult.Val; 12232 return true; 12233 } 12234 12235 if (E->isLogicalOp()) { 12236 bool lhsResult, rhsResult; 12237 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12238 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12239 12240 if (LHSIsOK) { 12241 if (RHSIsOK) { 12242 if (E->getOpcode() == BO_LOr) 12243 return Success(lhsResult || rhsResult, E, Result); 12244 else 12245 return Success(lhsResult && rhsResult, E, Result); 12246 } 12247 } else { 12248 if (RHSIsOK) { 12249 // We can't evaluate the LHS; however, sometimes the result 12250 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12251 if (rhsResult == (E->getOpcode() == BO_LOr)) 12252 return Success(rhsResult, E, Result); 12253 } 12254 } 12255 12256 return false; 12257 } 12258 12259 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12260 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12261 12262 if (LHSResult.Failed || RHSResult.Failed) 12263 return false; 12264 12265 const APValue &LHSVal = LHSResult.Val; 12266 const APValue &RHSVal = RHSResult.Val; 12267 12268 // Handle cases like (unsigned long)&a + 4. 12269 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12270 Result = LHSVal; 12271 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12272 return true; 12273 } 12274 12275 // Handle cases like 4 + (unsigned long)&a 12276 if (E->getOpcode() == BO_Add && 12277 RHSVal.isLValue() && LHSVal.isInt()) { 12278 Result = RHSVal; 12279 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12280 return true; 12281 } 12282 12283 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12284 // Handle (intptr_t)&&A - (intptr_t)&&B. 12285 if (!LHSVal.getLValueOffset().isZero() || 12286 !RHSVal.getLValueOffset().isZero()) 12287 return false; 12288 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12289 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12290 if (!LHSExpr || !RHSExpr) 12291 return false; 12292 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12293 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12294 if (!LHSAddrExpr || !RHSAddrExpr) 12295 return false; 12296 // Make sure both labels come from the same function. 12297 if (LHSAddrExpr->getLabel()->getDeclContext() != 12298 RHSAddrExpr->getLabel()->getDeclContext()) 12299 return false; 12300 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12301 return true; 12302 } 12303 12304 // All the remaining cases expect both operands to be an integer 12305 if (!LHSVal.isInt() || !RHSVal.isInt()) 12306 return Error(E); 12307 12308 // Set up the width and signedness manually, in case it can't be deduced 12309 // from the operation we're performing. 12310 // FIXME: Don't do this in the cases where we can deduce it. 12311 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12312 E->getType()->isUnsignedIntegerOrEnumerationType()); 12313 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12314 RHSVal.getInt(), Value)) 12315 return false; 12316 return Success(Value, E, Result); 12317 } 12318 12319 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12320 Job &job = Queue.back(); 12321 12322 switch (job.Kind) { 12323 case Job::AnyExprKind: { 12324 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12325 if (shouldEnqueue(Bop)) { 12326 job.Kind = Job::BinOpKind; 12327 enqueue(Bop->getLHS()); 12328 return; 12329 } 12330 } 12331 12332 EvaluateExpr(job.E, Result); 12333 Queue.pop_back(); 12334 return; 12335 } 12336 12337 case Job::BinOpKind: { 12338 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12339 bool SuppressRHSDiags = false; 12340 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12341 Queue.pop_back(); 12342 return; 12343 } 12344 if (SuppressRHSDiags) 12345 job.startSpeculativeEval(Info); 12346 job.LHSResult.swap(Result); 12347 job.Kind = Job::BinOpVisitedLHSKind; 12348 enqueue(Bop->getRHS()); 12349 return; 12350 } 12351 12352 case Job::BinOpVisitedLHSKind: { 12353 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12354 EvalResult RHS; 12355 RHS.swap(Result); 12356 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12357 Queue.pop_back(); 12358 return; 12359 } 12360 } 12361 12362 llvm_unreachable("Invalid Job::Kind!"); 12363 } 12364 12365 namespace { 12366 /// Used when we determine that we should fail, but can keep evaluating prior to 12367 /// noting that we had a failure. 12368 class DelayedNoteFailureRAII { 12369 EvalInfo &Info; 12370 bool NoteFailure; 12371 12372 public: 12373 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12374 : Info(Info), NoteFailure(NoteFailure) {} 12375 ~DelayedNoteFailureRAII() { 12376 if (NoteFailure) { 12377 bool ContinueAfterFailure = Info.noteFailure(); 12378 (void)ContinueAfterFailure; 12379 assert(ContinueAfterFailure && 12380 "Shouldn't have kept evaluating on failure."); 12381 } 12382 } 12383 }; 12384 12385 enum class CmpResult { 12386 Unequal, 12387 Less, 12388 Equal, 12389 Greater, 12390 Unordered, 12391 }; 12392 } 12393 12394 template <class SuccessCB, class AfterCB> 12395 static bool 12396 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12397 SuccessCB &&Success, AfterCB &&DoAfter) { 12398 assert(E->isComparisonOp() && "expected comparison operator"); 12399 assert((E->getOpcode() == BO_Cmp || 12400 E->getType()->isIntegralOrEnumerationType()) && 12401 "unsupported binary expression evaluation"); 12402 auto Error = [&](const Expr *E) { 12403 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12404 return false; 12405 }; 12406 12407 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12408 bool IsEquality = E->isEqualityOp(); 12409 12410 QualType LHSTy = E->getLHS()->getType(); 12411 QualType RHSTy = E->getRHS()->getType(); 12412 12413 if (LHSTy->isIntegralOrEnumerationType() && 12414 RHSTy->isIntegralOrEnumerationType()) { 12415 APSInt LHS, RHS; 12416 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12417 if (!LHSOK && !Info.noteFailure()) 12418 return false; 12419 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12420 return false; 12421 if (LHS < RHS) 12422 return Success(CmpResult::Less, E); 12423 if (LHS > RHS) 12424 return Success(CmpResult::Greater, E); 12425 return Success(CmpResult::Equal, E); 12426 } 12427 12428 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12429 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12430 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12431 12432 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12433 if (!LHSOK && !Info.noteFailure()) 12434 return false; 12435 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12436 return false; 12437 if (LHSFX < RHSFX) 12438 return Success(CmpResult::Less, E); 12439 if (LHSFX > RHSFX) 12440 return Success(CmpResult::Greater, E); 12441 return Success(CmpResult::Equal, E); 12442 } 12443 12444 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12445 ComplexValue LHS, RHS; 12446 bool LHSOK; 12447 if (E->isAssignmentOp()) { 12448 LValue LV; 12449 EvaluateLValue(E->getLHS(), LV, Info); 12450 LHSOK = false; 12451 } else if (LHSTy->isRealFloatingType()) { 12452 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12453 if (LHSOK) { 12454 LHS.makeComplexFloat(); 12455 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12456 } 12457 } else { 12458 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12459 } 12460 if (!LHSOK && !Info.noteFailure()) 12461 return false; 12462 12463 if (E->getRHS()->getType()->isRealFloatingType()) { 12464 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12465 return false; 12466 RHS.makeComplexFloat(); 12467 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12468 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12469 return false; 12470 12471 if (LHS.isComplexFloat()) { 12472 APFloat::cmpResult CR_r = 12473 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12474 APFloat::cmpResult CR_i = 12475 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12476 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12477 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12478 } else { 12479 assert(IsEquality && "invalid complex comparison"); 12480 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12481 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12482 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12483 } 12484 } 12485 12486 if (LHSTy->isRealFloatingType() && 12487 RHSTy->isRealFloatingType()) { 12488 APFloat RHS(0.0), LHS(0.0); 12489 12490 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12491 if (!LHSOK && !Info.noteFailure()) 12492 return false; 12493 12494 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12495 return false; 12496 12497 assert(E->isComparisonOp() && "Invalid binary operator!"); 12498 auto GetCmpRes = [&]() { 12499 switch (LHS.compare(RHS)) { 12500 case APFloat::cmpEqual: 12501 return CmpResult::Equal; 12502 case APFloat::cmpLessThan: 12503 return CmpResult::Less; 12504 case APFloat::cmpGreaterThan: 12505 return CmpResult::Greater; 12506 case APFloat::cmpUnordered: 12507 return CmpResult::Unordered; 12508 } 12509 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12510 }; 12511 return Success(GetCmpRes(), E); 12512 } 12513 12514 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12515 LValue LHSValue, RHSValue; 12516 12517 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12518 if (!LHSOK && !Info.noteFailure()) 12519 return false; 12520 12521 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12522 return false; 12523 12524 // Reject differing bases from the normal codepath; we special-case 12525 // comparisons to null. 12526 if (!HasSameBase(LHSValue, RHSValue)) { 12527 // Inequalities and subtractions between unrelated pointers have 12528 // unspecified or undefined behavior. 12529 if (!IsEquality) { 12530 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12531 return false; 12532 } 12533 // A constant address may compare equal to the address of a symbol. 12534 // The one exception is that address of an object cannot compare equal 12535 // to a null pointer constant. 12536 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12537 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12538 return Error(E); 12539 // It's implementation-defined whether distinct literals will have 12540 // distinct addresses. In clang, the result of such a comparison is 12541 // unspecified, so it is not a constant expression. However, we do know 12542 // that the address of a literal will be non-null. 12543 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12544 LHSValue.Base && RHSValue.Base) 12545 return Error(E); 12546 // We can't tell whether weak symbols will end up pointing to the same 12547 // object. 12548 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12549 return Error(E); 12550 // We can't compare the address of the start of one object with the 12551 // past-the-end address of another object, per C++ DR1652. 12552 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12553 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12554 (RHSValue.Base && RHSValue.Offset.isZero() && 12555 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12556 return Error(E); 12557 // We can't tell whether an object is at the same address as another 12558 // zero sized object. 12559 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12560 (LHSValue.Base && isZeroSized(RHSValue))) 12561 return Error(E); 12562 return Success(CmpResult::Unequal, E); 12563 } 12564 12565 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12566 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12567 12568 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12569 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12570 12571 // C++11 [expr.rel]p3: 12572 // Pointers to void (after pointer conversions) can be compared, with a 12573 // result defined as follows: If both pointers represent the same 12574 // address or are both the null pointer value, the result is true if the 12575 // operator is <= or >= and false otherwise; otherwise the result is 12576 // unspecified. 12577 // We interpret this as applying to pointers to *cv* void. 12578 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12579 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12580 12581 // C++11 [expr.rel]p2: 12582 // - If two pointers point to non-static data members of the same object, 12583 // or to subobjects or array elements fo such members, recursively, the 12584 // pointer to the later declared member compares greater provided the 12585 // two members have the same access control and provided their class is 12586 // not a union. 12587 // [...] 12588 // - Otherwise pointer comparisons are unspecified. 12589 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12590 bool WasArrayIndex; 12591 unsigned Mismatch = FindDesignatorMismatch( 12592 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12593 // At the point where the designators diverge, the comparison has a 12594 // specified value if: 12595 // - we are comparing array indices 12596 // - we are comparing fields of a union, or fields with the same access 12597 // Otherwise, the result is unspecified and thus the comparison is not a 12598 // constant expression. 12599 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12600 Mismatch < RHSDesignator.Entries.size()) { 12601 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12602 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12603 if (!LF && !RF) 12604 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12605 else if (!LF) 12606 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12607 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12608 << RF->getParent() << RF; 12609 else if (!RF) 12610 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12611 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12612 << LF->getParent() << LF; 12613 else if (!LF->getParent()->isUnion() && 12614 LF->getAccess() != RF->getAccess()) 12615 Info.CCEDiag(E, 12616 diag::note_constexpr_pointer_comparison_differing_access) 12617 << LF << LF->getAccess() << RF << RF->getAccess() 12618 << LF->getParent(); 12619 } 12620 } 12621 12622 // The comparison here must be unsigned, and performed with the same 12623 // width as the pointer. 12624 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12625 uint64_t CompareLHS = LHSOffset.getQuantity(); 12626 uint64_t CompareRHS = RHSOffset.getQuantity(); 12627 assert(PtrSize <= 64 && "Unexpected pointer width"); 12628 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12629 CompareLHS &= Mask; 12630 CompareRHS &= Mask; 12631 12632 // If there is a base and this is a relational operator, we can only 12633 // compare pointers within the object in question; otherwise, the result 12634 // depends on where the object is located in memory. 12635 if (!LHSValue.Base.isNull() && IsRelational) { 12636 QualType BaseTy = getType(LHSValue.Base); 12637 if (BaseTy->isIncompleteType()) 12638 return Error(E); 12639 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12640 uint64_t OffsetLimit = Size.getQuantity(); 12641 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12642 return Error(E); 12643 } 12644 12645 if (CompareLHS < CompareRHS) 12646 return Success(CmpResult::Less, E); 12647 if (CompareLHS > CompareRHS) 12648 return Success(CmpResult::Greater, E); 12649 return Success(CmpResult::Equal, E); 12650 } 12651 12652 if (LHSTy->isMemberPointerType()) { 12653 assert(IsEquality && "unexpected member pointer operation"); 12654 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12655 12656 MemberPtr LHSValue, RHSValue; 12657 12658 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12659 if (!LHSOK && !Info.noteFailure()) 12660 return false; 12661 12662 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12663 return false; 12664 12665 // C++11 [expr.eq]p2: 12666 // If both operands are null, they compare equal. Otherwise if only one is 12667 // null, they compare unequal. 12668 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12669 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12670 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12671 } 12672 12673 // Otherwise if either is a pointer to a virtual member function, the 12674 // result is unspecified. 12675 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12676 if (MD->isVirtual()) 12677 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12678 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12679 if (MD->isVirtual()) 12680 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12681 12682 // Otherwise they compare equal if and only if they would refer to the 12683 // same member of the same most derived object or the same subobject if 12684 // they were dereferenced with a hypothetical object of the associated 12685 // class type. 12686 bool Equal = LHSValue == RHSValue; 12687 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12688 } 12689 12690 if (LHSTy->isNullPtrType()) { 12691 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12692 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12693 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12694 // are compared, the result is true of the operator is <=, >= or ==, and 12695 // false otherwise. 12696 return Success(CmpResult::Equal, E); 12697 } 12698 12699 return DoAfter(); 12700 } 12701 12702 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12703 if (!CheckLiteralType(Info, E)) 12704 return false; 12705 12706 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12707 ComparisonCategoryResult CCR; 12708 switch (CR) { 12709 case CmpResult::Unequal: 12710 llvm_unreachable("should never produce Unequal for three-way comparison"); 12711 case CmpResult::Less: 12712 CCR = ComparisonCategoryResult::Less; 12713 break; 12714 case CmpResult::Equal: 12715 CCR = ComparisonCategoryResult::Equal; 12716 break; 12717 case CmpResult::Greater: 12718 CCR = ComparisonCategoryResult::Greater; 12719 break; 12720 case CmpResult::Unordered: 12721 CCR = ComparisonCategoryResult::Unordered; 12722 break; 12723 } 12724 // Evaluation succeeded. Lookup the information for the comparison category 12725 // type and fetch the VarDecl for the result. 12726 const ComparisonCategoryInfo &CmpInfo = 12727 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12728 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12729 // Check and evaluate the result as a constant expression. 12730 LValue LV; 12731 LV.set(VD); 12732 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12733 return false; 12734 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12735 }; 12736 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12737 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12738 }); 12739 } 12740 12741 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12742 // We don't call noteFailure immediately because the assignment happens after 12743 // we evaluate LHS and RHS. 12744 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12745 return Error(E); 12746 12747 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12748 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12749 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12750 12751 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12752 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12753 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12754 12755 if (E->isComparisonOp()) { 12756 // Evaluate builtin binary comparisons by evaluating them as three-way 12757 // comparisons and then translating the result. 12758 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12759 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12760 "should only produce Unequal for equality comparisons"); 12761 bool IsEqual = CR == CmpResult::Equal, 12762 IsLess = CR == CmpResult::Less, 12763 IsGreater = CR == CmpResult::Greater; 12764 auto Op = E->getOpcode(); 12765 switch (Op) { 12766 default: 12767 llvm_unreachable("unsupported binary operator"); 12768 case BO_EQ: 12769 case BO_NE: 12770 return Success(IsEqual == (Op == BO_EQ), E); 12771 case BO_LT: 12772 return Success(IsLess, E); 12773 case BO_GT: 12774 return Success(IsGreater, E); 12775 case BO_LE: 12776 return Success(IsEqual || IsLess, E); 12777 case BO_GE: 12778 return Success(IsEqual || IsGreater, E); 12779 } 12780 }; 12781 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12782 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12783 }); 12784 } 12785 12786 QualType LHSTy = E->getLHS()->getType(); 12787 QualType RHSTy = E->getRHS()->getType(); 12788 12789 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12790 E->getOpcode() == BO_Sub) { 12791 LValue LHSValue, RHSValue; 12792 12793 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12794 if (!LHSOK && !Info.noteFailure()) 12795 return false; 12796 12797 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12798 return false; 12799 12800 // Reject differing bases from the normal codepath; we special-case 12801 // comparisons to null. 12802 if (!HasSameBase(LHSValue, RHSValue)) { 12803 // Handle &&A - &&B. 12804 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12805 return Error(E); 12806 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12807 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12808 if (!LHSExpr || !RHSExpr) 12809 return Error(E); 12810 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12811 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12812 if (!LHSAddrExpr || !RHSAddrExpr) 12813 return Error(E); 12814 // Make sure both labels come from the same function. 12815 if (LHSAddrExpr->getLabel()->getDeclContext() != 12816 RHSAddrExpr->getLabel()->getDeclContext()) 12817 return Error(E); 12818 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12819 } 12820 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12821 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12822 12823 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12824 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12825 12826 // C++11 [expr.add]p6: 12827 // Unless both pointers point to elements of the same array object, or 12828 // one past the last element of the array object, the behavior is 12829 // undefined. 12830 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12831 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12832 RHSDesignator)) 12833 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12834 12835 QualType Type = E->getLHS()->getType(); 12836 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12837 12838 CharUnits ElementSize; 12839 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12840 return false; 12841 12842 // As an extension, a type may have zero size (empty struct or union in 12843 // C, array of zero length). Pointer subtraction in such cases has 12844 // undefined behavior, so is not constant. 12845 if (ElementSize.isZero()) { 12846 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12847 << ElementType; 12848 return false; 12849 } 12850 12851 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12852 // and produce incorrect results when it overflows. Such behavior 12853 // appears to be non-conforming, but is common, so perhaps we should 12854 // assume the standard intended for such cases to be undefined behavior 12855 // and check for them. 12856 12857 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12858 // overflow in the final conversion to ptrdiff_t. 12859 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12860 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12861 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12862 false); 12863 APSInt TrueResult = (LHS - RHS) / ElemSize; 12864 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12865 12866 if (Result.extend(65) != TrueResult && 12867 !HandleOverflow(Info, E, TrueResult, E->getType())) 12868 return false; 12869 return Success(Result, E); 12870 } 12871 12872 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12873 } 12874 12875 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12876 /// a result as the expression's type. 12877 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12878 const UnaryExprOrTypeTraitExpr *E) { 12879 switch(E->getKind()) { 12880 case UETT_PreferredAlignOf: 12881 case UETT_AlignOf: { 12882 if (E->isArgumentType()) 12883 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12884 E); 12885 else 12886 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12887 E); 12888 } 12889 12890 case UETT_VecStep: { 12891 QualType Ty = E->getTypeOfArgument(); 12892 12893 if (Ty->isVectorType()) { 12894 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12895 12896 // The vec_step built-in functions that take a 3-component 12897 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12898 if (n == 3) 12899 n = 4; 12900 12901 return Success(n, E); 12902 } else 12903 return Success(1, E); 12904 } 12905 12906 case UETT_SizeOf: { 12907 QualType SrcTy = E->getTypeOfArgument(); 12908 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12909 // the result is the size of the referenced type." 12910 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12911 SrcTy = Ref->getPointeeType(); 12912 12913 CharUnits Sizeof; 12914 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12915 return false; 12916 return Success(Sizeof, E); 12917 } 12918 case UETT_OpenMPRequiredSimdAlign: 12919 assert(E->isArgumentType()); 12920 return Success( 12921 Info.Ctx.toCharUnitsFromBits( 12922 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12923 .getQuantity(), 12924 E); 12925 } 12926 12927 llvm_unreachable("unknown expr/type trait"); 12928 } 12929 12930 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12931 CharUnits Result; 12932 unsigned n = OOE->getNumComponents(); 12933 if (n == 0) 12934 return Error(OOE); 12935 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12936 for (unsigned i = 0; i != n; ++i) { 12937 OffsetOfNode ON = OOE->getComponent(i); 12938 switch (ON.getKind()) { 12939 case OffsetOfNode::Array: { 12940 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12941 APSInt IdxResult; 12942 if (!EvaluateInteger(Idx, IdxResult, Info)) 12943 return false; 12944 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12945 if (!AT) 12946 return Error(OOE); 12947 CurrentType = AT->getElementType(); 12948 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12949 Result += IdxResult.getSExtValue() * ElementSize; 12950 break; 12951 } 12952 12953 case OffsetOfNode::Field: { 12954 FieldDecl *MemberDecl = ON.getField(); 12955 const RecordType *RT = CurrentType->getAs<RecordType>(); 12956 if (!RT) 12957 return Error(OOE); 12958 RecordDecl *RD = RT->getDecl(); 12959 if (RD->isInvalidDecl()) return false; 12960 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12961 unsigned i = MemberDecl->getFieldIndex(); 12962 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12963 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12964 CurrentType = MemberDecl->getType().getNonReferenceType(); 12965 break; 12966 } 12967 12968 case OffsetOfNode::Identifier: 12969 llvm_unreachable("dependent __builtin_offsetof"); 12970 12971 case OffsetOfNode::Base: { 12972 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12973 if (BaseSpec->isVirtual()) 12974 return Error(OOE); 12975 12976 // Find the layout of the class whose base we are looking into. 12977 const RecordType *RT = CurrentType->getAs<RecordType>(); 12978 if (!RT) 12979 return Error(OOE); 12980 RecordDecl *RD = RT->getDecl(); 12981 if (RD->isInvalidDecl()) return false; 12982 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12983 12984 // Find the base class itself. 12985 CurrentType = BaseSpec->getType(); 12986 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12987 if (!BaseRT) 12988 return Error(OOE); 12989 12990 // Add the offset to the base. 12991 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12992 break; 12993 } 12994 } 12995 } 12996 return Success(Result, OOE); 12997 } 12998 12999 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13000 switch (E->getOpcode()) { 13001 default: 13002 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13003 // See C99 6.6p3. 13004 return Error(E); 13005 case UO_Extension: 13006 // FIXME: Should extension allow i-c-e extension expressions in its scope? 13007 // If so, we could clear the diagnostic ID. 13008 return Visit(E->getSubExpr()); 13009 case UO_Plus: 13010 // The result is just the value. 13011 return Visit(E->getSubExpr()); 13012 case UO_Minus: { 13013 if (!Visit(E->getSubExpr())) 13014 return false; 13015 if (!Result.isInt()) return Error(E); 13016 const APSInt &Value = Result.getInt(); 13017 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13018 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13019 E->getType())) 13020 return false; 13021 return Success(-Value, E); 13022 } 13023 case UO_Not: { 13024 if (!Visit(E->getSubExpr())) 13025 return false; 13026 if (!Result.isInt()) return Error(E); 13027 return Success(~Result.getInt(), E); 13028 } 13029 case UO_LNot: { 13030 bool bres; 13031 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13032 return false; 13033 return Success(!bres, E); 13034 } 13035 } 13036 } 13037 13038 /// HandleCast - This is used to evaluate implicit or explicit casts where the 13039 /// result type is integer. 13040 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13041 const Expr *SubExpr = E->getSubExpr(); 13042 QualType DestType = E->getType(); 13043 QualType SrcType = SubExpr->getType(); 13044 13045 switch (E->getCastKind()) { 13046 case CK_BaseToDerived: 13047 case CK_DerivedToBase: 13048 case CK_UncheckedDerivedToBase: 13049 case CK_Dynamic: 13050 case CK_ToUnion: 13051 case CK_ArrayToPointerDecay: 13052 case CK_FunctionToPointerDecay: 13053 case CK_NullToPointer: 13054 case CK_NullToMemberPointer: 13055 case CK_BaseToDerivedMemberPointer: 13056 case CK_DerivedToBaseMemberPointer: 13057 case CK_ReinterpretMemberPointer: 13058 case CK_ConstructorConversion: 13059 case CK_IntegralToPointer: 13060 case CK_ToVoid: 13061 case CK_VectorSplat: 13062 case CK_IntegralToFloating: 13063 case CK_FloatingCast: 13064 case CK_CPointerToObjCPointerCast: 13065 case CK_BlockPointerToObjCPointerCast: 13066 case CK_AnyPointerToBlockPointerCast: 13067 case CK_ObjCObjectLValueCast: 13068 case CK_FloatingRealToComplex: 13069 case CK_FloatingComplexToReal: 13070 case CK_FloatingComplexCast: 13071 case CK_FloatingComplexToIntegralComplex: 13072 case CK_IntegralRealToComplex: 13073 case CK_IntegralComplexCast: 13074 case CK_IntegralComplexToFloatingComplex: 13075 case CK_BuiltinFnToFnPtr: 13076 case CK_ZeroToOCLOpaqueType: 13077 case CK_NonAtomicToAtomic: 13078 case CK_AddressSpaceConversion: 13079 case CK_IntToOCLSampler: 13080 case CK_FloatingToFixedPoint: 13081 case CK_FixedPointToFloating: 13082 case CK_FixedPointCast: 13083 case CK_IntegralToFixedPoint: 13084 llvm_unreachable("invalid cast kind for integral value"); 13085 13086 case CK_BitCast: 13087 case CK_Dependent: 13088 case CK_LValueBitCast: 13089 case CK_ARCProduceObject: 13090 case CK_ARCConsumeObject: 13091 case CK_ARCReclaimReturnedObject: 13092 case CK_ARCExtendBlockObject: 13093 case CK_CopyAndAutoreleaseBlockObject: 13094 return Error(E); 13095 13096 case CK_UserDefinedConversion: 13097 case CK_LValueToRValue: 13098 case CK_AtomicToNonAtomic: 13099 case CK_NoOp: 13100 case CK_LValueToRValueBitCast: 13101 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13102 13103 case CK_MemberPointerToBoolean: 13104 case CK_PointerToBoolean: 13105 case CK_IntegralToBoolean: 13106 case CK_FloatingToBoolean: 13107 case CK_BooleanToSignedIntegral: 13108 case CK_FloatingComplexToBoolean: 13109 case CK_IntegralComplexToBoolean: { 13110 bool BoolResult; 13111 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13112 return false; 13113 uint64_t IntResult = BoolResult; 13114 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13115 IntResult = (uint64_t)-1; 13116 return Success(IntResult, E); 13117 } 13118 13119 case CK_FixedPointToIntegral: { 13120 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13121 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13122 return false; 13123 bool Overflowed; 13124 llvm::APSInt Result = Src.convertToInt( 13125 Info.Ctx.getIntWidth(DestType), 13126 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13127 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13128 return false; 13129 return Success(Result, E); 13130 } 13131 13132 case CK_FixedPointToBoolean: { 13133 // Unsigned padding does not affect this. 13134 APValue Val; 13135 if (!Evaluate(Val, Info, SubExpr)) 13136 return false; 13137 return Success(Val.getFixedPoint().getBoolValue(), E); 13138 } 13139 13140 case CK_IntegralCast: { 13141 if (!Visit(SubExpr)) 13142 return false; 13143 13144 if (!Result.isInt()) { 13145 // Allow casts of address-of-label differences if they are no-ops 13146 // or narrowing. (The narrowing case isn't actually guaranteed to 13147 // be constant-evaluatable except in some narrow cases which are hard 13148 // to detect here. We let it through on the assumption the user knows 13149 // what they are doing.) 13150 if (Result.isAddrLabelDiff()) 13151 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13152 // Only allow casts of lvalues if they are lossless. 13153 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13154 } 13155 13156 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13157 Result.getInt()), E); 13158 } 13159 13160 case CK_PointerToIntegral: { 13161 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13162 13163 LValue LV; 13164 if (!EvaluatePointer(SubExpr, LV, Info)) 13165 return false; 13166 13167 if (LV.getLValueBase()) { 13168 // Only allow based lvalue casts if they are lossless. 13169 // FIXME: Allow a larger integer size than the pointer size, and allow 13170 // narrowing back down to pointer width in subsequent integral casts. 13171 // FIXME: Check integer type's active bits, not its type size. 13172 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13173 return Error(E); 13174 13175 LV.Designator.setInvalid(); 13176 LV.moveInto(Result); 13177 return true; 13178 } 13179 13180 APSInt AsInt; 13181 APValue V; 13182 LV.moveInto(V); 13183 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13184 llvm_unreachable("Can't cast this!"); 13185 13186 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13187 } 13188 13189 case CK_IntegralComplexToReal: { 13190 ComplexValue C; 13191 if (!EvaluateComplex(SubExpr, C, Info)) 13192 return false; 13193 return Success(C.getComplexIntReal(), E); 13194 } 13195 13196 case CK_FloatingToIntegral: { 13197 APFloat F(0.0); 13198 if (!EvaluateFloat(SubExpr, F, Info)) 13199 return false; 13200 13201 APSInt Value; 13202 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13203 return false; 13204 return Success(Value, E); 13205 } 13206 } 13207 13208 llvm_unreachable("unknown cast resulting in integral value"); 13209 } 13210 13211 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13212 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13213 ComplexValue LV; 13214 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13215 return false; 13216 if (!LV.isComplexInt()) 13217 return Error(E); 13218 return Success(LV.getComplexIntReal(), E); 13219 } 13220 13221 return Visit(E->getSubExpr()); 13222 } 13223 13224 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13225 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13226 ComplexValue LV; 13227 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13228 return false; 13229 if (!LV.isComplexInt()) 13230 return Error(E); 13231 return Success(LV.getComplexIntImag(), E); 13232 } 13233 13234 VisitIgnoredValue(E->getSubExpr()); 13235 return Success(0, E); 13236 } 13237 13238 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13239 return Success(E->getPackLength(), E); 13240 } 13241 13242 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13243 return Success(E->getValue(), E); 13244 } 13245 13246 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13247 const ConceptSpecializationExpr *E) { 13248 return Success(E->isSatisfied(), E); 13249 } 13250 13251 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13252 return Success(E->isSatisfied(), E); 13253 } 13254 13255 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13256 switch (E->getOpcode()) { 13257 default: 13258 // Invalid unary operators 13259 return Error(E); 13260 case UO_Plus: 13261 // The result is just the value. 13262 return Visit(E->getSubExpr()); 13263 case UO_Minus: { 13264 if (!Visit(E->getSubExpr())) return false; 13265 if (!Result.isFixedPoint()) 13266 return Error(E); 13267 bool Overflowed; 13268 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13269 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13270 return false; 13271 return Success(Negated, E); 13272 } 13273 case UO_LNot: { 13274 bool bres; 13275 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13276 return false; 13277 return Success(!bres, E); 13278 } 13279 } 13280 } 13281 13282 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13283 const Expr *SubExpr = E->getSubExpr(); 13284 QualType DestType = E->getType(); 13285 assert(DestType->isFixedPointType() && 13286 "Expected destination type to be a fixed point type"); 13287 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13288 13289 switch (E->getCastKind()) { 13290 case CK_FixedPointCast: { 13291 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13292 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13293 return false; 13294 bool Overflowed; 13295 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13296 if (Overflowed) { 13297 if (Info.checkingForUndefinedBehavior()) 13298 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13299 diag::warn_fixedpoint_constant_overflow) 13300 << Result.toString() << E->getType(); 13301 else if (!HandleOverflow(Info, E, Result, E->getType())) 13302 return false; 13303 } 13304 return Success(Result, E); 13305 } 13306 case CK_IntegralToFixedPoint: { 13307 APSInt Src; 13308 if (!EvaluateInteger(SubExpr, Src, Info)) 13309 return false; 13310 13311 bool Overflowed; 13312 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13313 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13314 13315 if (Overflowed) { 13316 if (Info.checkingForUndefinedBehavior()) 13317 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13318 diag::warn_fixedpoint_constant_overflow) 13319 << IntResult.toString() << E->getType(); 13320 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13321 return false; 13322 } 13323 13324 return Success(IntResult, E); 13325 } 13326 case CK_FloatingToFixedPoint: { 13327 APFloat Src(0.0); 13328 if (!EvaluateFloat(SubExpr, Src, Info)) 13329 return false; 13330 13331 bool Overflowed; 13332 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13333 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13334 13335 if (Overflowed) { 13336 if (Info.checkingForUndefinedBehavior()) 13337 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13338 diag::warn_fixedpoint_constant_overflow) 13339 << Result.toString() << E->getType(); 13340 else if (!HandleOverflow(Info, E, Result, E->getType())) 13341 return false; 13342 } 13343 13344 return Success(Result, E); 13345 } 13346 case CK_NoOp: 13347 case CK_LValueToRValue: 13348 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13349 default: 13350 return Error(E); 13351 } 13352 } 13353 13354 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13355 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13356 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13357 13358 const Expr *LHS = E->getLHS(); 13359 const Expr *RHS = E->getRHS(); 13360 FixedPointSemantics ResultFXSema = 13361 Info.Ctx.getFixedPointSemantics(E->getType()); 13362 13363 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13364 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13365 return false; 13366 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13367 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13368 return false; 13369 13370 bool OpOverflow = false, ConversionOverflow = false; 13371 APFixedPoint Result(LHSFX.getSemantics()); 13372 switch (E->getOpcode()) { 13373 case BO_Add: { 13374 Result = LHSFX.add(RHSFX, &OpOverflow) 13375 .convert(ResultFXSema, &ConversionOverflow); 13376 break; 13377 } 13378 case BO_Sub: { 13379 Result = LHSFX.sub(RHSFX, &OpOverflow) 13380 .convert(ResultFXSema, &ConversionOverflow); 13381 break; 13382 } 13383 case BO_Mul: { 13384 Result = LHSFX.mul(RHSFX, &OpOverflow) 13385 .convert(ResultFXSema, &ConversionOverflow); 13386 break; 13387 } 13388 case BO_Div: { 13389 if (RHSFX.getValue() == 0) { 13390 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13391 return false; 13392 } 13393 Result = LHSFX.div(RHSFX, &OpOverflow) 13394 .convert(ResultFXSema, &ConversionOverflow); 13395 break; 13396 } 13397 case BO_Shl: 13398 case BO_Shr: { 13399 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13400 llvm::APSInt RHSVal = RHSFX.getValue(); 13401 13402 unsigned ShiftBW = 13403 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13404 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13405 // Embedded-C 4.1.6.2.2: 13406 // The right operand must be nonnegative and less than the total number 13407 // of (nonpadding) bits of the fixed-point operand ... 13408 if (RHSVal.isNegative()) 13409 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13410 else if (Amt != RHSVal) 13411 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13412 << RHSVal << E->getType() << ShiftBW; 13413 13414 if (E->getOpcode() == BO_Shl) 13415 Result = LHSFX.shl(Amt, &OpOverflow); 13416 else 13417 Result = LHSFX.shr(Amt, &OpOverflow); 13418 break; 13419 } 13420 default: 13421 return false; 13422 } 13423 if (OpOverflow || ConversionOverflow) { 13424 if (Info.checkingForUndefinedBehavior()) 13425 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13426 diag::warn_fixedpoint_constant_overflow) 13427 << Result.toString() << E->getType(); 13428 else if (!HandleOverflow(Info, E, Result, E->getType())) 13429 return false; 13430 } 13431 return Success(Result, E); 13432 } 13433 13434 //===----------------------------------------------------------------------===// 13435 // Float Evaluation 13436 //===----------------------------------------------------------------------===// 13437 13438 namespace { 13439 class FloatExprEvaluator 13440 : public ExprEvaluatorBase<FloatExprEvaluator> { 13441 APFloat &Result; 13442 public: 13443 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13444 : ExprEvaluatorBaseTy(info), Result(result) {} 13445 13446 bool Success(const APValue &V, const Expr *e) { 13447 Result = V.getFloat(); 13448 return true; 13449 } 13450 13451 bool ZeroInitialization(const Expr *E) { 13452 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13453 return true; 13454 } 13455 13456 bool VisitCallExpr(const CallExpr *E); 13457 13458 bool VisitUnaryOperator(const UnaryOperator *E); 13459 bool VisitBinaryOperator(const BinaryOperator *E); 13460 bool VisitFloatingLiteral(const FloatingLiteral *E); 13461 bool VisitCastExpr(const CastExpr *E); 13462 13463 bool VisitUnaryReal(const UnaryOperator *E); 13464 bool VisitUnaryImag(const UnaryOperator *E); 13465 13466 // FIXME: Missing: array subscript of vector, member of vector 13467 }; 13468 } // end anonymous namespace 13469 13470 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13471 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13472 return FloatExprEvaluator(Info, Result).Visit(E); 13473 } 13474 13475 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13476 QualType ResultTy, 13477 const Expr *Arg, 13478 bool SNaN, 13479 llvm::APFloat &Result) { 13480 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13481 if (!S) return false; 13482 13483 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13484 13485 llvm::APInt fill; 13486 13487 // Treat empty strings as if they were zero. 13488 if (S->getString().empty()) 13489 fill = llvm::APInt(32, 0); 13490 else if (S->getString().getAsInteger(0, fill)) 13491 return false; 13492 13493 if (Context.getTargetInfo().isNan2008()) { 13494 if (SNaN) 13495 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13496 else 13497 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13498 } else { 13499 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13500 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13501 // a different encoding to what became a standard in 2008, and for pre- 13502 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13503 // sNaN. This is now known as "legacy NaN" encoding. 13504 if (SNaN) 13505 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13506 else 13507 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13508 } 13509 13510 return true; 13511 } 13512 13513 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13514 switch (E->getBuiltinCallee()) { 13515 default: 13516 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13517 13518 case Builtin::BI__builtin_huge_val: 13519 case Builtin::BI__builtin_huge_valf: 13520 case Builtin::BI__builtin_huge_vall: 13521 case Builtin::BI__builtin_huge_valf128: 13522 case Builtin::BI__builtin_inf: 13523 case Builtin::BI__builtin_inff: 13524 case Builtin::BI__builtin_infl: 13525 case Builtin::BI__builtin_inff128: { 13526 const llvm::fltSemantics &Sem = 13527 Info.Ctx.getFloatTypeSemantics(E->getType()); 13528 Result = llvm::APFloat::getInf(Sem); 13529 return true; 13530 } 13531 13532 case Builtin::BI__builtin_nans: 13533 case Builtin::BI__builtin_nansf: 13534 case Builtin::BI__builtin_nansl: 13535 case Builtin::BI__builtin_nansf128: 13536 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13537 true, Result)) 13538 return Error(E); 13539 return true; 13540 13541 case Builtin::BI__builtin_nan: 13542 case Builtin::BI__builtin_nanf: 13543 case Builtin::BI__builtin_nanl: 13544 case Builtin::BI__builtin_nanf128: 13545 // If this is __builtin_nan() turn this into a nan, otherwise we 13546 // can't constant fold it. 13547 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13548 false, Result)) 13549 return Error(E); 13550 return true; 13551 13552 case Builtin::BI__builtin_fabs: 13553 case Builtin::BI__builtin_fabsf: 13554 case Builtin::BI__builtin_fabsl: 13555 case Builtin::BI__builtin_fabsf128: 13556 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13557 return false; 13558 13559 if (Result.isNegative()) 13560 Result.changeSign(); 13561 return true; 13562 13563 // FIXME: Builtin::BI__builtin_powi 13564 // FIXME: Builtin::BI__builtin_powif 13565 // FIXME: Builtin::BI__builtin_powil 13566 13567 case Builtin::BI__builtin_copysign: 13568 case Builtin::BI__builtin_copysignf: 13569 case Builtin::BI__builtin_copysignl: 13570 case Builtin::BI__builtin_copysignf128: { 13571 APFloat RHS(0.); 13572 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13573 !EvaluateFloat(E->getArg(1), RHS, Info)) 13574 return false; 13575 Result.copySign(RHS); 13576 return true; 13577 } 13578 } 13579 } 13580 13581 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13582 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13583 ComplexValue CV; 13584 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13585 return false; 13586 Result = CV.FloatReal; 13587 return true; 13588 } 13589 13590 return Visit(E->getSubExpr()); 13591 } 13592 13593 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13594 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13595 ComplexValue CV; 13596 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13597 return false; 13598 Result = CV.FloatImag; 13599 return true; 13600 } 13601 13602 VisitIgnoredValue(E->getSubExpr()); 13603 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13604 Result = llvm::APFloat::getZero(Sem); 13605 return true; 13606 } 13607 13608 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13609 switch (E->getOpcode()) { 13610 default: return Error(E); 13611 case UO_Plus: 13612 return EvaluateFloat(E->getSubExpr(), Result, Info); 13613 case UO_Minus: 13614 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13615 return false; 13616 Result.changeSign(); 13617 return true; 13618 } 13619 } 13620 13621 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13622 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13623 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13624 13625 APFloat RHS(0.0); 13626 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13627 if (!LHSOK && !Info.noteFailure()) 13628 return false; 13629 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13630 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13631 } 13632 13633 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13634 Result = E->getValue(); 13635 return true; 13636 } 13637 13638 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13639 const Expr* SubExpr = E->getSubExpr(); 13640 13641 switch (E->getCastKind()) { 13642 default: 13643 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13644 13645 case CK_IntegralToFloating: { 13646 APSInt IntResult; 13647 return EvaluateInteger(SubExpr, IntResult, Info) && 13648 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13649 E->getType(), Result); 13650 } 13651 13652 case CK_FixedPointToFloating: { 13653 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13654 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13655 return false; 13656 Result = 13657 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13658 return true; 13659 } 13660 13661 case CK_FloatingCast: { 13662 if (!Visit(SubExpr)) 13663 return false; 13664 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13665 Result); 13666 } 13667 13668 case CK_FloatingComplexToReal: { 13669 ComplexValue V; 13670 if (!EvaluateComplex(SubExpr, V, Info)) 13671 return false; 13672 Result = V.getComplexFloatReal(); 13673 return true; 13674 } 13675 } 13676 } 13677 13678 //===----------------------------------------------------------------------===// 13679 // Complex Evaluation (for float and integer) 13680 //===----------------------------------------------------------------------===// 13681 13682 namespace { 13683 class ComplexExprEvaluator 13684 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13685 ComplexValue &Result; 13686 13687 public: 13688 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13689 : ExprEvaluatorBaseTy(info), Result(Result) {} 13690 13691 bool Success(const APValue &V, const Expr *e) { 13692 Result.setFrom(V); 13693 return true; 13694 } 13695 13696 bool ZeroInitialization(const Expr *E); 13697 13698 //===--------------------------------------------------------------------===// 13699 // Visitor Methods 13700 //===--------------------------------------------------------------------===// 13701 13702 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13703 bool VisitCastExpr(const CastExpr *E); 13704 bool VisitBinaryOperator(const BinaryOperator *E); 13705 bool VisitUnaryOperator(const UnaryOperator *E); 13706 bool VisitInitListExpr(const InitListExpr *E); 13707 bool VisitCallExpr(const CallExpr *E); 13708 }; 13709 } // end anonymous namespace 13710 13711 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13712 EvalInfo &Info) { 13713 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13714 return ComplexExprEvaluator(Info, Result).Visit(E); 13715 } 13716 13717 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13718 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13719 if (ElemTy->isRealFloatingType()) { 13720 Result.makeComplexFloat(); 13721 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13722 Result.FloatReal = Zero; 13723 Result.FloatImag = Zero; 13724 } else { 13725 Result.makeComplexInt(); 13726 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13727 Result.IntReal = Zero; 13728 Result.IntImag = Zero; 13729 } 13730 return true; 13731 } 13732 13733 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13734 const Expr* SubExpr = E->getSubExpr(); 13735 13736 if (SubExpr->getType()->isRealFloatingType()) { 13737 Result.makeComplexFloat(); 13738 APFloat &Imag = Result.FloatImag; 13739 if (!EvaluateFloat(SubExpr, Imag, Info)) 13740 return false; 13741 13742 Result.FloatReal = APFloat(Imag.getSemantics()); 13743 return true; 13744 } else { 13745 assert(SubExpr->getType()->isIntegerType() && 13746 "Unexpected imaginary literal."); 13747 13748 Result.makeComplexInt(); 13749 APSInt &Imag = Result.IntImag; 13750 if (!EvaluateInteger(SubExpr, Imag, Info)) 13751 return false; 13752 13753 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13754 return true; 13755 } 13756 } 13757 13758 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13759 13760 switch (E->getCastKind()) { 13761 case CK_BitCast: 13762 case CK_BaseToDerived: 13763 case CK_DerivedToBase: 13764 case CK_UncheckedDerivedToBase: 13765 case CK_Dynamic: 13766 case CK_ToUnion: 13767 case CK_ArrayToPointerDecay: 13768 case CK_FunctionToPointerDecay: 13769 case CK_NullToPointer: 13770 case CK_NullToMemberPointer: 13771 case CK_BaseToDerivedMemberPointer: 13772 case CK_DerivedToBaseMemberPointer: 13773 case CK_MemberPointerToBoolean: 13774 case CK_ReinterpretMemberPointer: 13775 case CK_ConstructorConversion: 13776 case CK_IntegralToPointer: 13777 case CK_PointerToIntegral: 13778 case CK_PointerToBoolean: 13779 case CK_ToVoid: 13780 case CK_VectorSplat: 13781 case CK_IntegralCast: 13782 case CK_BooleanToSignedIntegral: 13783 case CK_IntegralToBoolean: 13784 case CK_IntegralToFloating: 13785 case CK_FloatingToIntegral: 13786 case CK_FloatingToBoolean: 13787 case CK_FloatingCast: 13788 case CK_CPointerToObjCPointerCast: 13789 case CK_BlockPointerToObjCPointerCast: 13790 case CK_AnyPointerToBlockPointerCast: 13791 case CK_ObjCObjectLValueCast: 13792 case CK_FloatingComplexToReal: 13793 case CK_FloatingComplexToBoolean: 13794 case CK_IntegralComplexToReal: 13795 case CK_IntegralComplexToBoolean: 13796 case CK_ARCProduceObject: 13797 case CK_ARCConsumeObject: 13798 case CK_ARCReclaimReturnedObject: 13799 case CK_ARCExtendBlockObject: 13800 case CK_CopyAndAutoreleaseBlockObject: 13801 case CK_BuiltinFnToFnPtr: 13802 case CK_ZeroToOCLOpaqueType: 13803 case CK_NonAtomicToAtomic: 13804 case CK_AddressSpaceConversion: 13805 case CK_IntToOCLSampler: 13806 case CK_FloatingToFixedPoint: 13807 case CK_FixedPointToFloating: 13808 case CK_FixedPointCast: 13809 case CK_FixedPointToBoolean: 13810 case CK_FixedPointToIntegral: 13811 case CK_IntegralToFixedPoint: 13812 llvm_unreachable("invalid cast kind for complex value"); 13813 13814 case CK_LValueToRValue: 13815 case CK_AtomicToNonAtomic: 13816 case CK_NoOp: 13817 case CK_LValueToRValueBitCast: 13818 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13819 13820 case CK_Dependent: 13821 case CK_LValueBitCast: 13822 case CK_UserDefinedConversion: 13823 return Error(E); 13824 13825 case CK_FloatingRealToComplex: { 13826 APFloat &Real = Result.FloatReal; 13827 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13828 return false; 13829 13830 Result.makeComplexFloat(); 13831 Result.FloatImag = APFloat(Real.getSemantics()); 13832 return true; 13833 } 13834 13835 case CK_FloatingComplexCast: { 13836 if (!Visit(E->getSubExpr())) 13837 return false; 13838 13839 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13840 QualType From 13841 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13842 13843 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13844 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13845 } 13846 13847 case CK_FloatingComplexToIntegralComplex: { 13848 if (!Visit(E->getSubExpr())) 13849 return false; 13850 13851 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13852 QualType From 13853 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13854 Result.makeComplexInt(); 13855 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13856 To, Result.IntReal) && 13857 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13858 To, Result.IntImag); 13859 } 13860 13861 case CK_IntegralRealToComplex: { 13862 APSInt &Real = Result.IntReal; 13863 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13864 return false; 13865 13866 Result.makeComplexInt(); 13867 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13868 return true; 13869 } 13870 13871 case CK_IntegralComplexCast: { 13872 if (!Visit(E->getSubExpr())) 13873 return false; 13874 13875 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13876 QualType From 13877 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13878 13879 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13880 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13881 return true; 13882 } 13883 13884 case CK_IntegralComplexToFloatingComplex: { 13885 if (!Visit(E->getSubExpr())) 13886 return false; 13887 13888 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13889 QualType From 13890 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13891 Result.makeComplexFloat(); 13892 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13893 To, Result.FloatReal) && 13894 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13895 To, Result.FloatImag); 13896 } 13897 } 13898 13899 llvm_unreachable("unknown cast resulting in complex value"); 13900 } 13901 13902 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13903 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13904 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13905 13906 // Track whether the LHS or RHS is real at the type system level. When this is 13907 // the case we can simplify our evaluation strategy. 13908 bool LHSReal = false, RHSReal = false; 13909 13910 bool LHSOK; 13911 if (E->getLHS()->getType()->isRealFloatingType()) { 13912 LHSReal = true; 13913 APFloat &Real = Result.FloatReal; 13914 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13915 if (LHSOK) { 13916 Result.makeComplexFloat(); 13917 Result.FloatImag = APFloat(Real.getSemantics()); 13918 } 13919 } else { 13920 LHSOK = Visit(E->getLHS()); 13921 } 13922 if (!LHSOK && !Info.noteFailure()) 13923 return false; 13924 13925 ComplexValue RHS; 13926 if (E->getRHS()->getType()->isRealFloatingType()) { 13927 RHSReal = true; 13928 APFloat &Real = RHS.FloatReal; 13929 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13930 return false; 13931 RHS.makeComplexFloat(); 13932 RHS.FloatImag = APFloat(Real.getSemantics()); 13933 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13934 return false; 13935 13936 assert(!(LHSReal && RHSReal) && 13937 "Cannot have both operands of a complex operation be real."); 13938 switch (E->getOpcode()) { 13939 default: return Error(E); 13940 case BO_Add: 13941 if (Result.isComplexFloat()) { 13942 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13943 APFloat::rmNearestTiesToEven); 13944 if (LHSReal) 13945 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13946 else if (!RHSReal) 13947 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13948 APFloat::rmNearestTiesToEven); 13949 } else { 13950 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13951 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13952 } 13953 break; 13954 case BO_Sub: 13955 if (Result.isComplexFloat()) { 13956 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13957 APFloat::rmNearestTiesToEven); 13958 if (LHSReal) { 13959 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13960 Result.getComplexFloatImag().changeSign(); 13961 } else if (!RHSReal) { 13962 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13963 APFloat::rmNearestTiesToEven); 13964 } 13965 } else { 13966 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13967 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13968 } 13969 break; 13970 case BO_Mul: 13971 if (Result.isComplexFloat()) { 13972 // This is an implementation of complex multiplication according to the 13973 // constraints laid out in C11 Annex G. The implementation uses the 13974 // following naming scheme: 13975 // (a + ib) * (c + id) 13976 ComplexValue LHS = Result; 13977 APFloat &A = LHS.getComplexFloatReal(); 13978 APFloat &B = LHS.getComplexFloatImag(); 13979 APFloat &C = RHS.getComplexFloatReal(); 13980 APFloat &D = RHS.getComplexFloatImag(); 13981 APFloat &ResR = Result.getComplexFloatReal(); 13982 APFloat &ResI = Result.getComplexFloatImag(); 13983 if (LHSReal) { 13984 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13985 ResR = A * C; 13986 ResI = A * D; 13987 } else if (RHSReal) { 13988 ResR = C * A; 13989 ResI = C * B; 13990 } else { 13991 // In the fully general case, we need to handle NaNs and infinities 13992 // robustly. 13993 APFloat AC = A * C; 13994 APFloat BD = B * D; 13995 APFloat AD = A * D; 13996 APFloat BC = B * C; 13997 ResR = AC - BD; 13998 ResI = AD + BC; 13999 if (ResR.isNaN() && ResI.isNaN()) { 14000 bool Recalc = false; 14001 if (A.isInfinity() || B.isInfinity()) { 14002 A = APFloat::copySign( 14003 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14004 B = APFloat::copySign( 14005 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14006 if (C.isNaN()) 14007 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14008 if (D.isNaN()) 14009 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14010 Recalc = true; 14011 } 14012 if (C.isInfinity() || D.isInfinity()) { 14013 C = APFloat::copySign( 14014 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14015 D = APFloat::copySign( 14016 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14017 if (A.isNaN()) 14018 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14019 if (B.isNaN()) 14020 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14021 Recalc = true; 14022 } 14023 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14024 AD.isInfinity() || BC.isInfinity())) { 14025 if (A.isNaN()) 14026 A = APFloat::copySign(APFloat(A.getSemantics()), A); 14027 if (B.isNaN()) 14028 B = APFloat::copySign(APFloat(B.getSemantics()), B); 14029 if (C.isNaN()) 14030 C = APFloat::copySign(APFloat(C.getSemantics()), C); 14031 if (D.isNaN()) 14032 D = APFloat::copySign(APFloat(D.getSemantics()), D); 14033 Recalc = true; 14034 } 14035 if (Recalc) { 14036 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14037 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14038 } 14039 } 14040 } 14041 } else { 14042 ComplexValue LHS = Result; 14043 Result.getComplexIntReal() = 14044 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14045 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14046 Result.getComplexIntImag() = 14047 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14048 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14049 } 14050 break; 14051 case BO_Div: 14052 if (Result.isComplexFloat()) { 14053 // This is an implementation of complex division according to the 14054 // constraints laid out in C11 Annex G. The implementation uses the 14055 // following naming scheme: 14056 // (a + ib) / (c + id) 14057 ComplexValue LHS = Result; 14058 APFloat &A = LHS.getComplexFloatReal(); 14059 APFloat &B = LHS.getComplexFloatImag(); 14060 APFloat &C = RHS.getComplexFloatReal(); 14061 APFloat &D = RHS.getComplexFloatImag(); 14062 APFloat &ResR = Result.getComplexFloatReal(); 14063 APFloat &ResI = Result.getComplexFloatImag(); 14064 if (RHSReal) { 14065 ResR = A / C; 14066 ResI = B / C; 14067 } else { 14068 if (LHSReal) { 14069 // No real optimizations we can do here, stub out with zero. 14070 B = APFloat::getZero(A.getSemantics()); 14071 } 14072 int DenomLogB = 0; 14073 APFloat MaxCD = maxnum(abs(C), abs(D)); 14074 if (MaxCD.isFinite()) { 14075 DenomLogB = ilogb(MaxCD); 14076 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14077 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14078 } 14079 APFloat Denom = C * C + D * D; 14080 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14081 APFloat::rmNearestTiesToEven); 14082 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14083 APFloat::rmNearestTiesToEven); 14084 if (ResR.isNaN() && ResI.isNaN()) { 14085 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14086 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14087 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14088 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14089 D.isFinite()) { 14090 A = APFloat::copySign( 14091 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14092 B = APFloat::copySign( 14093 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14094 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14095 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14096 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14097 C = APFloat::copySign( 14098 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14099 D = APFloat::copySign( 14100 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14101 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14102 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14103 } 14104 } 14105 } 14106 } else { 14107 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14108 return Error(E, diag::note_expr_divide_by_zero); 14109 14110 ComplexValue LHS = Result; 14111 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14112 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14113 Result.getComplexIntReal() = 14114 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14115 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14116 Result.getComplexIntImag() = 14117 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14118 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14119 } 14120 break; 14121 } 14122 14123 return true; 14124 } 14125 14126 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14127 // Get the operand value into 'Result'. 14128 if (!Visit(E->getSubExpr())) 14129 return false; 14130 14131 switch (E->getOpcode()) { 14132 default: 14133 return Error(E); 14134 case UO_Extension: 14135 return true; 14136 case UO_Plus: 14137 // The result is always just the subexpr. 14138 return true; 14139 case UO_Minus: 14140 if (Result.isComplexFloat()) { 14141 Result.getComplexFloatReal().changeSign(); 14142 Result.getComplexFloatImag().changeSign(); 14143 } 14144 else { 14145 Result.getComplexIntReal() = -Result.getComplexIntReal(); 14146 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14147 } 14148 return true; 14149 case UO_Not: 14150 if (Result.isComplexFloat()) 14151 Result.getComplexFloatImag().changeSign(); 14152 else 14153 Result.getComplexIntImag() = -Result.getComplexIntImag(); 14154 return true; 14155 } 14156 } 14157 14158 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14159 if (E->getNumInits() == 2) { 14160 if (E->getType()->isComplexType()) { 14161 Result.makeComplexFloat(); 14162 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14163 return false; 14164 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14165 return false; 14166 } else { 14167 Result.makeComplexInt(); 14168 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14169 return false; 14170 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14171 return false; 14172 } 14173 return true; 14174 } 14175 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14176 } 14177 14178 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14179 switch (E->getBuiltinCallee()) { 14180 case Builtin::BI__builtin_complex: 14181 Result.makeComplexFloat(); 14182 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14183 return false; 14184 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14185 return false; 14186 return true; 14187 14188 default: 14189 break; 14190 } 14191 14192 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14193 } 14194 14195 //===----------------------------------------------------------------------===// 14196 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14197 // implicit conversion. 14198 //===----------------------------------------------------------------------===// 14199 14200 namespace { 14201 class AtomicExprEvaluator : 14202 public ExprEvaluatorBase<AtomicExprEvaluator> { 14203 const LValue *This; 14204 APValue &Result; 14205 public: 14206 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14207 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14208 14209 bool Success(const APValue &V, const Expr *E) { 14210 Result = V; 14211 return true; 14212 } 14213 14214 bool ZeroInitialization(const Expr *E) { 14215 ImplicitValueInitExpr VIE( 14216 E->getType()->castAs<AtomicType>()->getValueType()); 14217 // For atomic-qualified class (and array) types in C++, initialize the 14218 // _Atomic-wrapped subobject directly, in-place. 14219 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14220 : Evaluate(Result, Info, &VIE); 14221 } 14222 14223 bool VisitCastExpr(const CastExpr *E) { 14224 switch (E->getCastKind()) { 14225 default: 14226 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14227 case CK_NonAtomicToAtomic: 14228 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14229 : Evaluate(Result, Info, E->getSubExpr()); 14230 } 14231 } 14232 }; 14233 } // end anonymous namespace 14234 14235 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14236 EvalInfo &Info) { 14237 assert(E->isRValue() && E->getType()->isAtomicType()); 14238 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14239 } 14240 14241 //===----------------------------------------------------------------------===// 14242 // Void expression evaluation, primarily for a cast to void on the LHS of a 14243 // comma operator 14244 //===----------------------------------------------------------------------===// 14245 14246 namespace { 14247 class VoidExprEvaluator 14248 : public ExprEvaluatorBase<VoidExprEvaluator> { 14249 public: 14250 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14251 14252 bool Success(const APValue &V, const Expr *e) { return true; } 14253 14254 bool ZeroInitialization(const Expr *E) { return true; } 14255 14256 bool VisitCastExpr(const CastExpr *E) { 14257 switch (E->getCastKind()) { 14258 default: 14259 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14260 case CK_ToVoid: 14261 VisitIgnoredValue(E->getSubExpr()); 14262 return true; 14263 } 14264 } 14265 14266 bool VisitCallExpr(const CallExpr *E) { 14267 switch (E->getBuiltinCallee()) { 14268 case Builtin::BI__assume: 14269 case Builtin::BI__builtin_assume: 14270 // The argument is not evaluated! 14271 return true; 14272 14273 case Builtin::BI__builtin_operator_delete: 14274 return HandleOperatorDeleteCall(Info, E); 14275 14276 default: 14277 break; 14278 } 14279 14280 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14281 } 14282 14283 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14284 }; 14285 } // end anonymous namespace 14286 14287 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14288 // We cannot speculatively evaluate a delete expression. 14289 if (Info.SpeculativeEvaluationDepth) 14290 return false; 14291 14292 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14293 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14294 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14295 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14296 return false; 14297 } 14298 14299 const Expr *Arg = E->getArgument(); 14300 14301 LValue Pointer; 14302 if (!EvaluatePointer(Arg, Pointer, Info)) 14303 return false; 14304 if (Pointer.Designator.Invalid) 14305 return false; 14306 14307 // Deleting a null pointer has no effect. 14308 if (Pointer.isNullPointer()) { 14309 // This is the only case where we need to produce an extension warning: 14310 // the only other way we can succeed is if we find a dynamic allocation, 14311 // and we will have warned when we allocated it in that case. 14312 if (!Info.getLangOpts().CPlusPlus20) 14313 Info.CCEDiag(E, diag::note_constexpr_new); 14314 return true; 14315 } 14316 14317 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14318 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14319 if (!Alloc) 14320 return false; 14321 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14322 14323 // For the non-array case, the designator must be empty if the static type 14324 // does not have a virtual destructor. 14325 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14326 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14327 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14328 << Arg->getType()->getPointeeType() << AllocType; 14329 return false; 14330 } 14331 14332 // For a class type with a virtual destructor, the selected operator delete 14333 // is the one looked up when building the destructor. 14334 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14335 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14336 if (VirtualDelete && 14337 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14338 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14339 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14340 return false; 14341 } 14342 } 14343 14344 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14345 (*Alloc)->Value, AllocType)) 14346 return false; 14347 14348 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14349 // The element was already erased. This means the destructor call also 14350 // deleted the object. 14351 // FIXME: This probably results in undefined behavior before we get this 14352 // far, and should be diagnosed elsewhere first. 14353 Info.FFDiag(E, diag::note_constexpr_double_delete); 14354 return false; 14355 } 14356 14357 return true; 14358 } 14359 14360 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14361 assert(E->isRValue() && E->getType()->isVoidType()); 14362 return VoidExprEvaluator(Info).Visit(E); 14363 } 14364 14365 //===----------------------------------------------------------------------===// 14366 // Top level Expr::EvaluateAsRValue method. 14367 //===----------------------------------------------------------------------===// 14368 14369 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14370 // In C, function designators are not lvalues, but we evaluate them as if they 14371 // are. 14372 QualType T = E->getType(); 14373 if (E->isGLValue() || T->isFunctionType()) { 14374 LValue LV; 14375 if (!EvaluateLValue(E, LV, Info)) 14376 return false; 14377 LV.moveInto(Result); 14378 } else if (T->isVectorType()) { 14379 if (!EvaluateVector(E, Result, Info)) 14380 return false; 14381 } else if (T->isIntegralOrEnumerationType()) { 14382 if (!IntExprEvaluator(Info, Result).Visit(E)) 14383 return false; 14384 } else if (T->hasPointerRepresentation()) { 14385 LValue LV; 14386 if (!EvaluatePointer(E, LV, Info)) 14387 return false; 14388 LV.moveInto(Result); 14389 } else if (T->isRealFloatingType()) { 14390 llvm::APFloat F(0.0); 14391 if (!EvaluateFloat(E, F, Info)) 14392 return false; 14393 Result = APValue(F); 14394 } else if (T->isAnyComplexType()) { 14395 ComplexValue C; 14396 if (!EvaluateComplex(E, C, Info)) 14397 return false; 14398 C.moveInto(Result); 14399 } else if (T->isFixedPointType()) { 14400 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14401 } else if (T->isMemberPointerType()) { 14402 MemberPtr P; 14403 if (!EvaluateMemberPointer(E, P, Info)) 14404 return false; 14405 P.moveInto(Result); 14406 return true; 14407 } else if (T->isArrayType()) { 14408 LValue LV; 14409 APValue &Value = 14410 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14411 if (!EvaluateArray(E, LV, Value, Info)) 14412 return false; 14413 Result = Value; 14414 } else if (T->isRecordType()) { 14415 LValue LV; 14416 APValue &Value = 14417 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14418 if (!EvaluateRecord(E, LV, Value, Info)) 14419 return false; 14420 Result = Value; 14421 } else if (T->isVoidType()) { 14422 if (!Info.getLangOpts().CPlusPlus11) 14423 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14424 << E->getType(); 14425 if (!EvaluateVoid(E, Info)) 14426 return false; 14427 } else if (T->isAtomicType()) { 14428 QualType Unqual = T.getAtomicUnqualifiedType(); 14429 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14430 LValue LV; 14431 APValue &Value = Info.CurrentCall->createTemporary( 14432 E, Unqual, ScopeKind::FullExpression, LV); 14433 if (!EvaluateAtomic(E, &LV, Value, Info)) 14434 return false; 14435 } else { 14436 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14437 return false; 14438 } 14439 } else if (Info.getLangOpts().CPlusPlus11) { 14440 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14441 return false; 14442 } else { 14443 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14444 return false; 14445 } 14446 14447 return true; 14448 } 14449 14450 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14451 /// cases, the in-place evaluation is essential, since later initializers for 14452 /// an object can indirectly refer to subobjects which were initialized earlier. 14453 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14454 const Expr *E, bool AllowNonLiteralTypes) { 14455 assert(!E->isValueDependent()); 14456 14457 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14458 return false; 14459 14460 if (E->isRValue()) { 14461 // Evaluate arrays and record types in-place, so that later initializers can 14462 // refer to earlier-initialized members of the object. 14463 QualType T = E->getType(); 14464 if (T->isArrayType()) 14465 return EvaluateArray(E, This, Result, Info); 14466 else if (T->isRecordType()) 14467 return EvaluateRecord(E, This, Result, Info); 14468 else if (T->isAtomicType()) { 14469 QualType Unqual = T.getAtomicUnqualifiedType(); 14470 if (Unqual->isArrayType() || Unqual->isRecordType()) 14471 return EvaluateAtomic(E, &This, Result, Info); 14472 } 14473 } 14474 14475 // For any other type, in-place evaluation is unimportant. 14476 return Evaluate(Result, Info, E); 14477 } 14478 14479 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14480 /// lvalue-to-rvalue cast if it is an lvalue. 14481 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14482 if (Info.EnableNewConstInterp) { 14483 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14484 return false; 14485 } else { 14486 if (E->getType().isNull()) 14487 return false; 14488 14489 if (!CheckLiteralType(Info, E)) 14490 return false; 14491 14492 if (!::Evaluate(Result, Info, E)) 14493 return false; 14494 14495 if (E->isGLValue()) { 14496 LValue LV; 14497 LV.setFrom(Info.Ctx, Result); 14498 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14499 return false; 14500 } 14501 } 14502 14503 // Check this core constant expression is a constant expression. 14504 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14505 CheckMemoryLeaks(Info); 14506 } 14507 14508 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14509 const ASTContext &Ctx, bool &IsConst) { 14510 // Fast-path evaluations of integer literals, since we sometimes see files 14511 // containing vast quantities of these. 14512 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14513 Result.Val = APValue(APSInt(L->getValue(), 14514 L->getType()->isUnsignedIntegerType())); 14515 IsConst = true; 14516 return true; 14517 } 14518 14519 // This case should be rare, but we need to check it before we check on 14520 // the type below. 14521 if (Exp->getType().isNull()) { 14522 IsConst = false; 14523 return true; 14524 } 14525 14526 // FIXME: Evaluating values of large array and record types can cause 14527 // performance problems. Only do so in C++11 for now. 14528 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14529 Exp->getType()->isRecordType()) && 14530 !Ctx.getLangOpts().CPlusPlus11) { 14531 IsConst = false; 14532 return true; 14533 } 14534 return false; 14535 } 14536 14537 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14538 Expr::SideEffectsKind SEK) { 14539 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14540 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14541 } 14542 14543 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14544 const ASTContext &Ctx, EvalInfo &Info) { 14545 bool IsConst; 14546 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14547 return IsConst; 14548 14549 return EvaluateAsRValue(Info, E, Result.Val); 14550 } 14551 14552 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14553 const ASTContext &Ctx, 14554 Expr::SideEffectsKind AllowSideEffects, 14555 EvalInfo &Info) { 14556 if (!E->getType()->isIntegralOrEnumerationType()) 14557 return false; 14558 14559 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14560 !ExprResult.Val.isInt() || 14561 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14562 return false; 14563 14564 return true; 14565 } 14566 14567 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14568 const ASTContext &Ctx, 14569 Expr::SideEffectsKind AllowSideEffects, 14570 EvalInfo &Info) { 14571 if (!E->getType()->isFixedPointType()) 14572 return false; 14573 14574 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14575 return false; 14576 14577 if (!ExprResult.Val.isFixedPoint() || 14578 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14579 return false; 14580 14581 return true; 14582 } 14583 14584 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14585 /// any crazy technique (that has nothing to do with language standards) that 14586 /// we want to. If this function returns true, it returns the folded constant 14587 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14588 /// will be applied to the result. 14589 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14590 bool InConstantContext) const { 14591 assert(!isValueDependent() && 14592 "Expression evaluator can't be called on a dependent expression."); 14593 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14594 Info.InConstantContext = InConstantContext; 14595 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14596 } 14597 14598 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14599 bool InConstantContext) const { 14600 assert(!isValueDependent() && 14601 "Expression evaluator can't be called on a dependent expression."); 14602 EvalResult Scratch; 14603 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14604 HandleConversionToBool(Scratch.Val, Result); 14605 } 14606 14607 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14608 SideEffectsKind AllowSideEffects, 14609 bool InConstantContext) const { 14610 assert(!isValueDependent() && 14611 "Expression evaluator can't be called on a dependent expression."); 14612 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14613 Info.InConstantContext = InConstantContext; 14614 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14615 } 14616 14617 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14618 SideEffectsKind AllowSideEffects, 14619 bool InConstantContext) const { 14620 assert(!isValueDependent() && 14621 "Expression evaluator can't be called on a dependent expression."); 14622 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14623 Info.InConstantContext = InConstantContext; 14624 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14625 } 14626 14627 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14628 SideEffectsKind AllowSideEffects, 14629 bool InConstantContext) const { 14630 assert(!isValueDependent() && 14631 "Expression evaluator can't be called on a dependent expression."); 14632 14633 if (!getType()->isRealFloatingType()) 14634 return false; 14635 14636 EvalResult ExprResult; 14637 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14638 !ExprResult.Val.isFloat() || 14639 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14640 return false; 14641 14642 Result = ExprResult.Val.getFloat(); 14643 return true; 14644 } 14645 14646 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14647 bool InConstantContext) const { 14648 assert(!isValueDependent() && 14649 "Expression evaluator can't be called on a dependent expression."); 14650 14651 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14652 Info.InConstantContext = InConstantContext; 14653 LValue LV; 14654 CheckedTemporaries CheckedTemps; 14655 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14656 Result.HasSideEffects || 14657 !CheckLValueConstantExpression(Info, getExprLoc(), 14658 Ctx.getLValueReferenceType(getType()), LV, 14659 Expr::EvaluateForCodeGen, CheckedTemps)) 14660 return false; 14661 14662 LV.moveInto(Result.Val); 14663 return true; 14664 } 14665 14666 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14667 const ASTContext &Ctx, bool InPlace) const { 14668 assert(!isValueDependent() && 14669 "Expression evaluator can't be called on a dependent expression."); 14670 14671 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14672 EvalInfo Info(Ctx, Result, EM); 14673 Info.InConstantContext = true; 14674 14675 if (InPlace) { 14676 Info.setEvaluatingDecl(this, Result.Val); 14677 LValue LVal; 14678 LVal.set(this); 14679 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14680 Result.HasSideEffects) 14681 return false; 14682 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14683 return false; 14684 14685 if (!Info.discardCleanups()) 14686 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14687 14688 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14689 Result.Val, Usage) && 14690 CheckMemoryLeaks(Info); 14691 } 14692 14693 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14694 const VarDecl *VD, 14695 SmallVectorImpl<PartialDiagnosticAt> &Notes, 14696 bool IsConstantInitialization) const { 14697 assert(!isValueDependent() && 14698 "Expression evaluator can't be called on a dependent expression."); 14699 14700 // FIXME: Evaluating initializers for large array and record types can cause 14701 // performance problems. Only do so in C++11 for now. 14702 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14703 !Ctx.getLangOpts().CPlusPlus11) 14704 return false; 14705 14706 Expr::EvalStatus EStatus; 14707 EStatus.Diag = &Notes; 14708 14709 EvalInfo Info(Ctx, EStatus, 14710 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14711 ? EvalInfo::EM_ConstantExpression 14712 : EvalInfo::EM_ConstantFold); 14713 Info.setEvaluatingDecl(VD, Value); 14714 Info.InConstantContext = IsConstantInitialization; 14715 14716 SourceLocation DeclLoc = VD->getLocation(); 14717 QualType DeclTy = VD->getType(); 14718 14719 if (Info.EnableNewConstInterp) { 14720 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14721 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14722 return false; 14723 } else { 14724 LValue LVal; 14725 LVal.set(VD); 14726 14727 if (!EvaluateInPlace(Value, Info, LVal, this, 14728 /*AllowNonLiteralTypes=*/true) || 14729 EStatus.HasSideEffects) 14730 return false; 14731 14732 // At this point, any lifetime-extended temporaries are completely 14733 // initialized. 14734 Info.performLifetimeExtension(); 14735 14736 if (!Info.discardCleanups()) 14737 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14738 } 14739 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14740 CheckMemoryLeaks(Info); 14741 } 14742 14743 bool VarDecl::evaluateDestruction( 14744 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14745 Expr::EvalStatus EStatus; 14746 EStatus.Diag = &Notes; 14747 14748 // Make a copy of the value for the destructor to mutate, if we know it. 14749 // Otherwise, treat the value as default-initialized; if the destructor works 14750 // anyway, then the destruction is constant (and must be essentially empty). 14751 APValue DestroyedValue; 14752 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14753 DestroyedValue = *getEvaluatedValue(); 14754 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14755 return false; 14756 14757 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14758 Info.setEvaluatingDecl(this, DestroyedValue, 14759 EvalInfo::EvaluatingDeclKind::Dtor); 14760 Info.InConstantContext = true; 14761 14762 SourceLocation DeclLoc = getLocation(); 14763 QualType DeclTy = getType(); 14764 14765 LValue LVal; 14766 LVal.set(this); 14767 14768 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14769 EStatus.HasSideEffects) 14770 return false; 14771 14772 if (!Info.discardCleanups()) 14773 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14774 14775 ensureEvaluatedStmt()->HasConstantDestruction = true; 14776 return true; 14777 } 14778 14779 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14780 /// constant folded, but discard the result. 14781 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14782 assert(!isValueDependent() && 14783 "Expression evaluator can't be called on a dependent expression."); 14784 14785 EvalResult Result; 14786 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14787 !hasUnacceptableSideEffect(Result, SEK); 14788 } 14789 14790 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14791 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14792 assert(!isValueDependent() && 14793 "Expression evaluator can't be called on a dependent expression."); 14794 14795 EvalResult EVResult; 14796 EVResult.Diag = Diag; 14797 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14798 Info.InConstantContext = true; 14799 14800 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14801 (void)Result; 14802 assert(Result && "Could not evaluate expression"); 14803 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14804 14805 return EVResult.Val.getInt(); 14806 } 14807 14808 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14809 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14810 assert(!isValueDependent() && 14811 "Expression evaluator can't be called on a dependent expression."); 14812 14813 EvalResult EVResult; 14814 EVResult.Diag = Diag; 14815 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14816 Info.InConstantContext = true; 14817 Info.CheckingForUndefinedBehavior = true; 14818 14819 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14820 (void)Result; 14821 assert(Result && "Could not evaluate expression"); 14822 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14823 14824 return EVResult.Val.getInt(); 14825 } 14826 14827 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14828 assert(!isValueDependent() && 14829 "Expression evaluator can't be called on a dependent expression."); 14830 14831 bool IsConst; 14832 EvalResult EVResult; 14833 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14834 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14835 Info.CheckingForUndefinedBehavior = true; 14836 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14837 } 14838 } 14839 14840 bool Expr::EvalResult::isGlobalLValue() const { 14841 assert(Val.isLValue()); 14842 return IsGlobalLValue(Val.getLValueBase()); 14843 } 14844 14845 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14846 /// an integer constant expression. 14847 14848 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14849 /// comma, etc 14850 14851 // CheckICE - This function does the fundamental ICE checking: the returned 14852 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14853 // and a (possibly null) SourceLocation indicating the location of the problem. 14854 // 14855 // Note that to reduce code duplication, this helper does no evaluation 14856 // itself; the caller checks whether the expression is evaluatable, and 14857 // in the rare cases where CheckICE actually cares about the evaluated 14858 // value, it calls into Evaluate. 14859 14860 namespace { 14861 14862 enum ICEKind { 14863 /// This expression is an ICE. 14864 IK_ICE, 14865 /// This expression is not an ICE, but if it isn't evaluated, it's 14866 /// a legal subexpression for an ICE. This return value is used to handle 14867 /// the comma operator in C99 mode, and non-constant subexpressions. 14868 IK_ICEIfUnevaluated, 14869 /// This expression is not an ICE, and is not a legal subexpression for one. 14870 IK_NotICE 14871 }; 14872 14873 struct ICEDiag { 14874 ICEKind Kind; 14875 SourceLocation Loc; 14876 14877 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14878 }; 14879 14880 } 14881 14882 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14883 14884 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14885 14886 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14887 Expr::EvalResult EVResult; 14888 Expr::EvalStatus Status; 14889 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14890 14891 Info.InConstantContext = true; 14892 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14893 !EVResult.Val.isInt()) 14894 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14895 14896 return NoDiag(); 14897 } 14898 14899 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14900 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14901 if (!E->getType()->isIntegralOrEnumerationType()) 14902 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14903 14904 switch (E->getStmtClass()) { 14905 #define ABSTRACT_STMT(Node) 14906 #define STMT(Node, Base) case Expr::Node##Class: 14907 #define EXPR(Node, Base) 14908 #include "clang/AST/StmtNodes.inc" 14909 case Expr::PredefinedExprClass: 14910 case Expr::FloatingLiteralClass: 14911 case Expr::ImaginaryLiteralClass: 14912 case Expr::StringLiteralClass: 14913 case Expr::ArraySubscriptExprClass: 14914 case Expr::MatrixSubscriptExprClass: 14915 case Expr::OMPArraySectionExprClass: 14916 case Expr::OMPArrayShapingExprClass: 14917 case Expr::OMPIteratorExprClass: 14918 case Expr::MemberExprClass: 14919 case Expr::CompoundAssignOperatorClass: 14920 case Expr::CompoundLiteralExprClass: 14921 case Expr::ExtVectorElementExprClass: 14922 case Expr::DesignatedInitExprClass: 14923 case Expr::ArrayInitLoopExprClass: 14924 case Expr::ArrayInitIndexExprClass: 14925 case Expr::NoInitExprClass: 14926 case Expr::DesignatedInitUpdateExprClass: 14927 case Expr::ImplicitValueInitExprClass: 14928 case Expr::ParenListExprClass: 14929 case Expr::VAArgExprClass: 14930 case Expr::AddrLabelExprClass: 14931 case Expr::StmtExprClass: 14932 case Expr::CXXMemberCallExprClass: 14933 case Expr::CUDAKernelCallExprClass: 14934 case Expr::CXXAddrspaceCastExprClass: 14935 case Expr::CXXDynamicCastExprClass: 14936 case Expr::CXXTypeidExprClass: 14937 case Expr::CXXUuidofExprClass: 14938 case Expr::MSPropertyRefExprClass: 14939 case Expr::MSPropertySubscriptExprClass: 14940 case Expr::CXXNullPtrLiteralExprClass: 14941 case Expr::UserDefinedLiteralClass: 14942 case Expr::CXXThisExprClass: 14943 case Expr::CXXThrowExprClass: 14944 case Expr::CXXNewExprClass: 14945 case Expr::CXXDeleteExprClass: 14946 case Expr::CXXPseudoDestructorExprClass: 14947 case Expr::UnresolvedLookupExprClass: 14948 case Expr::TypoExprClass: 14949 case Expr::RecoveryExprClass: 14950 case Expr::DependentScopeDeclRefExprClass: 14951 case Expr::CXXConstructExprClass: 14952 case Expr::CXXInheritedCtorInitExprClass: 14953 case Expr::CXXStdInitializerListExprClass: 14954 case Expr::CXXBindTemporaryExprClass: 14955 case Expr::ExprWithCleanupsClass: 14956 case Expr::CXXTemporaryObjectExprClass: 14957 case Expr::CXXUnresolvedConstructExprClass: 14958 case Expr::CXXDependentScopeMemberExprClass: 14959 case Expr::UnresolvedMemberExprClass: 14960 case Expr::ObjCStringLiteralClass: 14961 case Expr::ObjCBoxedExprClass: 14962 case Expr::ObjCArrayLiteralClass: 14963 case Expr::ObjCDictionaryLiteralClass: 14964 case Expr::ObjCEncodeExprClass: 14965 case Expr::ObjCMessageExprClass: 14966 case Expr::ObjCSelectorExprClass: 14967 case Expr::ObjCProtocolExprClass: 14968 case Expr::ObjCIvarRefExprClass: 14969 case Expr::ObjCPropertyRefExprClass: 14970 case Expr::ObjCSubscriptRefExprClass: 14971 case Expr::ObjCIsaExprClass: 14972 case Expr::ObjCAvailabilityCheckExprClass: 14973 case Expr::ShuffleVectorExprClass: 14974 case Expr::ConvertVectorExprClass: 14975 case Expr::BlockExprClass: 14976 case Expr::NoStmtClass: 14977 case Expr::OpaqueValueExprClass: 14978 case Expr::PackExpansionExprClass: 14979 case Expr::SubstNonTypeTemplateParmPackExprClass: 14980 case Expr::FunctionParmPackExprClass: 14981 case Expr::AsTypeExprClass: 14982 case Expr::ObjCIndirectCopyRestoreExprClass: 14983 case Expr::MaterializeTemporaryExprClass: 14984 case Expr::PseudoObjectExprClass: 14985 case Expr::AtomicExprClass: 14986 case Expr::LambdaExprClass: 14987 case Expr::CXXFoldExprClass: 14988 case Expr::CoawaitExprClass: 14989 case Expr::DependentCoawaitExprClass: 14990 case Expr::CoyieldExprClass: 14991 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14992 14993 case Expr::InitListExprClass: { 14994 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14995 // form "T x = { a };" is equivalent to "T x = a;". 14996 // Unless we're initializing a reference, T is a scalar as it is known to be 14997 // of integral or enumeration type. 14998 if (E->isRValue()) 14999 if (cast<InitListExpr>(E)->getNumInits() == 1) 15000 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15001 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15002 } 15003 15004 case Expr::SizeOfPackExprClass: 15005 case Expr::GNUNullExprClass: 15006 case Expr::SourceLocExprClass: 15007 return NoDiag(); 15008 15009 case Expr::SubstNonTypeTemplateParmExprClass: 15010 return 15011 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15012 15013 case Expr::ConstantExprClass: 15014 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15015 15016 case Expr::ParenExprClass: 15017 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15018 case Expr::GenericSelectionExprClass: 15019 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15020 case Expr::IntegerLiteralClass: 15021 case Expr::FixedPointLiteralClass: 15022 case Expr::CharacterLiteralClass: 15023 case Expr::ObjCBoolLiteralExprClass: 15024 case Expr::CXXBoolLiteralExprClass: 15025 case Expr::CXXScalarValueInitExprClass: 15026 case Expr::TypeTraitExprClass: 15027 case Expr::ConceptSpecializationExprClass: 15028 case Expr::RequiresExprClass: 15029 case Expr::ArrayTypeTraitExprClass: 15030 case Expr::ExpressionTraitExprClass: 15031 case Expr::CXXNoexceptExprClass: 15032 return NoDiag(); 15033 case Expr::CallExprClass: 15034 case Expr::CXXOperatorCallExprClass: { 15035 // C99 6.6/3 allows function calls within unevaluated subexpressions of 15036 // constant expressions, but they can never be ICEs because an ICE cannot 15037 // contain an operand of (pointer to) function type. 15038 const CallExpr *CE = cast<CallExpr>(E); 15039 if (CE->getBuiltinCallee()) 15040 return CheckEvalInICE(E, Ctx); 15041 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15042 } 15043 case Expr::CXXRewrittenBinaryOperatorClass: 15044 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15045 Ctx); 15046 case Expr::DeclRefExprClass: { 15047 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15048 if (isa<EnumConstantDecl>(D)) 15049 return NoDiag(); 15050 15051 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15052 // integer variables in constant expressions: 15053 // 15054 // C++ 7.1.5.1p2 15055 // A variable of non-volatile const-qualified integral or enumeration 15056 // type initialized by an ICE can be used in ICEs. 15057 const VarDecl *VD = dyn_cast<VarDecl>(D); 15058 if (VD && VD->isUsableInConstantExpressions(Ctx)) 15059 return NoDiag(); 15060 15061 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15062 } 15063 case Expr::UnaryOperatorClass: { 15064 const UnaryOperator *Exp = cast<UnaryOperator>(E); 15065 switch (Exp->getOpcode()) { 15066 case UO_PostInc: 15067 case UO_PostDec: 15068 case UO_PreInc: 15069 case UO_PreDec: 15070 case UO_AddrOf: 15071 case UO_Deref: 15072 case UO_Coawait: 15073 // C99 6.6/3 allows increment and decrement within unevaluated 15074 // subexpressions of constant expressions, but they can never be ICEs 15075 // because an ICE cannot contain an lvalue operand. 15076 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15077 case UO_Extension: 15078 case UO_LNot: 15079 case UO_Plus: 15080 case UO_Minus: 15081 case UO_Not: 15082 case UO_Real: 15083 case UO_Imag: 15084 return CheckICE(Exp->getSubExpr(), Ctx); 15085 } 15086 llvm_unreachable("invalid unary operator class"); 15087 } 15088 case Expr::OffsetOfExprClass: { 15089 // Note that per C99, offsetof must be an ICE. And AFAIK, using 15090 // EvaluateAsRValue matches the proposed gcc behavior for cases like 15091 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15092 // compliance: we should warn earlier for offsetof expressions with 15093 // array subscripts that aren't ICEs, and if the array subscripts 15094 // are ICEs, the value of the offsetof must be an integer constant. 15095 return CheckEvalInICE(E, Ctx); 15096 } 15097 case Expr::UnaryExprOrTypeTraitExprClass: { 15098 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15099 if ((Exp->getKind() == UETT_SizeOf) && 15100 Exp->getTypeOfArgument()->isVariableArrayType()) 15101 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15102 return NoDiag(); 15103 } 15104 case Expr::BinaryOperatorClass: { 15105 const BinaryOperator *Exp = cast<BinaryOperator>(E); 15106 switch (Exp->getOpcode()) { 15107 case BO_PtrMemD: 15108 case BO_PtrMemI: 15109 case BO_Assign: 15110 case BO_MulAssign: 15111 case BO_DivAssign: 15112 case BO_RemAssign: 15113 case BO_AddAssign: 15114 case BO_SubAssign: 15115 case BO_ShlAssign: 15116 case BO_ShrAssign: 15117 case BO_AndAssign: 15118 case BO_XorAssign: 15119 case BO_OrAssign: 15120 // C99 6.6/3 allows assignments within unevaluated subexpressions of 15121 // constant expressions, but they can never be ICEs because an ICE cannot 15122 // contain an lvalue operand. 15123 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15124 15125 case BO_Mul: 15126 case BO_Div: 15127 case BO_Rem: 15128 case BO_Add: 15129 case BO_Sub: 15130 case BO_Shl: 15131 case BO_Shr: 15132 case BO_LT: 15133 case BO_GT: 15134 case BO_LE: 15135 case BO_GE: 15136 case BO_EQ: 15137 case BO_NE: 15138 case BO_And: 15139 case BO_Xor: 15140 case BO_Or: 15141 case BO_Comma: 15142 case BO_Cmp: { 15143 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15144 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15145 if (Exp->getOpcode() == BO_Div || 15146 Exp->getOpcode() == BO_Rem) { 15147 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15148 // we don't evaluate one. 15149 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15150 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15151 if (REval == 0) 15152 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15153 if (REval.isSigned() && REval.isAllOnesValue()) { 15154 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15155 if (LEval.isMinSignedValue()) 15156 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15157 } 15158 } 15159 } 15160 if (Exp->getOpcode() == BO_Comma) { 15161 if (Ctx.getLangOpts().C99) { 15162 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15163 // if it isn't evaluated. 15164 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15165 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15166 } else { 15167 // In both C89 and C++, commas in ICEs are illegal. 15168 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15169 } 15170 } 15171 return Worst(LHSResult, RHSResult); 15172 } 15173 case BO_LAnd: 15174 case BO_LOr: { 15175 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15176 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15177 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15178 // Rare case where the RHS has a comma "side-effect"; we need 15179 // to actually check the condition to see whether the side 15180 // with the comma is evaluated. 15181 if ((Exp->getOpcode() == BO_LAnd) != 15182 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15183 return RHSResult; 15184 return NoDiag(); 15185 } 15186 15187 return Worst(LHSResult, RHSResult); 15188 } 15189 } 15190 llvm_unreachable("invalid binary operator kind"); 15191 } 15192 case Expr::ImplicitCastExprClass: 15193 case Expr::CStyleCastExprClass: 15194 case Expr::CXXFunctionalCastExprClass: 15195 case Expr::CXXStaticCastExprClass: 15196 case Expr::CXXReinterpretCastExprClass: 15197 case Expr::CXXConstCastExprClass: 15198 case Expr::ObjCBridgedCastExprClass: { 15199 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15200 if (isa<ExplicitCastExpr>(E)) { 15201 if (const FloatingLiteral *FL 15202 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15203 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15204 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15205 APSInt IgnoredVal(DestWidth, !DestSigned); 15206 bool Ignored; 15207 // If the value does not fit in the destination type, the behavior is 15208 // undefined, so we are not required to treat it as a constant 15209 // expression. 15210 if (FL->getValue().convertToInteger(IgnoredVal, 15211 llvm::APFloat::rmTowardZero, 15212 &Ignored) & APFloat::opInvalidOp) 15213 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15214 return NoDiag(); 15215 } 15216 } 15217 switch (cast<CastExpr>(E)->getCastKind()) { 15218 case CK_LValueToRValue: 15219 case CK_AtomicToNonAtomic: 15220 case CK_NonAtomicToAtomic: 15221 case CK_NoOp: 15222 case CK_IntegralToBoolean: 15223 case CK_IntegralCast: 15224 return CheckICE(SubExpr, Ctx); 15225 default: 15226 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15227 } 15228 } 15229 case Expr::BinaryConditionalOperatorClass: { 15230 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15231 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15232 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15233 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15234 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15235 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15236 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15237 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15238 return FalseResult; 15239 } 15240 case Expr::ConditionalOperatorClass: { 15241 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15242 // If the condition (ignoring parens) is a __builtin_constant_p call, 15243 // then only the true side is actually considered in an integer constant 15244 // expression, and it is fully evaluated. This is an important GNU 15245 // extension. See GCC PR38377 for discussion. 15246 if (const CallExpr *CallCE 15247 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15248 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15249 return CheckEvalInICE(E, Ctx); 15250 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15251 if (CondResult.Kind == IK_NotICE) 15252 return CondResult; 15253 15254 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15255 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15256 15257 if (TrueResult.Kind == IK_NotICE) 15258 return TrueResult; 15259 if (FalseResult.Kind == IK_NotICE) 15260 return FalseResult; 15261 if (CondResult.Kind == IK_ICEIfUnevaluated) 15262 return CondResult; 15263 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15264 return NoDiag(); 15265 // Rare case where the diagnostics depend on which side is evaluated 15266 // Note that if we get here, CondResult is 0, and at least one of 15267 // TrueResult and FalseResult is non-zero. 15268 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15269 return FalseResult; 15270 return TrueResult; 15271 } 15272 case Expr::CXXDefaultArgExprClass: 15273 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15274 case Expr::CXXDefaultInitExprClass: 15275 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15276 case Expr::ChooseExprClass: { 15277 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15278 } 15279 case Expr::BuiltinBitCastExprClass: { 15280 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15281 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15282 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15283 } 15284 } 15285 15286 llvm_unreachable("Invalid StmtClass!"); 15287 } 15288 15289 /// Evaluate an expression as a C++11 integral constant expression. 15290 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15291 const Expr *E, 15292 llvm::APSInt *Value, 15293 SourceLocation *Loc) { 15294 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15295 if (Loc) *Loc = E->getExprLoc(); 15296 return false; 15297 } 15298 15299 APValue Result; 15300 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15301 return false; 15302 15303 if (!Result.isInt()) { 15304 if (Loc) *Loc = E->getExprLoc(); 15305 return false; 15306 } 15307 15308 if (Value) *Value = Result.getInt(); 15309 return true; 15310 } 15311 15312 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15313 SourceLocation *Loc) const { 15314 assert(!isValueDependent() && 15315 "Expression evaluator can't be called on a dependent expression."); 15316 15317 if (Ctx.getLangOpts().CPlusPlus11) 15318 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15319 15320 ICEDiag D = CheckICE(this, Ctx); 15321 if (D.Kind != IK_ICE) { 15322 if (Loc) *Loc = D.Loc; 15323 return false; 15324 } 15325 return true; 15326 } 15327 15328 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15329 SourceLocation *Loc, 15330 bool isEvaluated) const { 15331 assert(!isValueDependent() && 15332 "Expression evaluator can't be called on a dependent expression."); 15333 15334 APSInt Value; 15335 15336 if (Ctx.getLangOpts().CPlusPlus11) { 15337 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15338 return Value; 15339 return None; 15340 } 15341 15342 if (!isIntegerConstantExpr(Ctx, Loc)) 15343 return None; 15344 15345 // The only possible side-effects here are due to UB discovered in the 15346 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15347 // required to treat the expression as an ICE, so we produce the folded 15348 // value. 15349 EvalResult ExprResult; 15350 Expr::EvalStatus Status; 15351 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15352 Info.InConstantContext = true; 15353 15354 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15355 llvm_unreachable("ICE cannot be evaluated!"); 15356 15357 return ExprResult.Val.getInt(); 15358 } 15359 15360 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15361 assert(!isValueDependent() && 15362 "Expression evaluator can't be called on a dependent expression."); 15363 15364 return CheckICE(this, Ctx).Kind == IK_ICE; 15365 } 15366 15367 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15368 SourceLocation *Loc) const { 15369 assert(!isValueDependent() && 15370 "Expression evaluator can't be called on a dependent expression."); 15371 15372 // We support this checking in C++98 mode in order to diagnose compatibility 15373 // issues. 15374 assert(Ctx.getLangOpts().CPlusPlus); 15375 15376 // Build evaluation settings. 15377 Expr::EvalStatus Status; 15378 SmallVector<PartialDiagnosticAt, 8> Diags; 15379 Status.Diag = &Diags; 15380 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15381 15382 APValue Scratch; 15383 bool IsConstExpr = 15384 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15385 // FIXME: We don't produce a diagnostic for this, but the callers that 15386 // call us on arbitrary full-expressions should generally not care. 15387 Info.discardCleanups() && !Status.HasSideEffects; 15388 15389 if (!Diags.empty()) { 15390 IsConstExpr = false; 15391 if (Loc) *Loc = Diags[0].first; 15392 } else if (!IsConstExpr) { 15393 // FIXME: This shouldn't happen. 15394 if (Loc) *Loc = getExprLoc(); 15395 } 15396 15397 return IsConstExpr; 15398 } 15399 15400 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15401 const FunctionDecl *Callee, 15402 ArrayRef<const Expr*> Args, 15403 const Expr *This) const { 15404 assert(!isValueDependent() && 15405 "Expression evaluator can't be called on a dependent expression."); 15406 15407 Expr::EvalStatus Status; 15408 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15409 Info.InConstantContext = true; 15410 15411 LValue ThisVal; 15412 const LValue *ThisPtr = nullptr; 15413 if (This) { 15414 #ifndef NDEBUG 15415 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15416 assert(MD && "Don't provide `this` for non-methods."); 15417 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15418 #endif 15419 if (!This->isValueDependent() && 15420 EvaluateObjectArgument(Info, This, ThisVal) && 15421 !Info.EvalStatus.HasSideEffects) 15422 ThisPtr = &ThisVal; 15423 15424 // Ignore any side-effects from a failed evaluation. This is safe because 15425 // they can't interfere with any other argument evaluation. 15426 Info.EvalStatus.HasSideEffects = false; 15427 } 15428 15429 CallRef Call = Info.CurrentCall->createCall(Callee); 15430 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15431 I != E; ++I) { 15432 unsigned Idx = I - Args.begin(); 15433 if (Idx >= Callee->getNumParams()) 15434 break; 15435 const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15436 if ((*I)->isValueDependent() || 15437 !EvaluateCallArg(PVD, *I, Call, Info) || 15438 Info.EvalStatus.HasSideEffects) { 15439 // If evaluation fails, throw away the argument entirely. 15440 if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15441 *Slot = APValue(); 15442 } 15443 15444 // Ignore any side-effects from a failed evaluation. This is safe because 15445 // they can't interfere with any other argument evaluation. 15446 Info.EvalStatus.HasSideEffects = false; 15447 } 15448 15449 // Parameter cleanups happen in the caller and are not part of this 15450 // evaluation. 15451 Info.discardCleanups(); 15452 Info.EvalStatus.HasSideEffects = false; 15453 15454 // Build fake call to Callee. 15455 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15456 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15457 FullExpressionRAII Scope(Info); 15458 return Evaluate(Value, Info, this) && Scope.destroy() && 15459 !Info.EvalStatus.HasSideEffects; 15460 } 15461 15462 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15463 SmallVectorImpl< 15464 PartialDiagnosticAt> &Diags) { 15465 // FIXME: It would be useful to check constexpr function templates, but at the 15466 // moment the constant expression evaluator cannot cope with the non-rigorous 15467 // ASTs which we build for dependent expressions. 15468 if (FD->isDependentContext()) 15469 return true; 15470 15471 // Bail out if a constexpr constructor has an initializer that contains an 15472 // error. We deliberately don't produce a diagnostic, as we have produced a 15473 // relevant diagnostic when parsing the error initializer. 15474 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15475 for (const auto *InitExpr : Ctor->inits()) { 15476 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15477 return false; 15478 } 15479 } 15480 Expr::EvalStatus Status; 15481 Status.Diag = &Diags; 15482 15483 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15484 Info.InConstantContext = true; 15485 Info.CheckingPotentialConstantExpression = true; 15486 15487 // The constexpr VM attempts to compile all methods to bytecode here. 15488 if (Info.EnableNewConstInterp) { 15489 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15490 return Diags.empty(); 15491 } 15492 15493 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15494 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15495 15496 // Fabricate an arbitrary expression on the stack and pretend that it 15497 // is a temporary being used as the 'this' pointer. 15498 LValue This; 15499 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15500 This.set({&VIE, Info.CurrentCall->Index}); 15501 15502 ArrayRef<const Expr*> Args; 15503 15504 APValue Scratch; 15505 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15506 // Evaluate the call as a constant initializer, to allow the construction 15507 // of objects of non-literal types. 15508 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15509 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15510 } else { 15511 SourceLocation Loc = FD->getLocation(); 15512 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15513 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15514 } 15515 15516 return Diags.empty(); 15517 } 15518 15519 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15520 const FunctionDecl *FD, 15521 SmallVectorImpl< 15522 PartialDiagnosticAt> &Diags) { 15523 assert(!E->isValueDependent() && 15524 "Expression evaluator can't be called on a dependent expression."); 15525 15526 Expr::EvalStatus Status; 15527 Status.Diag = &Diags; 15528 15529 EvalInfo Info(FD->getASTContext(), Status, 15530 EvalInfo::EM_ConstantExpressionUnevaluated); 15531 Info.InConstantContext = true; 15532 Info.CheckingPotentialConstantExpression = true; 15533 15534 // Fabricate a call stack frame to give the arguments a plausible cover story. 15535 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15536 15537 APValue ResultScratch; 15538 Evaluate(ResultScratch, Info, E); 15539 return Diags.empty(); 15540 } 15541 15542 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15543 unsigned Type) const { 15544 if (!getType()->isPointerType()) 15545 return false; 15546 15547 Expr::EvalStatus Status; 15548 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15549 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15550 } 15551