1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Expr constant evaluator. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/RecordLayout.h" 18 #include "clang/AST/StmtVisitor.h" 19 #include "clang/AST/TypeLoc.h" 20 #include "clang/AST/ASTDiagnostic.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/Basic/Builtins.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "llvm/ADT/SmallString.h" 25 #include <cstring> 26 27 using namespace clang; 28 using llvm::APSInt; 29 using llvm::APFloat; 30 31 /// EvalInfo - This is a private struct used by the evaluator to capture 32 /// information about a subexpression as it is folded. It retains information 33 /// about the AST context, but also maintains information about the folded 34 /// expression. 35 /// 36 /// If an expression could be evaluated, it is still possible it is not a C 37 /// "integer constant expression" or constant expression. If not, this struct 38 /// captures information about how and why not. 39 /// 40 /// One bit of information passed *into* the request for constant folding 41 /// indicates whether the subexpression is "evaluated" or not according to C 42 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 43 /// evaluate the expression regardless of what the RHS is, but C only allows 44 /// certain things in certain situations. 45 namespace { 46 struct LValue; 47 struct CallStackFrame; 48 struct EvalInfo; 49 50 QualType getType(APValue::LValueBase B) { 51 if (!B) return QualType(); 52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) 53 return D->getType(); 54 return B.get<const Expr*>()->getType(); 55 } 56 57 /// Get an LValue path entry, which is known to not be an array index, as a 58 /// field declaration. 59 const FieldDecl *getAsField(APValue::LValuePathEntry E) { 60 APValue::BaseOrMemberType Value; 61 Value.setFromOpaqueValue(E.BaseOrMember); 62 return dyn_cast<FieldDecl>(Value.getPointer()); 63 } 64 /// Get an LValue path entry, which is known to not be an array index, as a 65 /// base class declaration. 66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 67 APValue::BaseOrMemberType Value; 68 Value.setFromOpaqueValue(E.BaseOrMember); 69 return dyn_cast<CXXRecordDecl>(Value.getPointer()); 70 } 71 /// Determine whether this LValue path entry for a base class names a virtual 72 /// base class. 73 bool isVirtualBaseClass(APValue::LValuePathEntry E) { 74 APValue::BaseOrMemberType Value; 75 Value.setFromOpaqueValue(E.BaseOrMember); 76 return Value.getInt(); 77 } 78 79 /// Determine whether the described subobject is an array element. 80 static bool SubobjectIsArrayElement(QualType Base, 81 ArrayRef<APValue::LValuePathEntry> Path) { 82 bool IsArrayElement = false; 83 const Type *T = Base.getTypePtr(); 84 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 85 IsArrayElement = T && T->isArrayType(); 86 if (IsArrayElement) 87 T = T->getBaseElementTypeUnsafe(); 88 else if (const FieldDecl *FD = getAsField(Path[I])) 89 T = FD->getType().getTypePtr(); 90 else 91 // Path[I] describes a base class. 92 T = 0; 93 } 94 return IsArrayElement; 95 } 96 97 /// A path from a glvalue to a subobject of that glvalue. 98 struct SubobjectDesignator { 99 /// True if the subobject was named in a manner not supported by C++11. Such 100 /// lvalues can still be folded, but they are not core constant expressions 101 /// and we cannot perform lvalue-to-rvalue conversions on them. 102 bool Invalid : 1; 103 104 /// Whether this designates an array element. 105 bool ArrayElement : 1; 106 107 /// Whether this designates 'one past the end' of the current subobject. 108 bool OnePastTheEnd : 1; 109 110 typedef APValue::LValuePathEntry PathEntry; 111 112 /// The entries on the path from the glvalue to the designated subobject. 113 SmallVector<PathEntry, 8> Entries; 114 115 SubobjectDesignator() : 116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {} 117 118 SubobjectDesignator(const APValue &V) : 119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false), 120 OnePastTheEnd(false) { 121 if (!Invalid) { 122 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 124 if (V.getLValueBase()) 125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()), 126 V.getLValuePath()); 127 else 128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path"); 129 OnePastTheEnd = V.isLValueOnePastTheEnd(); 130 } 131 } 132 133 void setInvalid() { 134 Invalid = true; 135 Entries.clear(); 136 } 137 /// Update this designator to refer to the given element within this array. 138 void addIndex(uint64_t N) { 139 if (Invalid) return; 140 if (OnePastTheEnd) { 141 setInvalid(); 142 return; 143 } 144 PathEntry Entry; 145 Entry.ArrayIndex = N; 146 Entries.push_back(Entry); 147 ArrayElement = true; 148 } 149 /// Update this designator to refer to the given base or member of this 150 /// object. 151 void addDecl(const Decl *D, bool Virtual = false) { 152 if (Invalid) return; 153 if (OnePastTheEnd) { 154 setInvalid(); 155 return; 156 } 157 PathEntry Entry; 158 APValue::BaseOrMemberType Value(D, Virtual); 159 Entry.BaseOrMember = Value.getOpaqueValue(); 160 Entries.push_back(Entry); 161 ArrayElement = false; 162 } 163 /// Add N to the address of this subobject. 164 void adjustIndex(uint64_t N) { 165 if (Invalid) return; 166 if (ArrayElement) { 167 // FIXME: Make sure the index stays within bounds, or one past the end. 168 Entries.back().ArrayIndex += N; 169 return; 170 } 171 if (OnePastTheEnd && N == (uint64_t)-1) 172 OnePastTheEnd = false; 173 else if (!OnePastTheEnd && N == 1) 174 OnePastTheEnd = true; 175 else if (N != 0) 176 setInvalid(); 177 } 178 }; 179 180 /// A core constant value. This can be the value of any constant expression, 181 /// or a pointer or reference to a non-static object or function parameter. 182 /// 183 /// For an LValue, the base and offset are stored in the APValue subobject, 184 /// but the other information is stored in the SubobjectDesignator. For all 185 /// other value kinds, the value is stored directly in the APValue subobject. 186 class CCValue : public APValue { 187 typedef llvm::APSInt APSInt; 188 typedef llvm::APFloat APFloat; 189 /// If the value is a reference or pointer into a parameter or temporary, 190 /// this is the corresponding call stack frame. 191 CallStackFrame *CallFrame; 192 /// If the value is a reference or pointer, this is a description of how the 193 /// subobject was specified. 194 SubobjectDesignator Designator; 195 public: 196 struct GlobalValue {}; 197 198 CCValue() {} 199 explicit CCValue(const APSInt &I) : APValue(I) {} 200 explicit CCValue(const APFloat &F) : APValue(F) {} 201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {} 202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {} 203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {} 204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {} 205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F, 206 const SubobjectDesignator &D) : 207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {} 208 CCValue(const APValue &V, GlobalValue) : 209 APValue(V), CallFrame(0), Designator(V) {} 210 CCValue(const ValueDecl *D, bool IsDerivedMember, 211 ArrayRef<const CXXRecordDecl*> Path) : 212 APValue(D, IsDerivedMember, Path) {} 213 214 CallStackFrame *getLValueFrame() const { 215 assert(getKind() == LValue); 216 return CallFrame; 217 } 218 SubobjectDesignator &getLValueDesignator() { 219 assert(getKind() == LValue); 220 return Designator; 221 } 222 const SubobjectDesignator &getLValueDesignator() const { 223 return const_cast<CCValue*>(this)->getLValueDesignator(); 224 } 225 }; 226 227 /// A stack frame in the constexpr call stack. 228 struct CallStackFrame { 229 EvalInfo &Info; 230 231 /// Parent - The caller of this stack frame. 232 CallStackFrame *Caller; 233 234 /// This - The binding for the this pointer in this call, if any. 235 const LValue *This; 236 237 /// ParmBindings - Parameter bindings for this function call, indexed by 238 /// parameters' function scope indices. 239 const CCValue *Arguments; 240 241 typedef llvm::DenseMap<const Expr*, CCValue> MapTy; 242 typedef MapTy::const_iterator temp_iterator; 243 /// Temporaries - Temporary lvalues materialized within this stack frame. 244 MapTy Temporaries; 245 246 CallStackFrame(EvalInfo &Info, const LValue *This, 247 const CCValue *Arguments); 248 ~CallStackFrame(); 249 }; 250 251 struct EvalInfo { 252 const ASTContext &Ctx; 253 254 /// EvalStatus - Contains information about the evaluation. 255 Expr::EvalStatus &EvalStatus; 256 257 /// CurrentCall - The top of the constexpr call stack. 258 CallStackFrame *CurrentCall; 259 260 /// CallStackDepth - The number of calls in the call stack right now. 261 unsigned CallStackDepth; 262 263 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy; 264 /// OpaqueValues - Values used as the common expression in a 265 /// BinaryConditionalOperator. 266 MapTy OpaqueValues; 267 268 /// BottomFrame - The frame in which evaluation started. This must be 269 /// initialized last. 270 CallStackFrame BottomFrame; 271 272 /// EvaluatingDecl - This is the declaration whose initializer is being 273 /// evaluated, if any. 274 const VarDecl *EvaluatingDecl; 275 276 /// EvaluatingDeclValue - This is the value being constructed for the 277 /// declaration whose initializer is being evaluated, if any. 278 APValue *EvaluatingDeclValue; 279 280 281 EvalInfo(const ASTContext &C, Expr::EvalStatus &S) 282 : Ctx(C), EvalStatus(S), CurrentCall(0), CallStackDepth(0), 283 BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {} 284 285 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const { 286 MapTy::const_iterator i = OpaqueValues.find(e); 287 if (i == OpaqueValues.end()) return 0; 288 return &i->second; 289 } 290 291 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) { 292 EvaluatingDecl = VD; 293 EvaluatingDeclValue = &Value; 294 } 295 296 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); } 297 298 bool atCallLimit() const { 299 return CallStackDepth > getLangOpts().ConstexprCallDepth; 300 } 301 }; 302 303 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This, 304 const CCValue *Arguments) 305 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) { 306 Info.CurrentCall = this; 307 ++Info.CallStackDepth; 308 } 309 310 CallStackFrame::~CallStackFrame() { 311 assert(Info.CurrentCall == this && "calls retired out of order"); 312 --Info.CallStackDepth; 313 Info.CurrentCall = Caller; 314 } 315 316 struct ComplexValue { 317 private: 318 bool IsInt; 319 320 public: 321 APSInt IntReal, IntImag; 322 APFloat FloatReal, FloatImag; 323 324 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {} 325 326 void makeComplexFloat() { IsInt = false; } 327 bool isComplexFloat() const { return !IsInt; } 328 APFloat &getComplexFloatReal() { return FloatReal; } 329 APFloat &getComplexFloatImag() { return FloatImag; } 330 331 void makeComplexInt() { IsInt = true; } 332 bool isComplexInt() const { return IsInt; } 333 APSInt &getComplexIntReal() { return IntReal; } 334 APSInt &getComplexIntImag() { return IntImag; } 335 336 void moveInto(CCValue &v) const { 337 if (isComplexFloat()) 338 v = CCValue(FloatReal, FloatImag); 339 else 340 v = CCValue(IntReal, IntImag); 341 } 342 void setFrom(const CCValue &v) { 343 assert(v.isComplexFloat() || v.isComplexInt()); 344 if (v.isComplexFloat()) { 345 makeComplexFloat(); 346 FloatReal = v.getComplexFloatReal(); 347 FloatImag = v.getComplexFloatImag(); 348 } else { 349 makeComplexInt(); 350 IntReal = v.getComplexIntReal(); 351 IntImag = v.getComplexIntImag(); 352 } 353 } 354 }; 355 356 struct LValue { 357 APValue::LValueBase Base; 358 CharUnits Offset; 359 CallStackFrame *Frame; 360 SubobjectDesignator Designator; 361 362 const APValue::LValueBase getLValueBase() const { return Base; } 363 CharUnits &getLValueOffset() { return Offset; } 364 const CharUnits &getLValueOffset() const { return Offset; } 365 CallStackFrame *getLValueFrame() const { return Frame; } 366 SubobjectDesignator &getLValueDesignator() { return Designator; } 367 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 368 369 void moveInto(CCValue &V) const { 370 V = CCValue(Base, Offset, Frame, Designator); 371 } 372 void setFrom(const CCValue &V) { 373 assert(V.isLValue()); 374 Base = V.getLValueBase(); 375 Offset = V.getLValueOffset(); 376 Frame = V.getLValueFrame(); 377 Designator = V.getLValueDesignator(); 378 } 379 380 void set(APValue::LValueBase B, CallStackFrame *F = 0) { 381 Base = B; 382 Offset = CharUnits::Zero(); 383 Frame = F; 384 Designator = SubobjectDesignator(); 385 } 386 }; 387 388 struct MemberPtr { 389 MemberPtr() {} 390 explicit MemberPtr(const ValueDecl *Decl) : 391 DeclAndIsDerivedMember(Decl, false), Path() {} 392 393 /// The member or (direct or indirect) field referred to by this member 394 /// pointer, or 0 if this is a null member pointer. 395 const ValueDecl *getDecl() const { 396 return DeclAndIsDerivedMember.getPointer(); 397 } 398 /// Is this actually a member of some type derived from the relevant class? 399 bool isDerivedMember() const { 400 return DeclAndIsDerivedMember.getInt(); 401 } 402 /// Get the class which the declaration actually lives in. 403 const CXXRecordDecl *getContainingRecord() const { 404 return cast<CXXRecordDecl>( 405 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 406 } 407 408 void moveInto(CCValue &V) const { 409 V = CCValue(getDecl(), isDerivedMember(), Path); 410 } 411 void setFrom(const CCValue &V) { 412 assert(V.isMemberPointer()); 413 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 414 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 415 Path.clear(); 416 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 417 Path.insert(Path.end(), P.begin(), P.end()); 418 } 419 420 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 421 /// whether the member is a member of some class derived from the class type 422 /// of the member pointer. 423 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 424 /// Path - The path of base/derived classes from the member declaration's 425 /// class (exclusive) to the class type of the member pointer (inclusive). 426 SmallVector<const CXXRecordDecl*, 4> Path; 427 428 /// Perform a cast towards the class of the Decl (either up or down the 429 /// hierarchy). 430 bool castBack(const CXXRecordDecl *Class) { 431 assert(!Path.empty()); 432 const CXXRecordDecl *Expected; 433 if (Path.size() >= 2) 434 Expected = Path[Path.size() - 2]; 435 else 436 Expected = getContainingRecord(); 437 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 438 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 439 // if B does not contain the original member and is not a base or 440 // derived class of the class containing the original member, the result 441 // of the cast is undefined. 442 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 443 // (D::*). We consider that to be a language defect. 444 return false; 445 } 446 Path.pop_back(); 447 return true; 448 } 449 /// Perform a base-to-derived member pointer cast. 450 bool castToDerived(const CXXRecordDecl *Derived) { 451 if (!getDecl()) 452 return true; 453 if (!isDerivedMember()) { 454 Path.push_back(Derived); 455 return true; 456 } 457 if (!castBack(Derived)) 458 return false; 459 if (Path.empty()) 460 DeclAndIsDerivedMember.setInt(false); 461 return true; 462 } 463 /// Perform a derived-to-base member pointer cast. 464 bool castToBase(const CXXRecordDecl *Base) { 465 if (!getDecl()) 466 return true; 467 if (Path.empty()) 468 DeclAndIsDerivedMember.setInt(true); 469 if (isDerivedMember()) { 470 Path.push_back(Base); 471 return true; 472 } 473 return castBack(Base); 474 } 475 }; 476 } 477 478 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E); 479 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info, 480 const LValue &This, const Expr *E); 481 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info); 482 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info); 483 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 484 EvalInfo &Info); 485 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 486 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 487 static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result, 488 EvalInfo &Info); 489 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 490 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 491 492 //===----------------------------------------------------------------------===// 493 // Misc utilities 494 //===----------------------------------------------------------------------===// 495 496 /// Should this call expression be treated as a string literal? 497 static bool IsStringLiteralCall(const CallExpr *E) { 498 unsigned Builtin = E->isBuiltinCall(); 499 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 500 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 501 } 502 503 static bool IsGlobalLValue(APValue::LValueBase B) { 504 // C++11 [expr.const]p3 An address constant expression is a prvalue core 505 // constant expression of pointer type that evaluates to... 506 507 // ... a null pointer value, or a prvalue core constant expression of type 508 // std::nullptr_t. 509 if (!B) return true; 510 511 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 512 // ... the address of an object with static storage duration, 513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 514 return VD->hasGlobalStorage(); 515 // ... the address of a function, 516 return isa<FunctionDecl>(D); 517 } 518 519 const Expr *E = B.get<const Expr*>(); 520 switch (E->getStmtClass()) { 521 default: 522 return false; 523 case Expr::CompoundLiteralExprClass: 524 return cast<CompoundLiteralExpr>(E)->isFileScope(); 525 // A string literal has static storage duration. 526 case Expr::StringLiteralClass: 527 case Expr::PredefinedExprClass: 528 case Expr::ObjCStringLiteralClass: 529 case Expr::ObjCEncodeExprClass: 530 return true; 531 case Expr::CallExprClass: 532 return IsStringLiteralCall(cast<CallExpr>(E)); 533 // For GCC compatibility, &&label has static storage duration. 534 case Expr::AddrLabelExprClass: 535 return true; 536 // A Block literal expression may be used as the initialization value for 537 // Block variables at global or local static scope. 538 case Expr::BlockExprClass: 539 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 540 } 541 } 542 543 /// Check that this reference or pointer core constant expression is a valid 544 /// value for a constant expression. Type T should be either LValue or CCValue. 545 template<typename T> 546 static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) { 547 if (!IsGlobalLValue(LVal.getLValueBase())) 548 return false; 549 550 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 551 // A constant expression must refer to an object or be a null pointer. 552 if (Designator.Invalid || 553 (!LVal.getLValueBase() && !Designator.Entries.empty())) { 554 // FIXME: This is not a constant expression. 555 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(), 556 APValue::NoLValuePath()); 557 return true; 558 } 559 560 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(), 561 Designator.Entries, Designator.OnePastTheEnd); 562 return true; 563 } 564 565 /// Check that this core constant expression value is a valid value for a 566 /// constant expression, and if it is, produce the corresponding constant value. 567 static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) { 568 if (!CCValue.isLValue()) { 569 Value = CCValue; 570 return true; 571 } 572 return CheckLValueConstantExpression(CCValue, Value); 573 } 574 575 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 576 return LVal.Base.dyn_cast<const ValueDecl*>(); 577 } 578 579 static bool IsLiteralLValue(const LValue &Value) { 580 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame; 581 } 582 583 static bool IsWeakLValue(const LValue &Value) { 584 const ValueDecl *Decl = GetLValueBaseDecl(Value); 585 return Decl && Decl->isWeak(); 586 } 587 588 static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) { 589 // A null base expression indicates a null pointer. These are always 590 // evaluatable, and they are false unless the offset is zero. 591 if (!Value.getLValueBase()) { 592 Result = !Value.getLValueOffset().isZero(); 593 return true; 594 } 595 596 // Require the base expression to be a global l-value. 597 // FIXME: C++11 requires such conversions. Remove this check. 598 if (!IsGlobalLValue(Value.getLValueBase())) return false; 599 600 // We have a non-null base. These are generally known to be true, but if it's 601 // a weak declaration it can be null at runtime. 602 Result = true; 603 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 604 return !Decl || !Decl->isWeak(); 605 } 606 607 static bool HandleConversionToBool(const CCValue &Val, bool &Result) { 608 switch (Val.getKind()) { 609 case APValue::Uninitialized: 610 return false; 611 case APValue::Int: 612 Result = Val.getInt().getBoolValue(); 613 return true; 614 case APValue::Float: 615 Result = !Val.getFloat().isZero(); 616 return true; 617 case APValue::ComplexInt: 618 Result = Val.getComplexIntReal().getBoolValue() || 619 Val.getComplexIntImag().getBoolValue(); 620 return true; 621 case APValue::ComplexFloat: 622 Result = !Val.getComplexFloatReal().isZero() || 623 !Val.getComplexFloatImag().isZero(); 624 return true; 625 case APValue::LValue: 626 return EvalPointerValueAsBool(Val, Result); 627 case APValue::MemberPointer: 628 Result = Val.getMemberPointerDecl(); 629 return true; 630 case APValue::Vector: 631 case APValue::Array: 632 case APValue::Struct: 633 case APValue::Union: 634 return false; 635 } 636 637 llvm_unreachable("unknown APValue kind"); 638 } 639 640 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 641 EvalInfo &Info) { 642 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 643 CCValue Val; 644 if (!Evaluate(Val, Info, E)) 645 return false; 646 return HandleConversionToBool(Val, Result); 647 } 648 649 static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType, 650 APFloat &Value, const ASTContext &Ctx) { 651 unsigned DestWidth = Ctx.getIntWidth(DestType); 652 // Determine whether we are converting to unsigned or signed. 653 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 654 655 // FIXME: Warning for overflow. 656 APSInt Result(DestWidth, !DestSigned); 657 bool ignored; 658 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored); 659 return Result; 660 } 661 662 static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType, 663 APFloat &Value, const ASTContext &Ctx) { 664 bool ignored; 665 APFloat Result = Value; 666 Result.convert(Ctx.getFloatTypeSemantics(DestType), 667 APFloat::rmNearestTiesToEven, &ignored); 668 return Result; 669 } 670 671 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, 672 APSInt &Value, const ASTContext &Ctx) { 673 unsigned DestWidth = Ctx.getIntWidth(DestType); 674 APSInt Result = Value; 675 // Figure out if this is a truncate, extend or noop cast. 676 // If the input is signed, do a sign extend, noop, or truncate. 677 Result = Result.extOrTrunc(DestWidth); 678 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 679 return Result; 680 } 681 682 static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType, 683 APSInt &Value, const ASTContext &Ctx) { 684 685 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1); 686 Result.convertFromAPInt(Value, Value.isSigned(), 687 APFloat::rmNearestTiesToEven); 688 return Result; 689 } 690 691 static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal, 692 const CXXRecordDecl *&MostDerivedType, 693 unsigned &MostDerivedPathLength, 694 bool &MostDerivedIsArrayElement) { 695 const SubobjectDesignator &D = LVal.Designator; 696 if (D.Invalid || !LVal.Base) 697 return false; 698 699 const Type *T = getType(LVal.Base).getTypePtr(); 700 701 // Find path prefix which leads to the most-derived subobject. 702 MostDerivedType = T->getAsCXXRecordDecl(); 703 MostDerivedPathLength = 0; 704 MostDerivedIsArrayElement = false; 705 706 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) { 707 bool IsArray = T && T->isArrayType(); 708 if (IsArray) 709 T = T->getBaseElementTypeUnsafe(); 710 else if (const FieldDecl *FD = getAsField(D.Entries[I])) 711 T = FD->getType().getTypePtr(); 712 else 713 T = 0; 714 715 if (T) { 716 MostDerivedType = T->getAsCXXRecordDecl(); 717 MostDerivedPathLength = I + 1; 718 MostDerivedIsArrayElement = IsArray; 719 } 720 } 721 722 // (B*)&d + 1 has no most-derived object. 723 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size()) 724 return false; 725 726 return MostDerivedType != 0; 727 } 728 729 static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result, 730 const RecordDecl *TruncatedType, 731 unsigned TruncatedElements, 732 bool IsArrayElement) { 733 SubobjectDesignator &D = Result.Designator; 734 const RecordDecl *RD = TruncatedType; 735 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 736 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 737 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 738 if (isVirtualBaseClass(D.Entries[I])) 739 Result.Offset -= Layout.getVBaseClassOffset(Base); 740 else 741 Result.Offset -= Layout.getBaseClassOffset(Base); 742 RD = Base; 743 } 744 D.Entries.resize(TruncatedElements); 745 D.ArrayElement = IsArrayElement; 746 } 747 748 /// If the given LValue refers to a base subobject of some object, find the most 749 /// derived object and the corresponding complete record type. This is necessary 750 /// in order to find the offset of a virtual base class. 751 static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result, 752 const CXXRecordDecl *&MostDerivedType) { 753 unsigned MostDerivedPathLength; 754 bool MostDerivedIsArrayElement; 755 if (!FindMostDerivedObject(Info, Result, MostDerivedType, 756 MostDerivedPathLength, MostDerivedIsArrayElement)) 757 return false; 758 759 // Remove the trailing base class path entries and their offsets. 760 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength, 761 MostDerivedIsArrayElement); 762 return true; 763 } 764 765 static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj, 766 const CXXRecordDecl *Derived, 767 const CXXRecordDecl *Base, 768 const ASTRecordLayout *RL = 0) { 769 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived); 770 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 771 Obj.Designator.addDecl(Base, /*Virtual*/ false); 772 } 773 774 static bool HandleLValueBase(EvalInfo &Info, LValue &Obj, 775 const CXXRecordDecl *DerivedDecl, 776 const CXXBaseSpecifier *Base) { 777 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 778 779 if (!Base->isVirtual()) { 780 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl); 781 return true; 782 } 783 784 // Extract most-derived object and corresponding type. 785 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl)) 786 return false; 787 788 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 789 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 790 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true); 791 return true; 792 } 793 794 /// Update LVal to refer to the given field, which must be a member of the type 795 /// currently described by LVal. 796 static void HandleLValueMember(EvalInfo &Info, LValue &LVal, 797 const FieldDecl *FD, 798 const ASTRecordLayout *RL = 0) { 799 if (!RL) 800 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 801 802 unsigned I = FD->getFieldIndex(); 803 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)); 804 LVal.Designator.addDecl(FD); 805 } 806 807 /// Get the size of the given type in char units. 808 static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) { 809 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 810 // extension. 811 if (Type->isVoidType() || Type->isFunctionType()) { 812 Size = CharUnits::One(); 813 return true; 814 } 815 816 if (!Type->isConstantSizeType()) { 817 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 818 return false; 819 } 820 821 Size = Info.Ctx.getTypeSizeInChars(Type); 822 return true; 823 } 824 825 /// Update a pointer value to model pointer arithmetic. 826 /// \param Info - Information about the ongoing evaluation. 827 /// \param LVal - The pointer value to be updated. 828 /// \param EltTy - The pointee type represented by LVal. 829 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 830 static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal, 831 QualType EltTy, int64_t Adjustment) { 832 CharUnits SizeOfPointee; 833 if (!HandleSizeof(Info, EltTy, SizeOfPointee)) 834 return false; 835 836 // Compute the new offset in the appropriate width. 837 LVal.Offset += Adjustment * SizeOfPointee; 838 LVal.Designator.adjustIndex(Adjustment); 839 return true; 840 } 841 842 /// Try to evaluate the initializer for a variable declaration. 843 static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD, 844 CallStackFrame *Frame, CCValue &Result) { 845 // If this is a parameter to an active constexpr function call, perform 846 // argument substitution. 847 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 848 if (!Frame || !Frame->Arguments) 849 return false; 850 Result = Frame->Arguments[PVD->getFunctionScopeIndex()]; 851 return true; 852 } 853 854 // If we're currently evaluating the initializer of this declaration, use that 855 // in-flight value. 856 if (Info.EvaluatingDecl == VD) { 857 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue()); 858 return !Result.isUninit(); 859 } 860 861 // Never evaluate the initializer of a weak variable. We can't be sure that 862 // this is the definition which will be used. 863 if (VD->isWeak()) 864 return false; 865 866 const Expr *Init = VD->getAnyInitializer(); 867 if (!Init || Init->isValueDependent()) 868 return false; 869 870 if (APValue *V = VD->getEvaluatedValue()) { 871 Result = CCValue(*V, CCValue::GlobalValue()); 872 return !Result.isUninit(); 873 } 874 875 if (VD->isEvaluatingValue()) 876 return false; 877 878 VD->setEvaluatingValue(); 879 880 Expr::EvalStatus EStatus; 881 EvalInfo InitInfo(Info.Ctx, EStatus); 882 APValue EvalResult; 883 InitInfo.setEvaluatingDecl(VD, EvalResult); 884 LValue LVal; 885 LVal.set(VD); 886 // FIXME: The caller will need to know whether the value was a constant 887 // expression. If not, we should propagate up a diagnostic. 888 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) { 889 // FIXME: If the evaluation failure was not permanent (for instance, if we 890 // hit a variable with no declaration yet, or a constexpr function with no 891 // definition yet), the standard is unclear as to how we should behave. 892 // 893 // Either the initializer should be evaluated when the variable is defined, 894 // or a failed evaluation of the initializer should be reattempted each time 895 // it is used. 896 VD->setEvaluatedValue(APValue()); 897 return false; 898 } 899 900 VD->setEvaluatedValue(EvalResult); 901 Result = CCValue(EvalResult, CCValue::GlobalValue()); 902 return true; 903 } 904 905 static bool IsConstNonVolatile(QualType T) { 906 Qualifiers Quals = T.getQualifiers(); 907 return Quals.hasConst() && !Quals.hasVolatile(); 908 } 909 910 /// Get the base index of the given base class within an APValue representing 911 /// the given derived class. 912 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 913 const CXXRecordDecl *Base) { 914 Base = Base->getCanonicalDecl(); 915 unsigned Index = 0; 916 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 917 E = Derived->bases_end(); I != E; ++I, ++Index) { 918 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 919 return Index; 920 } 921 922 llvm_unreachable("base class missing from derived class's bases list"); 923 } 924 925 /// Extract the designated sub-object of an rvalue. 926 static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType, 927 const SubobjectDesignator &Sub, QualType SubType) { 928 if (Sub.Invalid || Sub.OnePastTheEnd) 929 return false; 930 if (Sub.Entries.empty()) 931 return true; 932 933 assert(!Obj.isLValue() && "extracting subobject of lvalue"); 934 const APValue *O = &Obj; 935 // Walk the designator's path to find the subobject. 936 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) { 937 if (ObjType->isArrayType()) { 938 // Next subobject is an array element. 939 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 940 if (!CAT) 941 return false; 942 uint64_t Index = Sub.Entries[I].ArrayIndex; 943 if (CAT->getSize().ule(Index)) 944 return false; 945 if (O->getArrayInitializedElts() > Index) 946 O = &O->getArrayInitializedElt(Index); 947 else 948 O = &O->getArrayFiller(); 949 ObjType = CAT->getElementType(); 950 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 951 // Next subobject is a class, struct or union field. 952 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 953 if (RD->isUnion()) { 954 const FieldDecl *UnionField = O->getUnionField(); 955 if (!UnionField || 956 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) 957 return false; 958 O = &O->getUnionValue(); 959 } else 960 O = &O->getStructField(Field->getFieldIndex()); 961 ObjType = Field->getType(); 962 } else { 963 // Next subobject is a base class. 964 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 965 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 966 O = &O->getStructBase(getBaseIndex(Derived, Base)); 967 ObjType = Info.Ctx.getRecordType(Base); 968 } 969 970 if (O->isUninit()) 971 return false; 972 } 973 974 Obj = CCValue(*O, CCValue::GlobalValue()); 975 return true; 976 } 977 978 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on 979 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions 980 /// for looking up the glvalue referred to by an entity of reference type. 981 /// 982 /// \param Info - Information about the ongoing evaluation. 983 /// \param Type - The type we expect this conversion to produce. 984 /// \param LVal - The glvalue on which we are attempting to perform this action. 985 /// \param RVal - The produced value will be placed here. 986 static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type, 987 const LValue &LVal, CCValue &RVal) { 988 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 989 CallStackFrame *Frame = LVal.Frame; 990 991 // FIXME: Indirection through a null pointer deserves a diagnostic. 992 if (!LVal.Base) 993 return false; 994 995 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 996 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 997 // In C++11, constexpr, non-volatile variables initialized with constant 998 // expressions are constant expressions too. Inside constexpr functions, 999 // parameters are constant expressions even if they're non-const. 1000 // In C, such things can also be folded, although they are not ICEs. 1001 // 1002 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal 1003 // interpretation of C++11 suggests that volatile parameters are OK if 1004 // they're never read (there's no prohibition against constructing volatile 1005 // objects in constant expressions), but lvalue-to-rvalue conversions on 1006 // them are not permitted. 1007 const VarDecl *VD = dyn_cast<VarDecl>(D); 1008 if (!VD || VD->isInvalidDecl()) 1009 return false; 1010 QualType VT = VD->getType(); 1011 if (!isa<ParmVarDecl>(VD)) { 1012 if (!IsConstNonVolatile(VT)) 1013 return false; 1014 // FIXME: Allow folding of values of any literal type in all languages. 1015 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() && 1016 !VD->isConstexpr()) 1017 return false; 1018 } 1019 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal)) 1020 return false; 1021 1022 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue()) 1023 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type); 1024 1025 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue 1026 // conversion. This happens when the declaration and the lvalue should be 1027 // considered synonymous, for instance when initializing an array of char 1028 // from a string literal. Continue as if the initializer lvalue was the 1029 // value we were originally given. 1030 assert(RVal.getLValueOffset().isZero() && 1031 "offset for lvalue init of non-reference"); 1032 Base = RVal.getLValueBase().get<const Expr*>(); 1033 Frame = RVal.getLValueFrame(); 1034 } 1035 1036 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant 1037 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) { 1038 const SubobjectDesignator &Designator = LVal.Designator; 1039 if (Designator.Invalid || Designator.Entries.size() != 1) 1040 return false; 1041 1042 assert(Type->isIntegerType() && "string element not integer type"); 1043 uint64_t Index = Designator.Entries[0].ArrayIndex; 1044 if (Index > S->getLength()) 1045 return false; 1046 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 1047 Type->isUnsignedIntegerType()); 1048 if (Index < S->getLength()) 1049 Value = S->getCodeUnit(Index); 1050 RVal = CCValue(Value); 1051 return true; 1052 } 1053 1054 if (Frame) { 1055 // If this is a temporary expression with a nontrivial initializer, grab the 1056 // value from the relevant stack frame. 1057 RVal = Frame->Temporaries[Base]; 1058 } else if (const CompoundLiteralExpr *CLE 1059 = dyn_cast<CompoundLiteralExpr>(Base)) { 1060 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 1061 // initializer until now for such expressions. Such an expression can't be 1062 // an ICE in C, so this only matters for fold. 1063 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 1064 if (!Evaluate(RVal, Info, CLE->getInitializer())) 1065 return false; 1066 } else 1067 return false; 1068 1069 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type); 1070 } 1071 1072 /// Build an lvalue for the object argument of a member function call. 1073 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 1074 LValue &This) { 1075 if (Object->getType()->isPointerType()) 1076 return EvaluatePointer(Object, This, Info); 1077 1078 if (Object->isGLValue()) 1079 return EvaluateLValue(Object, This, Info); 1080 1081 if (Object->getType()->isLiteralType()) 1082 return EvaluateTemporary(Object, This, Info); 1083 1084 return false; 1085 } 1086 1087 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 1088 /// lvalue referring to the result. 1089 /// 1090 /// \param Info - Information about the ongoing evaluation. 1091 /// \param BO - The member pointer access operation. 1092 /// \param LV - Filled in with a reference to the resulting object. 1093 /// \param IncludeMember - Specifies whether the member itself is included in 1094 /// the resulting LValue subobject designator. This is not possible when 1095 /// creating a bound member function. 1096 /// \return The field or method declaration to which the member pointer refers, 1097 /// or 0 if evaluation fails. 1098 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 1099 const BinaryOperator *BO, 1100 LValue &LV, 1101 bool IncludeMember = true) { 1102 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 1103 1104 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) 1105 return 0; 1106 1107 MemberPtr MemPtr; 1108 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info)) 1109 return 0; 1110 1111 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 1112 // member value, the behavior is undefined. 1113 if (!MemPtr.getDecl()) 1114 return 0; 1115 1116 if (MemPtr.isDerivedMember()) { 1117 // This is a member of some derived class. Truncate LV appropriately. 1118 const CXXRecordDecl *MostDerivedType; 1119 unsigned MostDerivedPathLength; 1120 bool MostDerivedIsArrayElement; 1121 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength, 1122 MostDerivedIsArrayElement)) 1123 return 0; 1124 1125 // The end of the derived-to-base path for the base object must match the 1126 // derived-to-base path for the member pointer. 1127 if (MostDerivedPathLength + MemPtr.Path.size() > 1128 LV.Designator.Entries.size()) 1129 return 0; 1130 unsigned PathLengthToMember = 1131 LV.Designator.Entries.size() - MemPtr.Path.size(); 1132 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 1133 const CXXRecordDecl *LVDecl = getAsBaseClass( 1134 LV.Designator.Entries[PathLengthToMember + I]); 1135 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 1136 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) 1137 return 0; 1138 } 1139 1140 // Truncate the lvalue to the appropriate derived class. 1141 bool ResultIsArray = false; 1142 if (PathLengthToMember == MostDerivedPathLength) 1143 ResultIsArray = MostDerivedIsArrayElement; 1144 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(), 1145 PathLengthToMember, ResultIsArray); 1146 } else if (!MemPtr.Path.empty()) { 1147 // Extend the LValue path with the member pointer's path. 1148 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 1149 MemPtr.Path.size() + IncludeMember); 1150 1151 // Walk down to the appropriate base class. 1152 QualType LVType = BO->getLHS()->getType(); 1153 if (const PointerType *PT = LVType->getAs<PointerType>()) 1154 LVType = PT->getPointeeType(); 1155 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 1156 assert(RD && "member pointer access on non-class-type expression"); 1157 // The first class in the path is that of the lvalue. 1158 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 1159 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 1160 HandleLValueDirectBase(Info, LV, RD, Base); 1161 RD = Base; 1162 } 1163 // Finally cast to the class containing the member. 1164 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord()); 1165 } 1166 1167 // Add the member. Note that we cannot build bound member functions here. 1168 if (IncludeMember) { 1169 // FIXME: Deal with IndirectFieldDecls. 1170 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()); 1171 if (!FD) return 0; 1172 HandleLValueMember(Info, LV, FD); 1173 } 1174 1175 return MemPtr.getDecl(); 1176 } 1177 1178 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 1179 /// the provided lvalue, which currently refers to the base object. 1180 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 1181 LValue &Result) { 1182 const CXXRecordDecl *MostDerivedType; 1183 unsigned MostDerivedPathLength; 1184 bool MostDerivedIsArrayElement; 1185 1186 // Check this cast doesn't take us outside the object. 1187 if (!FindMostDerivedObject(Info, Result, MostDerivedType, 1188 MostDerivedPathLength, 1189 MostDerivedIsArrayElement)) 1190 return false; 1191 SubobjectDesignator &D = Result.Designator; 1192 if (MostDerivedPathLength + E->path_size() > D.Entries.size()) 1193 return false; 1194 1195 // Check the type of the final cast. We don't need to check the path, 1196 // since a cast can only be formed if the path is unique. 1197 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 1198 bool ResultIsArray = false; 1199 QualType TargetQT = E->getType(); 1200 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 1201 TargetQT = PT->getPointeeType(); 1202 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 1203 const CXXRecordDecl *FinalType; 1204 if (NewEntriesSize == MostDerivedPathLength) { 1205 ResultIsArray = MostDerivedIsArrayElement; 1206 FinalType = MostDerivedType; 1207 } else 1208 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 1209 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) 1210 return false; 1211 1212 // Truncate the lvalue to the appropriate derived class. 1213 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize, 1214 ResultIsArray); 1215 return true; 1216 } 1217 1218 namespace { 1219 enum EvalStmtResult { 1220 /// Evaluation failed. 1221 ESR_Failed, 1222 /// Hit a 'return' statement. 1223 ESR_Returned, 1224 /// Evaluation succeeded. 1225 ESR_Succeeded 1226 }; 1227 } 1228 1229 // Evaluate a statement. 1230 static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info, 1231 const Stmt *S) { 1232 switch (S->getStmtClass()) { 1233 default: 1234 return ESR_Failed; 1235 1236 case Stmt::NullStmtClass: 1237 case Stmt::DeclStmtClass: 1238 return ESR_Succeeded; 1239 1240 case Stmt::ReturnStmtClass: 1241 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue())) 1242 return ESR_Returned; 1243 return ESR_Failed; 1244 1245 case Stmt::CompoundStmtClass: { 1246 const CompoundStmt *CS = cast<CompoundStmt>(S); 1247 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 1248 BE = CS->body_end(); BI != BE; ++BI) { 1249 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 1250 if (ESR != ESR_Succeeded) 1251 return ESR; 1252 } 1253 return ESR_Succeeded; 1254 } 1255 } 1256 } 1257 1258 namespace { 1259 typedef SmallVector<CCValue, 8> ArgVector; 1260 } 1261 1262 /// EvaluateArgs - Evaluate the arguments to a function call. 1263 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 1264 EvalInfo &Info) { 1265 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 1266 I != E; ++I) 1267 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) 1268 return false; 1269 return true; 1270 } 1271 1272 /// Evaluate a function call. 1273 static bool HandleFunctionCall(const LValue *This, ArrayRef<const Expr*> Args, 1274 const Stmt *Body, EvalInfo &Info, 1275 CCValue &Result) { 1276 if (Info.atCallLimit()) 1277 return false; 1278 1279 ArgVector ArgValues(Args.size()); 1280 if (!EvaluateArgs(Args, ArgValues, Info)) 1281 return false; 1282 1283 CallStackFrame Frame(Info, This, ArgValues.data()); 1284 return EvaluateStmt(Result, Info, Body) == ESR_Returned; 1285 } 1286 1287 /// Evaluate a constructor call. 1288 static bool HandleConstructorCall(const LValue &This, 1289 ArrayRef<const Expr*> Args, 1290 const CXXConstructorDecl *Definition, 1291 EvalInfo &Info, 1292 APValue &Result) { 1293 if (Info.atCallLimit()) 1294 return false; 1295 1296 ArgVector ArgValues(Args.size()); 1297 if (!EvaluateArgs(Args, ArgValues, Info)) 1298 return false; 1299 1300 CallStackFrame Frame(Info, &This, ArgValues.data()); 1301 1302 // If it's a delegating constructor, just delegate. 1303 if (Definition->isDelegatingConstructor()) { 1304 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 1305 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit()); 1306 } 1307 1308 // Reserve space for the struct members. 1309 const CXXRecordDecl *RD = Definition->getParent(); 1310 if (!RD->isUnion()) 1311 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 1312 std::distance(RD->field_begin(), RD->field_end())); 1313 1314 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 1315 1316 unsigned BasesSeen = 0; 1317 #ifndef NDEBUG 1318 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 1319 #endif 1320 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(), 1321 E = Definition->init_end(); I != E; ++I) { 1322 if ((*I)->isBaseInitializer()) { 1323 QualType BaseType((*I)->getBaseClass(), 0); 1324 #ifndef NDEBUG 1325 // Non-virtual base classes are initialized in the order in the class 1326 // definition. We cannot have a virtual base class for a literal type. 1327 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 1328 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 1329 "base class initializers not in expected order"); 1330 ++BaseIt; 1331 #endif 1332 LValue Subobject = This; 1333 HandleLValueDirectBase(Info, Subobject, RD, 1334 BaseType->getAsCXXRecordDecl(), &Layout); 1335 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info, 1336 Subobject, (*I)->getInit())) 1337 return false; 1338 } else if (FieldDecl *FD = (*I)->getMember()) { 1339 LValue Subobject = This; 1340 HandleLValueMember(Info, Subobject, FD, &Layout); 1341 if (RD->isUnion()) { 1342 Result = APValue(FD); 1343 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, 1344 Subobject, (*I)->getInit())) 1345 return false; 1346 } else if (!EvaluateConstantExpression( 1347 Result.getStructField(FD->getFieldIndex()), 1348 Info, Subobject, (*I)->getInit())) 1349 return false; 1350 } else { 1351 // FIXME: handle indirect field initializers 1352 return false; 1353 } 1354 } 1355 1356 return true; 1357 } 1358 1359 namespace { 1360 class HasSideEffect 1361 : public ConstStmtVisitor<HasSideEffect, bool> { 1362 const ASTContext &Ctx; 1363 public: 1364 1365 HasSideEffect(const ASTContext &C) : Ctx(C) {} 1366 1367 // Unhandled nodes conservatively default to having side effects. 1368 bool VisitStmt(const Stmt *S) { 1369 return true; 1370 } 1371 1372 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); } 1373 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) { 1374 return Visit(E->getResultExpr()); 1375 } 1376 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1377 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1378 return true; 1379 return false; 1380 } 1381 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) { 1382 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1383 return true; 1384 return false; 1385 } 1386 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) { 1387 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1388 return true; 1389 return false; 1390 } 1391 1392 // We don't want to evaluate BlockExprs multiple times, as they generate 1393 // a ton of code. 1394 bool VisitBlockExpr(const BlockExpr *E) { return true; } 1395 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; } 1396 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) 1397 { return Visit(E->getInitializer()); } 1398 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); } 1399 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; } 1400 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; } 1401 bool VisitStringLiteral(const StringLiteral *E) { return false; } 1402 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; } 1403 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) 1404 { return false; } 1405 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E) 1406 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 1407 bool VisitChooseExpr(const ChooseExpr *E) 1408 { return Visit(E->getChosenSubExpr(Ctx)); } 1409 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); } 1410 bool VisitBinAssign(const BinaryOperator *E) { return true; } 1411 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; } 1412 bool VisitBinaryOperator(const BinaryOperator *E) 1413 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 1414 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; } 1415 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; } 1416 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; } 1417 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; } 1418 bool VisitUnaryDeref(const UnaryOperator *E) { 1419 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1420 return true; 1421 return Visit(E->getSubExpr()); 1422 } 1423 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); } 1424 1425 // Has side effects if any element does. 1426 bool VisitInitListExpr(const InitListExpr *E) { 1427 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i) 1428 if (Visit(E->getInit(i))) return true; 1429 if (const Expr *filler = E->getArrayFiller()) 1430 return Visit(filler); 1431 return false; 1432 } 1433 1434 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; } 1435 }; 1436 1437 class OpaqueValueEvaluation { 1438 EvalInfo &info; 1439 OpaqueValueExpr *opaqueValue; 1440 1441 public: 1442 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue, 1443 Expr *value) 1444 : info(info), opaqueValue(opaqueValue) { 1445 1446 // If evaluation fails, fail immediately. 1447 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) { 1448 this->opaqueValue = 0; 1449 return; 1450 } 1451 } 1452 1453 bool hasError() const { return opaqueValue == 0; } 1454 1455 ~OpaqueValueEvaluation() { 1456 // FIXME: This will not work for recursive constexpr functions using opaque 1457 // values. Restore the former value. 1458 if (opaqueValue) info.OpaqueValues.erase(opaqueValue); 1459 } 1460 }; 1461 1462 } // end anonymous namespace 1463 1464 //===----------------------------------------------------------------------===// 1465 // Generic Evaluation 1466 //===----------------------------------------------------------------------===// 1467 namespace { 1468 1469 template <class Derived, typename RetTy=void> 1470 class ExprEvaluatorBase 1471 : public ConstStmtVisitor<Derived, RetTy> { 1472 private: 1473 RetTy DerivedSuccess(const CCValue &V, const Expr *E) { 1474 return static_cast<Derived*>(this)->Success(V, E); 1475 } 1476 RetTy DerivedError(const Expr *E) { 1477 return static_cast<Derived*>(this)->Error(E); 1478 } 1479 RetTy DerivedValueInitialization(const Expr *E) { 1480 return static_cast<Derived*>(this)->ValueInitialization(E); 1481 } 1482 1483 protected: 1484 EvalInfo &Info; 1485 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy; 1486 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 1487 1488 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); } 1489 1490 public: 1491 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 1492 1493 RetTy VisitStmt(const Stmt *) { 1494 llvm_unreachable("Expression evaluator should not be called on stmts"); 1495 } 1496 RetTy VisitExpr(const Expr *E) { 1497 return DerivedError(E); 1498 } 1499 1500 RetTy VisitParenExpr(const ParenExpr *E) 1501 { return StmtVisitorTy::Visit(E->getSubExpr()); } 1502 RetTy VisitUnaryExtension(const UnaryOperator *E) 1503 { return StmtVisitorTy::Visit(E->getSubExpr()); } 1504 RetTy VisitUnaryPlus(const UnaryOperator *E) 1505 { return StmtVisitorTy::Visit(E->getSubExpr()); } 1506 RetTy VisitChooseExpr(const ChooseExpr *E) 1507 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); } 1508 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E) 1509 { return StmtVisitorTy::Visit(E->getResultExpr()); } 1510 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 1511 { return StmtVisitorTy::Visit(E->getReplacement()); } 1512 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) 1513 { return StmtVisitorTy::Visit(E->getExpr()); } 1514 1515 RetTy VisitBinaryOperator(const BinaryOperator *E) { 1516 switch (E->getOpcode()) { 1517 default: 1518 return DerivedError(E); 1519 1520 case BO_Comma: 1521 VisitIgnoredValue(E->getLHS()); 1522 return StmtVisitorTy::Visit(E->getRHS()); 1523 1524 case BO_PtrMemD: 1525 case BO_PtrMemI: { 1526 LValue Obj; 1527 if (!HandleMemberPointerAccess(Info, E, Obj)) 1528 return false; 1529 CCValue Result; 1530 if (!HandleLValueToRValueConversion(Info, E->getType(), Obj, Result)) 1531 return false; 1532 return DerivedSuccess(Result, E); 1533 } 1534 } 1535 } 1536 1537 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 1538 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon()); 1539 if (opaque.hasError()) 1540 return DerivedError(E); 1541 1542 bool cond; 1543 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info)) 1544 return DerivedError(E); 1545 1546 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr()); 1547 } 1548 1549 RetTy VisitConditionalOperator(const ConditionalOperator *E) { 1550 bool BoolResult; 1551 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) 1552 return DerivedError(E); 1553 1554 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 1555 return StmtVisitorTy::Visit(EvalExpr); 1556 } 1557 1558 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 1559 const CCValue *Value = Info.getOpaqueValue(E); 1560 if (!Value) 1561 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr()) 1562 : DerivedError(E)); 1563 return DerivedSuccess(*Value, E); 1564 } 1565 1566 RetTy VisitCallExpr(const CallExpr *E) { 1567 const Expr *Callee = E->getCallee()->IgnoreParens(); 1568 QualType CalleeType = Callee->getType(); 1569 1570 const FunctionDecl *FD = 0; 1571 LValue *This = 0, ThisVal; 1572 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 1573 1574 // Extract function decl and 'this' pointer from the callee. 1575 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 1576 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 1577 // Explicit bound member calls, such as x.f() or p->g(); 1578 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 1579 return DerivedError(ME->getBase()); 1580 This = &ThisVal; 1581 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl()); 1582 if (!FD) 1583 return DerivedError(ME); 1584 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 1585 // Indirect bound member calls ('.*' or '->*'). 1586 const ValueDecl *Member = HandleMemberPointerAccess(Info, BE, ThisVal, 1587 false); 1588 This = &ThisVal; 1589 FD = dyn_cast_or_null<FunctionDecl>(Member); 1590 if (!FD) 1591 return DerivedError(Callee); 1592 } else 1593 return DerivedError(Callee); 1594 } else if (CalleeType->isFunctionPointerType()) { 1595 CCValue Call; 1596 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() || 1597 !Call.getLValueOffset().isZero()) 1598 return DerivedError(Callee); 1599 1600 FD = dyn_cast_or_null<FunctionDecl>( 1601 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 1602 if (!FD) 1603 return DerivedError(Callee); 1604 1605 // Overloaded operator calls to member functions are represented as normal 1606 // calls with '*this' as the first argument. 1607 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 1608 if (MD && !MD->isStatic()) { 1609 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 1610 return false; 1611 This = &ThisVal; 1612 Args = Args.slice(1); 1613 } 1614 1615 // Don't call function pointers which have been cast to some other type. 1616 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType())) 1617 return DerivedError(E); 1618 } else 1619 return DerivedError(E); 1620 1621 const FunctionDecl *Definition; 1622 Stmt *Body = FD->getBody(Definition); 1623 CCValue CCResult; 1624 APValue Result; 1625 1626 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() && 1627 HandleFunctionCall(This, Args, Body, Info, CCResult) && 1628 CheckConstantExpression(CCResult, Result)) 1629 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E); 1630 1631 return DerivedError(E); 1632 } 1633 1634 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 1635 return StmtVisitorTy::Visit(E->getInitializer()); 1636 } 1637 RetTy VisitInitListExpr(const InitListExpr *E) { 1638 if (Info.getLangOpts().CPlusPlus0x) { 1639 if (E->getNumInits() == 0) 1640 return DerivedValueInitialization(E); 1641 if (E->getNumInits() == 1) 1642 return StmtVisitorTy::Visit(E->getInit(0)); 1643 } 1644 return DerivedError(E); 1645 } 1646 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 1647 return DerivedValueInitialization(E); 1648 } 1649 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 1650 return DerivedValueInitialization(E); 1651 } 1652 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 1653 return DerivedValueInitialization(E); 1654 } 1655 1656 /// A member expression where the object is a prvalue is itself a prvalue. 1657 RetTy VisitMemberExpr(const MemberExpr *E) { 1658 assert(!E->isArrow() && "missing call to bound member function?"); 1659 1660 CCValue Val; 1661 if (!Evaluate(Val, Info, E->getBase())) 1662 return false; 1663 1664 QualType BaseTy = E->getBase()->getType(); 1665 1666 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 1667 if (!FD) return false; 1668 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 1669 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 1670 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 1671 1672 SubobjectDesignator Designator; 1673 Designator.addDecl(FD); 1674 1675 return ExtractSubobject(Info, Val, BaseTy, Designator, E->getType()) && 1676 DerivedSuccess(Val, E); 1677 } 1678 1679 RetTy VisitCastExpr(const CastExpr *E) { 1680 switch (E->getCastKind()) { 1681 default: 1682 break; 1683 1684 case CK_NoOp: 1685 return StmtVisitorTy::Visit(E->getSubExpr()); 1686 1687 case CK_LValueToRValue: { 1688 LValue LVal; 1689 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) { 1690 CCValue RVal; 1691 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal)) 1692 return DerivedSuccess(RVal, E); 1693 } 1694 break; 1695 } 1696 } 1697 1698 return DerivedError(E); 1699 } 1700 1701 /// Visit a value which is evaluated, but whose value is ignored. 1702 void VisitIgnoredValue(const Expr *E) { 1703 CCValue Scratch; 1704 if (!Evaluate(Scratch, Info, E)) 1705 Info.EvalStatus.HasSideEffects = true; 1706 } 1707 }; 1708 1709 } 1710 1711 //===----------------------------------------------------------------------===// 1712 // Common base class for lvalue and temporary evaluation. 1713 //===----------------------------------------------------------------------===// 1714 namespace { 1715 template<class Derived> 1716 class LValueExprEvaluatorBase 1717 : public ExprEvaluatorBase<Derived, bool> { 1718 protected: 1719 LValue &Result; 1720 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 1721 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy; 1722 1723 bool Success(APValue::LValueBase B) { 1724 Result.set(B); 1725 return true; 1726 } 1727 1728 public: 1729 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) : 1730 ExprEvaluatorBaseTy(Info), Result(Result) {} 1731 1732 bool Success(const CCValue &V, const Expr *E) { 1733 Result.setFrom(V); 1734 return true; 1735 } 1736 bool Error(const Expr *E) { 1737 return false; 1738 } 1739 1740 bool CheckValidLValue() { 1741 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence 1742 // there are no null references, nor once-past-the-end references. 1743 // FIXME: Check for one-past-the-end array indices 1744 return Result.Base && !Result.Designator.Invalid && 1745 !Result.Designator.OnePastTheEnd; 1746 } 1747 1748 bool VisitMemberExpr(const MemberExpr *E) { 1749 // Handle non-static data members. 1750 QualType BaseTy; 1751 if (E->isArrow()) { 1752 if (!EvaluatePointer(E->getBase(), Result, this->Info)) 1753 return false; 1754 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType(); 1755 } else { 1756 if (!this->Visit(E->getBase())) 1757 return false; 1758 BaseTy = E->getBase()->getType(); 1759 } 1760 // FIXME: In C++11, require the result to be a valid lvalue. 1761 1762 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 1763 // FIXME: Handle IndirectFieldDecls 1764 if (!FD) return false; 1765 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 1766 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 1767 (void)BaseTy; 1768 1769 HandleLValueMember(this->Info, Result, FD); 1770 1771 if (FD->getType()->isReferenceType()) { 1772 CCValue RefValue; 1773 if (!HandleLValueToRValueConversion(this->Info, FD->getType(), Result, 1774 RefValue)) 1775 return false; 1776 return Success(RefValue, E); 1777 } 1778 return true; 1779 } 1780 1781 bool VisitBinaryOperator(const BinaryOperator *E) { 1782 switch (E->getOpcode()) { 1783 default: 1784 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 1785 1786 case BO_PtrMemD: 1787 case BO_PtrMemI: 1788 return HandleMemberPointerAccess(this->Info, E, Result); 1789 } 1790 } 1791 1792 bool VisitCastExpr(const CastExpr *E) { 1793 switch (E->getCastKind()) { 1794 default: 1795 return ExprEvaluatorBaseTy::VisitCastExpr(E); 1796 1797 case CK_DerivedToBase: 1798 case CK_UncheckedDerivedToBase: { 1799 if (!this->Visit(E->getSubExpr())) 1800 return false; 1801 if (!CheckValidLValue()) 1802 return false; 1803 1804 // Now figure out the necessary offset to add to the base LV to get from 1805 // the derived class to the base class. 1806 QualType Type = E->getSubExpr()->getType(); 1807 1808 for (CastExpr::path_const_iterator PathI = E->path_begin(), 1809 PathE = E->path_end(); PathI != PathE; ++PathI) { 1810 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(), 1811 *PathI)) 1812 return false; 1813 Type = (*PathI)->getType(); 1814 } 1815 1816 return true; 1817 } 1818 } 1819 } 1820 }; 1821 } 1822 1823 //===----------------------------------------------------------------------===// 1824 // LValue Evaluation 1825 // 1826 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 1827 // function designators (in C), decl references to void objects (in C), and 1828 // temporaries (if building with -Wno-address-of-temporary). 1829 // 1830 // LValue evaluation produces values comprising a base expression of one of the 1831 // following types: 1832 // - Declarations 1833 // * VarDecl 1834 // * FunctionDecl 1835 // - Literals 1836 // * CompoundLiteralExpr in C 1837 // * StringLiteral 1838 // * PredefinedExpr 1839 // * ObjCStringLiteralExpr 1840 // * ObjCEncodeExpr 1841 // * AddrLabelExpr 1842 // * BlockExpr 1843 // * CallExpr for a MakeStringConstant builtin 1844 // - Locals and temporaries 1845 // * Any Expr, with a Frame indicating the function in which the temporary was 1846 // evaluated. 1847 // plus an offset in bytes. 1848 //===----------------------------------------------------------------------===// 1849 namespace { 1850 class LValueExprEvaluator 1851 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 1852 public: 1853 LValueExprEvaluator(EvalInfo &Info, LValue &Result) : 1854 LValueExprEvaluatorBaseTy(Info, Result) {} 1855 1856 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 1857 1858 bool VisitDeclRefExpr(const DeclRefExpr *E); 1859 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 1860 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 1861 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 1862 bool VisitMemberExpr(const MemberExpr *E); 1863 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 1864 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 1865 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 1866 bool VisitUnaryDeref(const UnaryOperator *E); 1867 1868 bool VisitCastExpr(const CastExpr *E) { 1869 switch (E->getCastKind()) { 1870 default: 1871 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 1872 1873 case CK_LValueBitCast: 1874 if (!Visit(E->getSubExpr())) 1875 return false; 1876 Result.Designator.setInvalid(); 1877 return true; 1878 1879 case CK_BaseToDerived: 1880 if (!Visit(E->getSubExpr())) 1881 return false; 1882 if (!CheckValidLValue()) 1883 return false; 1884 return HandleBaseToDerivedCast(Info, E, Result); 1885 } 1886 } 1887 1888 // FIXME: Missing: __real__, __imag__ 1889 1890 }; 1891 } // end anonymous namespace 1892 1893 /// Evaluate an expression as an lvalue. This can be legitimately called on 1894 /// expressions which are not glvalues, in a few cases: 1895 /// * function designators in C, 1896 /// * "extern void" objects, 1897 /// * temporaries, if building with -Wno-address-of-temporary. 1898 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) { 1899 assert((E->isGLValue() || E->getType()->isFunctionType() || 1900 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) && 1901 "can't evaluate expression as an lvalue"); 1902 return LValueExprEvaluator(Info, Result).Visit(E); 1903 } 1904 1905 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 1906 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 1907 return Success(FD); 1908 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 1909 return VisitVarDecl(E, VD); 1910 return Error(E); 1911 } 1912 1913 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 1914 if (!VD->getType()->isReferenceType()) { 1915 if (isa<ParmVarDecl>(VD)) { 1916 Result.set(VD, Info.CurrentCall); 1917 return true; 1918 } 1919 return Success(VD); 1920 } 1921 1922 CCValue V; 1923 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V)) 1924 return Success(V, E); 1925 1926 return Error(E); 1927 } 1928 1929 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 1930 const MaterializeTemporaryExpr *E) { 1931 if (E->GetTemporaryExpr()->isRValue()) { 1932 if (E->getType()->isRecordType() && E->getType()->isLiteralType()) 1933 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info); 1934 1935 Result.set(E, Info.CurrentCall); 1936 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info, 1937 Result, E->GetTemporaryExpr()); 1938 } 1939 1940 // Materialization of an lvalue temporary occurs when we need to force a copy 1941 // (for instance, if it's a bitfield). 1942 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases. 1943 if (!Visit(E->GetTemporaryExpr())) 1944 return false; 1945 if (!HandleLValueToRValueConversion(Info, E->getType(), Result, 1946 Info.CurrentCall->Temporaries[E])) 1947 return false; 1948 Result.set(E, Info.CurrentCall); 1949 return true; 1950 } 1951 1952 bool 1953 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 1954 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 1955 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 1956 // only see this when folding in C, so there's no standard to follow here. 1957 return Success(E); 1958 } 1959 1960 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 1961 // Handle static data members. 1962 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 1963 VisitIgnoredValue(E->getBase()); 1964 return VisitVarDecl(E, VD); 1965 } 1966 1967 // Handle static member functions. 1968 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 1969 if (MD->isStatic()) { 1970 VisitIgnoredValue(E->getBase()); 1971 return Success(MD); 1972 } 1973 } 1974 1975 // Handle non-static data members. 1976 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 1977 } 1978 1979 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1980 // FIXME: Deal with vectors as array subscript bases. 1981 if (E->getBase()->getType()->isVectorType()) 1982 return false; 1983 1984 if (!EvaluatePointer(E->getBase(), Result, Info)) 1985 return false; 1986 1987 APSInt Index; 1988 if (!EvaluateInteger(E->getIdx(), Index, Info)) 1989 return false; 1990 int64_t IndexValue 1991 = Index.isSigned() ? Index.getSExtValue() 1992 : static_cast<int64_t>(Index.getZExtValue()); 1993 1994 // FIXME: In C++11, require the result to be a valid lvalue. 1995 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue); 1996 } 1997 1998 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 1999 // FIXME: In C++11, require the result to be a valid lvalue. 2000 return EvaluatePointer(E->getSubExpr(), Result, Info); 2001 } 2002 2003 //===----------------------------------------------------------------------===// 2004 // Pointer Evaluation 2005 //===----------------------------------------------------------------------===// 2006 2007 namespace { 2008 class PointerExprEvaluator 2009 : public ExprEvaluatorBase<PointerExprEvaluator, bool> { 2010 LValue &Result; 2011 2012 bool Success(const Expr *E) { 2013 Result.set(E); 2014 return true; 2015 } 2016 public: 2017 2018 PointerExprEvaluator(EvalInfo &info, LValue &Result) 2019 : ExprEvaluatorBaseTy(info), Result(Result) {} 2020 2021 bool Success(const CCValue &V, const Expr *E) { 2022 Result.setFrom(V); 2023 return true; 2024 } 2025 bool Error(const Stmt *S) { 2026 return false; 2027 } 2028 bool ValueInitialization(const Expr *E) { 2029 return Success((Expr*)0); 2030 } 2031 2032 bool VisitBinaryOperator(const BinaryOperator *E); 2033 bool VisitCastExpr(const CastExpr* E); 2034 bool VisitUnaryAddrOf(const UnaryOperator *E); 2035 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 2036 { return Success(E); } 2037 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 2038 { return Success(E); } 2039 bool VisitCallExpr(const CallExpr *E); 2040 bool VisitBlockExpr(const BlockExpr *E) { 2041 if (!E->getBlockDecl()->hasCaptures()) 2042 return Success(E); 2043 return false; 2044 } 2045 bool VisitCXXThisExpr(const CXXThisExpr *E) { 2046 if (!Info.CurrentCall->This) 2047 return false; 2048 Result = *Info.CurrentCall->This; 2049 return true; 2050 } 2051 2052 // FIXME: Missing: @protocol, @selector 2053 }; 2054 } // end anonymous namespace 2055 2056 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) { 2057 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 2058 return PointerExprEvaluator(Info, Result).Visit(E); 2059 } 2060 2061 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 2062 if (E->getOpcode() != BO_Add && 2063 E->getOpcode() != BO_Sub) 2064 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 2065 2066 const Expr *PExp = E->getLHS(); 2067 const Expr *IExp = E->getRHS(); 2068 if (IExp->getType()->isPointerType()) 2069 std::swap(PExp, IExp); 2070 2071 if (!EvaluatePointer(PExp, Result, Info)) 2072 return false; 2073 2074 llvm::APSInt Offset; 2075 if (!EvaluateInteger(IExp, Offset, Info)) 2076 return false; 2077 int64_t AdditionalOffset 2078 = Offset.isSigned() ? Offset.getSExtValue() 2079 : static_cast<int64_t>(Offset.getZExtValue()); 2080 if (E->getOpcode() == BO_Sub) 2081 AdditionalOffset = -AdditionalOffset; 2082 2083 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType(); 2084 // FIXME: In C++11, require the result to be a valid lvalue. 2085 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset); 2086 } 2087 2088 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 2089 return EvaluateLValue(E->getSubExpr(), Result, Info); 2090 } 2091 2092 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 2093 const Expr* SubExpr = E->getSubExpr(); 2094 2095 switch (E->getCastKind()) { 2096 default: 2097 break; 2098 2099 case CK_BitCast: 2100 case CK_CPointerToObjCPointerCast: 2101 case CK_BlockPointerToObjCPointerCast: 2102 case CK_AnyPointerToBlockPointerCast: 2103 if (!Visit(SubExpr)) 2104 return false; 2105 Result.Designator.setInvalid(); 2106 return true; 2107 2108 case CK_DerivedToBase: 2109 case CK_UncheckedDerivedToBase: { 2110 if (!EvaluatePointer(E->getSubExpr(), Result, Info)) 2111 return false; 2112 if (!Result.Base && Result.Offset.isZero()) 2113 return true; 2114 2115 // Now figure out the necessary offset to add to the base LV to get from 2116 // the derived class to the base class. 2117 QualType Type = 2118 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 2119 2120 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2121 PathE = E->path_end(); PathI != PathE; ++PathI) { 2122 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI)) 2123 return false; 2124 Type = (*PathI)->getType(); 2125 } 2126 2127 return true; 2128 } 2129 2130 case CK_BaseToDerived: 2131 if (!Visit(E->getSubExpr())) 2132 return false; 2133 if (!Result.Base && Result.Offset.isZero()) 2134 return true; 2135 return HandleBaseToDerivedCast(Info, E, Result); 2136 2137 case CK_NullToPointer: 2138 return ValueInitialization(E); 2139 2140 case CK_IntegralToPointer: { 2141 CCValue Value; 2142 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 2143 break; 2144 2145 if (Value.isInt()) { 2146 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 2147 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 2148 Result.Base = (Expr*)0; 2149 Result.Offset = CharUnits::fromQuantity(N); 2150 Result.Frame = 0; 2151 Result.Designator.setInvalid(); 2152 return true; 2153 } else { 2154 // Cast is of an lvalue, no need to change value. 2155 Result.setFrom(Value); 2156 return true; 2157 } 2158 } 2159 case CK_ArrayToPointerDecay: 2160 if (SubExpr->isGLValue()) { 2161 if (!EvaluateLValue(SubExpr, Result, Info)) 2162 return false; 2163 } else { 2164 Result.set(SubExpr, Info.CurrentCall); 2165 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr], 2166 Info, Result, SubExpr)) 2167 return false; 2168 } 2169 // The result is a pointer to the first element of the array. 2170 Result.Designator.addIndex(0); 2171 return true; 2172 2173 case CK_FunctionToPointerDecay: 2174 return EvaluateLValue(SubExpr, Result, Info); 2175 } 2176 2177 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2178 } 2179 2180 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 2181 if (IsStringLiteralCall(E)) 2182 return Success(E); 2183 2184 return ExprEvaluatorBaseTy::VisitCallExpr(E); 2185 } 2186 2187 //===----------------------------------------------------------------------===// 2188 // Member Pointer Evaluation 2189 //===----------------------------------------------------------------------===// 2190 2191 namespace { 2192 class MemberPointerExprEvaluator 2193 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> { 2194 MemberPtr &Result; 2195 2196 bool Success(const ValueDecl *D) { 2197 Result = MemberPtr(D); 2198 return true; 2199 } 2200 public: 2201 2202 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 2203 : ExprEvaluatorBaseTy(Info), Result(Result) {} 2204 2205 bool Success(const CCValue &V, const Expr *E) { 2206 Result.setFrom(V); 2207 return true; 2208 } 2209 bool Error(const Stmt *S) { 2210 return false; 2211 } 2212 bool ValueInitialization(const Expr *E) { 2213 return Success((const ValueDecl*)0); 2214 } 2215 2216 bool VisitCastExpr(const CastExpr *E); 2217 bool VisitUnaryAddrOf(const UnaryOperator *E); 2218 }; 2219 } // end anonymous namespace 2220 2221 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 2222 EvalInfo &Info) { 2223 assert(E->isRValue() && E->getType()->isMemberPointerType()); 2224 return MemberPointerExprEvaluator(Info, Result).Visit(E); 2225 } 2226 2227 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 2228 switch (E->getCastKind()) { 2229 default: 2230 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2231 2232 case CK_NullToMemberPointer: 2233 return ValueInitialization(E); 2234 2235 case CK_BaseToDerivedMemberPointer: { 2236 if (!Visit(E->getSubExpr())) 2237 return false; 2238 if (E->path_empty()) 2239 return true; 2240 // Base-to-derived member pointer casts store the path in derived-to-base 2241 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 2242 // the wrong end of the derived->base arc, so stagger the path by one class. 2243 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 2244 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 2245 PathI != PathE; ++PathI) { 2246 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 2247 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 2248 if (!Result.castToDerived(Derived)) 2249 return false; 2250 } 2251 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 2252 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 2253 return false; 2254 return true; 2255 } 2256 2257 case CK_DerivedToBaseMemberPointer: 2258 if (!Visit(E->getSubExpr())) 2259 return false; 2260 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2261 PathE = E->path_end(); PathI != PathE; ++PathI) { 2262 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 2263 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 2264 if (!Result.castToBase(Base)) 2265 return false; 2266 } 2267 return true; 2268 } 2269 } 2270 2271 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 2272 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 2273 // member can be formed. 2274 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 2275 } 2276 2277 //===----------------------------------------------------------------------===// 2278 // Record Evaluation 2279 //===----------------------------------------------------------------------===// 2280 2281 namespace { 2282 class RecordExprEvaluator 2283 : public ExprEvaluatorBase<RecordExprEvaluator, bool> { 2284 const LValue &This; 2285 APValue &Result; 2286 public: 2287 2288 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 2289 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 2290 2291 bool Success(const CCValue &V, const Expr *E) { 2292 return CheckConstantExpression(V, Result); 2293 } 2294 bool Error(const Expr *E) { return false; } 2295 2296 bool VisitCastExpr(const CastExpr *E); 2297 bool VisitInitListExpr(const InitListExpr *E); 2298 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 2299 }; 2300 } 2301 2302 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 2303 switch (E->getCastKind()) { 2304 default: 2305 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2306 2307 case CK_ConstructorConversion: 2308 return Visit(E->getSubExpr()); 2309 2310 case CK_DerivedToBase: 2311 case CK_UncheckedDerivedToBase: { 2312 CCValue DerivedObject; 2313 if (!Evaluate(DerivedObject, Info, E->getSubExpr()) || 2314 !DerivedObject.isStruct()) 2315 return false; 2316 2317 // Derived-to-base rvalue conversion: just slice off the derived part. 2318 APValue *Value = &DerivedObject; 2319 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 2320 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2321 PathE = E->path_end(); PathI != PathE; ++PathI) { 2322 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 2323 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 2324 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 2325 RD = Base; 2326 } 2327 Result = *Value; 2328 return true; 2329 } 2330 } 2331 } 2332 2333 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 2334 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 2335 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2336 2337 if (RD->isUnion()) { 2338 Result = APValue(E->getInitializedFieldInUnion()); 2339 if (!E->getNumInits()) 2340 return true; 2341 LValue Subobject = This; 2342 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(), 2343 &Layout); 2344 return EvaluateConstantExpression(Result.getUnionValue(), Info, 2345 Subobject, E->getInit(0)); 2346 } 2347 2348 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) && 2349 "initializer list for class with base classes"); 2350 Result = APValue(APValue::UninitStruct(), 0, 2351 std::distance(RD->field_begin(), RD->field_end())); 2352 unsigned ElementNo = 0; 2353 for (RecordDecl::field_iterator Field = RD->field_begin(), 2354 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) { 2355 // Anonymous bit-fields are not considered members of the class for 2356 // purposes of aggregate initialization. 2357 if (Field->isUnnamedBitfield()) 2358 continue; 2359 2360 LValue Subobject = This; 2361 HandleLValueMember(Info, Subobject, *Field, &Layout); 2362 2363 if (ElementNo < E->getNumInits()) { 2364 if (!EvaluateConstantExpression( 2365 Result.getStructField((*Field)->getFieldIndex()), 2366 Info, Subobject, E->getInit(ElementNo++))) 2367 return false; 2368 } else { 2369 // Perform an implicit value-initialization for members beyond the end of 2370 // the initializer list. 2371 ImplicitValueInitExpr VIE(Field->getType()); 2372 if (!EvaluateConstantExpression( 2373 Result.getStructField((*Field)->getFieldIndex()), 2374 Info, Subobject, &VIE)) 2375 return false; 2376 } 2377 } 2378 2379 return true; 2380 } 2381 2382 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 2383 const CXXConstructorDecl *FD = E->getConstructor(); 2384 const FunctionDecl *Definition = 0; 2385 FD->getBody(Definition); 2386 2387 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl()) 2388 return false; 2389 2390 // FIXME: Elide the copy/move construction wherever we can. 2391 if (E->isElidable()) 2392 if (const MaterializeTemporaryExpr *ME 2393 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 2394 return Visit(ME->GetTemporaryExpr()); 2395 2396 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 2397 return HandleConstructorCall(This, Args, cast<CXXConstructorDecl>(Definition), 2398 Info, Result); 2399 } 2400 2401 static bool EvaluateRecord(const Expr *E, const LValue &This, 2402 APValue &Result, EvalInfo &Info) { 2403 assert(E->isRValue() && E->getType()->isRecordType() && 2404 E->getType()->isLiteralType() && 2405 "can't evaluate expression as a record rvalue"); 2406 return RecordExprEvaluator(Info, This, Result).Visit(E); 2407 } 2408 2409 //===----------------------------------------------------------------------===// 2410 // Temporary Evaluation 2411 // 2412 // Temporaries are represented in the AST as rvalues, but generally behave like 2413 // lvalues. The full-object of which the temporary is a subobject is implicitly 2414 // materialized so that a reference can bind to it. 2415 //===----------------------------------------------------------------------===// 2416 namespace { 2417 class TemporaryExprEvaluator 2418 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 2419 public: 2420 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 2421 LValueExprEvaluatorBaseTy(Info, Result) {} 2422 2423 /// Visit an expression which constructs the value of this temporary. 2424 bool VisitConstructExpr(const Expr *E) { 2425 Result.set(E, Info.CurrentCall); 2426 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info, 2427 Result, E); 2428 } 2429 2430 bool VisitCastExpr(const CastExpr *E) { 2431 switch (E->getCastKind()) { 2432 default: 2433 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 2434 2435 case CK_ConstructorConversion: 2436 return VisitConstructExpr(E->getSubExpr()); 2437 } 2438 } 2439 bool VisitInitListExpr(const InitListExpr *E) { 2440 return VisitConstructExpr(E); 2441 } 2442 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 2443 return VisitConstructExpr(E); 2444 } 2445 bool VisitCallExpr(const CallExpr *E) { 2446 return VisitConstructExpr(E); 2447 } 2448 }; 2449 } // end anonymous namespace 2450 2451 /// Evaluate an expression of record type as a temporary. 2452 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 2453 assert(E->isRValue() && E->getType()->isRecordType() && 2454 E->getType()->isLiteralType()); 2455 return TemporaryExprEvaluator(Info, Result).Visit(E); 2456 } 2457 2458 //===----------------------------------------------------------------------===// 2459 // Vector Evaluation 2460 //===----------------------------------------------------------------------===// 2461 2462 namespace { 2463 class VectorExprEvaluator 2464 : public ExprEvaluatorBase<VectorExprEvaluator, bool> { 2465 APValue &Result; 2466 public: 2467 2468 VectorExprEvaluator(EvalInfo &info, APValue &Result) 2469 : ExprEvaluatorBaseTy(info), Result(Result) {} 2470 2471 bool Success(const ArrayRef<APValue> &V, const Expr *E) { 2472 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 2473 // FIXME: remove this APValue copy. 2474 Result = APValue(V.data(), V.size()); 2475 return true; 2476 } 2477 bool Success(const CCValue &V, const Expr *E) { 2478 assert(V.isVector()); 2479 Result = V; 2480 return true; 2481 } 2482 bool Error(const Expr *E) { return false; } 2483 bool ValueInitialization(const Expr *E); 2484 2485 bool VisitUnaryReal(const UnaryOperator *E) 2486 { return Visit(E->getSubExpr()); } 2487 bool VisitCastExpr(const CastExpr* E); 2488 bool VisitInitListExpr(const InitListExpr *E); 2489 bool VisitUnaryImag(const UnaryOperator *E); 2490 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 2491 // binary comparisons, binary and/or/xor, 2492 // shufflevector, ExtVectorElementExpr 2493 // (Note that these require implementing conversions 2494 // between vector types.) 2495 }; 2496 } // end anonymous namespace 2497 2498 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 2499 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 2500 return VectorExprEvaluator(Info, Result).Visit(E); 2501 } 2502 2503 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { 2504 const VectorType *VTy = E->getType()->castAs<VectorType>(); 2505 unsigned NElts = VTy->getNumElements(); 2506 2507 const Expr *SE = E->getSubExpr(); 2508 QualType SETy = SE->getType(); 2509 2510 switch (E->getCastKind()) { 2511 case CK_VectorSplat: { 2512 APValue Val = APValue(); 2513 if (SETy->isIntegerType()) { 2514 APSInt IntResult; 2515 if (!EvaluateInteger(SE, IntResult, Info)) 2516 return Error(E); 2517 Val = APValue(IntResult); 2518 } else if (SETy->isRealFloatingType()) { 2519 APFloat F(0.0); 2520 if (!EvaluateFloat(SE, F, Info)) 2521 return Error(E); 2522 Val = APValue(F); 2523 } else { 2524 return Error(E); 2525 } 2526 2527 // Splat and create vector APValue. 2528 SmallVector<APValue, 4> Elts(NElts, Val); 2529 return Success(Elts, E); 2530 } 2531 default: 2532 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2533 } 2534 } 2535 2536 bool 2537 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 2538 const VectorType *VT = E->getType()->castAs<VectorType>(); 2539 unsigned NumInits = E->getNumInits(); 2540 unsigned NumElements = VT->getNumElements(); 2541 2542 QualType EltTy = VT->getElementType(); 2543 SmallVector<APValue, 4> Elements; 2544 2545 // If a vector is initialized with a single element, that value 2546 // becomes every element of the vector, not just the first. 2547 // This is the behavior described in the IBM AltiVec documentation. 2548 if (NumInits == 1) { 2549 2550 // Handle the case where the vector is initialized by another 2551 // vector (OpenCL 6.1.6). 2552 if (E->getInit(0)->getType()->isVectorType()) 2553 return Visit(E->getInit(0)); 2554 2555 APValue InitValue; 2556 if (EltTy->isIntegerType()) { 2557 llvm::APSInt sInt(32); 2558 if (!EvaluateInteger(E->getInit(0), sInt, Info)) 2559 return Error(E); 2560 InitValue = APValue(sInt); 2561 } else { 2562 llvm::APFloat f(0.0); 2563 if (!EvaluateFloat(E->getInit(0), f, Info)) 2564 return Error(E); 2565 InitValue = APValue(f); 2566 } 2567 for (unsigned i = 0; i < NumElements; i++) { 2568 Elements.push_back(InitValue); 2569 } 2570 } else { 2571 for (unsigned i = 0; i < NumElements; i++) { 2572 if (EltTy->isIntegerType()) { 2573 llvm::APSInt sInt(32); 2574 if (i < NumInits) { 2575 if (!EvaluateInteger(E->getInit(i), sInt, Info)) 2576 return Error(E); 2577 } else { 2578 sInt = Info.Ctx.MakeIntValue(0, EltTy); 2579 } 2580 Elements.push_back(APValue(sInt)); 2581 } else { 2582 llvm::APFloat f(0.0); 2583 if (i < NumInits) { 2584 if (!EvaluateFloat(E->getInit(i), f, Info)) 2585 return Error(E); 2586 } else { 2587 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 2588 } 2589 Elements.push_back(APValue(f)); 2590 } 2591 } 2592 } 2593 return Success(Elements, E); 2594 } 2595 2596 bool 2597 VectorExprEvaluator::ValueInitialization(const Expr *E) { 2598 const VectorType *VT = E->getType()->getAs<VectorType>(); 2599 QualType EltTy = VT->getElementType(); 2600 APValue ZeroElement; 2601 if (EltTy->isIntegerType()) 2602 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 2603 else 2604 ZeroElement = 2605 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 2606 2607 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 2608 return Success(Elements, E); 2609 } 2610 2611 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 2612 VisitIgnoredValue(E->getSubExpr()); 2613 return ValueInitialization(E); 2614 } 2615 2616 //===----------------------------------------------------------------------===// 2617 // Array Evaluation 2618 //===----------------------------------------------------------------------===// 2619 2620 namespace { 2621 class ArrayExprEvaluator 2622 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> { 2623 const LValue &This; 2624 APValue &Result; 2625 public: 2626 2627 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 2628 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 2629 2630 bool Success(const APValue &V, const Expr *E) { 2631 assert(V.isArray() && "Expected array type"); 2632 Result = V; 2633 return true; 2634 } 2635 bool Error(const Expr *E) { return false; } 2636 2637 bool ValueInitialization(const Expr *E) { 2638 const ConstantArrayType *CAT = 2639 Info.Ctx.getAsConstantArrayType(E->getType()); 2640 if (!CAT) 2641 return false; 2642 2643 Result = APValue(APValue::UninitArray(), 0, 2644 CAT->getSize().getZExtValue()); 2645 if (!Result.hasArrayFiller()) return true; 2646 2647 // Value-initialize all elements. 2648 LValue Subobject = This; 2649 Subobject.Designator.addIndex(0); 2650 ImplicitValueInitExpr VIE(CAT->getElementType()); 2651 return EvaluateConstantExpression(Result.getArrayFiller(), Info, 2652 Subobject, &VIE); 2653 } 2654 2655 bool VisitInitListExpr(const InitListExpr *E); 2656 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 2657 }; 2658 } // end anonymous namespace 2659 2660 static bool EvaluateArray(const Expr *E, const LValue &This, 2661 APValue &Result, EvalInfo &Info) { 2662 assert(E->isRValue() && E->getType()->isArrayType() && 2663 E->getType()->isLiteralType() && "not a literal array rvalue"); 2664 return ArrayExprEvaluator(Info, This, Result).Visit(E); 2665 } 2666 2667 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 2668 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 2669 if (!CAT) 2670 return false; 2671 2672 Result = APValue(APValue::UninitArray(), E->getNumInits(), 2673 CAT->getSize().getZExtValue()); 2674 LValue Subobject = This; 2675 Subobject.Designator.addIndex(0); 2676 unsigned Index = 0; 2677 for (InitListExpr::const_iterator I = E->begin(), End = E->end(); 2678 I != End; ++I, ++Index) { 2679 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index), 2680 Info, Subobject, cast<Expr>(*I))) 2681 return false; 2682 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1)) 2683 return false; 2684 } 2685 2686 if (!Result.hasArrayFiller()) return true; 2687 assert(E->hasArrayFiller() && "no array filler for incomplete init list"); 2688 // FIXME: The Subobject here isn't necessarily right. This rarely matters, 2689 // but sometimes does: 2690 // struct S { constexpr S() : p(&p) {} void *p; }; 2691 // S s[10] = {}; 2692 return EvaluateConstantExpression(Result.getArrayFiller(), Info, 2693 Subobject, E->getArrayFiller()); 2694 } 2695 2696 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 2697 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 2698 if (!CAT) 2699 return false; 2700 2701 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue()); 2702 if (!Result.hasArrayFiller()) 2703 return true; 2704 2705 const CXXConstructorDecl *FD = E->getConstructor(); 2706 const FunctionDecl *Definition = 0; 2707 FD->getBody(Definition); 2708 2709 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl()) 2710 return false; 2711 2712 // FIXME: The Subobject here isn't necessarily right. This rarely matters, 2713 // but sometimes does: 2714 // struct S { constexpr S() : p(&p) {} void *p; }; 2715 // S s[10]; 2716 LValue Subobject = This; 2717 Subobject.Designator.addIndex(0); 2718 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 2719 return HandleConstructorCall(Subobject, Args, 2720 cast<CXXConstructorDecl>(Definition), 2721 Info, Result.getArrayFiller()); 2722 } 2723 2724 //===----------------------------------------------------------------------===// 2725 // Integer Evaluation 2726 // 2727 // As a GNU extension, we support casting pointers to sufficiently-wide integer 2728 // types and back in constant folding. Integer values are thus represented 2729 // either as an integer-valued APValue, or as an lvalue-valued APValue. 2730 //===----------------------------------------------------------------------===// 2731 2732 namespace { 2733 class IntExprEvaluator 2734 : public ExprEvaluatorBase<IntExprEvaluator, bool> { 2735 CCValue &Result; 2736 public: 2737 IntExprEvaluator(EvalInfo &info, CCValue &result) 2738 : ExprEvaluatorBaseTy(info), Result(result) {} 2739 2740 bool Success(const llvm::APSInt &SI, const Expr *E) { 2741 assert(E->getType()->isIntegralOrEnumerationType() && 2742 "Invalid evaluation result."); 2743 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 2744 "Invalid evaluation result."); 2745 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 2746 "Invalid evaluation result."); 2747 Result = CCValue(SI); 2748 return true; 2749 } 2750 2751 bool Success(const llvm::APInt &I, const Expr *E) { 2752 assert(E->getType()->isIntegralOrEnumerationType() && 2753 "Invalid evaluation result."); 2754 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 2755 "Invalid evaluation result."); 2756 Result = CCValue(APSInt(I)); 2757 Result.getInt().setIsUnsigned( 2758 E->getType()->isUnsignedIntegerOrEnumerationType()); 2759 return true; 2760 } 2761 2762 bool Success(uint64_t Value, const Expr *E) { 2763 assert(E->getType()->isIntegralOrEnumerationType() && 2764 "Invalid evaluation result."); 2765 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType())); 2766 return true; 2767 } 2768 2769 bool Success(CharUnits Size, const Expr *E) { 2770 return Success(Size.getQuantity(), E); 2771 } 2772 2773 2774 bool Error(SourceLocation L, diag::kind D, const Expr *E) { 2775 // Take the first error. 2776 if (Info.EvalStatus.Diag == 0) { 2777 Info.EvalStatus.DiagLoc = L; 2778 Info.EvalStatus.Diag = D; 2779 Info.EvalStatus.DiagExpr = E; 2780 } 2781 return false; 2782 } 2783 2784 bool Success(const CCValue &V, const Expr *E) { 2785 if (V.isLValue()) { 2786 Result = V; 2787 return true; 2788 } 2789 return Success(V.getInt(), E); 2790 } 2791 bool Error(const Expr *E) { 2792 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 2793 } 2794 2795 bool ValueInitialization(const Expr *E) { return Success(0, E); } 2796 2797 //===--------------------------------------------------------------------===// 2798 // Visitor Methods 2799 //===--------------------------------------------------------------------===// 2800 2801 bool VisitIntegerLiteral(const IntegerLiteral *E) { 2802 return Success(E->getValue(), E); 2803 } 2804 bool VisitCharacterLiteral(const CharacterLiteral *E) { 2805 return Success(E->getValue(), E); 2806 } 2807 2808 bool CheckReferencedDecl(const Expr *E, const Decl *D); 2809 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2810 if (CheckReferencedDecl(E, E->getDecl())) 2811 return true; 2812 2813 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 2814 } 2815 bool VisitMemberExpr(const MemberExpr *E) { 2816 if (CheckReferencedDecl(E, E->getMemberDecl())) { 2817 VisitIgnoredValue(E->getBase()); 2818 return true; 2819 } 2820 2821 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 2822 } 2823 2824 bool VisitCallExpr(const CallExpr *E); 2825 bool VisitBinaryOperator(const BinaryOperator *E); 2826 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 2827 bool VisitUnaryOperator(const UnaryOperator *E); 2828 2829 bool VisitCastExpr(const CastExpr* E); 2830 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 2831 2832 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 2833 return Success(E->getValue(), E); 2834 } 2835 2836 // Note, GNU defines __null as an integer, not a pointer. 2837 bool VisitGNUNullExpr(const GNUNullExpr *E) { 2838 return ValueInitialization(E); 2839 } 2840 2841 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 2842 return Success(E->getValue(), E); 2843 } 2844 2845 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 2846 return Success(E->getValue(), E); 2847 } 2848 2849 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 2850 return Success(E->getValue(), E); 2851 } 2852 2853 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 2854 return Success(E->getValue(), E); 2855 } 2856 2857 bool VisitUnaryReal(const UnaryOperator *E); 2858 bool VisitUnaryImag(const UnaryOperator *E); 2859 2860 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 2861 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 2862 2863 private: 2864 CharUnits GetAlignOfExpr(const Expr *E); 2865 CharUnits GetAlignOfType(QualType T); 2866 static QualType GetObjectType(APValue::LValueBase B); 2867 bool TryEvaluateBuiltinObjectSize(const CallExpr *E); 2868 // FIXME: Missing: array subscript of vector, member of vector 2869 }; 2870 } // end anonymous namespace 2871 2872 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 2873 /// produce either the integer value or a pointer. 2874 /// 2875 /// GCC has a heinous extension which folds casts between pointer types and 2876 /// pointer-sized integral types. We support this by allowing the evaluation of 2877 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 2878 /// Some simple arithmetic on such values is supported (they are treated much 2879 /// like char*). 2880 static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result, 2881 EvalInfo &Info) { 2882 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 2883 return IntExprEvaluator(Info, Result).Visit(E); 2884 } 2885 2886 static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) { 2887 CCValue Val; 2888 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt()) 2889 return false; 2890 Result = Val.getInt(); 2891 return true; 2892 } 2893 2894 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 2895 // Enums are integer constant exprs. 2896 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 2897 // Check for signedness/width mismatches between E type and ECD value. 2898 bool SameSign = (ECD->getInitVal().isSigned() 2899 == E->getType()->isSignedIntegerOrEnumerationType()); 2900 bool SameWidth = (ECD->getInitVal().getBitWidth() 2901 == Info.Ctx.getIntWidth(E->getType())); 2902 if (SameSign && SameWidth) 2903 return Success(ECD->getInitVal(), E); 2904 else { 2905 // Get rid of mismatch (otherwise Success assertions will fail) 2906 // by computing a new value matching the type of E. 2907 llvm::APSInt Val = ECD->getInitVal(); 2908 if (!SameSign) 2909 Val.setIsSigned(!ECD->getInitVal().isSigned()); 2910 if (!SameWidth) 2911 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 2912 return Success(Val, E); 2913 } 2914 } 2915 return false; 2916 } 2917 2918 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 2919 /// as GCC. 2920 static int EvaluateBuiltinClassifyType(const CallExpr *E) { 2921 // The following enum mimics the values returned by GCC. 2922 // FIXME: Does GCC differ between lvalue and rvalue references here? 2923 enum gcc_type_class { 2924 no_type_class = -1, 2925 void_type_class, integer_type_class, char_type_class, 2926 enumeral_type_class, boolean_type_class, 2927 pointer_type_class, reference_type_class, offset_type_class, 2928 real_type_class, complex_type_class, 2929 function_type_class, method_type_class, 2930 record_type_class, union_type_class, 2931 array_type_class, string_type_class, 2932 lang_type_class 2933 }; 2934 2935 // If no argument was supplied, default to "no_type_class". This isn't 2936 // ideal, however it is what gcc does. 2937 if (E->getNumArgs() == 0) 2938 return no_type_class; 2939 2940 QualType ArgTy = E->getArg(0)->getType(); 2941 if (ArgTy->isVoidType()) 2942 return void_type_class; 2943 else if (ArgTy->isEnumeralType()) 2944 return enumeral_type_class; 2945 else if (ArgTy->isBooleanType()) 2946 return boolean_type_class; 2947 else if (ArgTy->isCharType()) 2948 return string_type_class; // gcc doesn't appear to use char_type_class 2949 else if (ArgTy->isIntegerType()) 2950 return integer_type_class; 2951 else if (ArgTy->isPointerType()) 2952 return pointer_type_class; 2953 else if (ArgTy->isReferenceType()) 2954 return reference_type_class; 2955 else if (ArgTy->isRealType()) 2956 return real_type_class; 2957 else if (ArgTy->isComplexType()) 2958 return complex_type_class; 2959 else if (ArgTy->isFunctionType()) 2960 return function_type_class; 2961 else if (ArgTy->isStructureOrClassType()) 2962 return record_type_class; 2963 else if (ArgTy->isUnionType()) 2964 return union_type_class; 2965 else if (ArgTy->isArrayType()) 2966 return array_type_class; 2967 else if (ArgTy->isUnionType()) 2968 return union_type_class; 2969 else // FIXME: offset_type_class, method_type_class, & lang_type_class? 2970 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 2971 return -1; 2972 } 2973 2974 /// Retrieves the "underlying object type" of the given expression, 2975 /// as used by __builtin_object_size. 2976 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) { 2977 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 2978 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 2979 return VD->getType(); 2980 } else if (const Expr *E = B.get<const Expr*>()) { 2981 if (isa<CompoundLiteralExpr>(E)) 2982 return E->getType(); 2983 } 2984 2985 return QualType(); 2986 } 2987 2988 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) { 2989 // TODO: Perhaps we should let LLVM lower this? 2990 LValue Base; 2991 if (!EvaluatePointer(E->getArg(0), Base, Info)) 2992 return false; 2993 2994 // If we can prove the base is null, lower to zero now. 2995 if (!Base.getLValueBase()) return Success(0, E); 2996 2997 QualType T = GetObjectType(Base.getLValueBase()); 2998 if (T.isNull() || 2999 T->isIncompleteType() || 3000 T->isFunctionType() || 3001 T->isVariablyModifiedType() || 3002 T->isDependentType()) 3003 return false; 3004 3005 CharUnits Size = Info.Ctx.getTypeSizeInChars(T); 3006 CharUnits Offset = Base.getLValueOffset(); 3007 3008 if (!Offset.isNegative() && Offset <= Size) 3009 Size -= Offset; 3010 else 3011 Size = CharUnits::Zero(); 3012 return Success(Size, E); 3013 } 3014 3015 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 3016 switch (E->isBuiltinCall()) { 3017 default: 3018 return ExprEvaluatorBaseTy::VisitCallExpr(E); 3019 3020 case Builtin::BI__builtin_object_size: { 3021 if (TryEvaluateBuiltinObjectSize(E)) 3022 return true; 3023 3024 // If evaluating the argument has side-effects we can't determine 3025 // the size of the object and lower it to unknown now. 3026 if (E->getArg(0)->HasSideEffects(Info.Ctx)) { 3027 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1) 3028 return Success(-1ULL, E); 3029 return Success(0, E); 3030 } 3031 3032 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 3033 } 3034 3035 case Builtin::BI__builtin_classify_type: 3036 return Success(EvaluateBuiltinClassifyType(E), E); 3037 3038 case Builtin::BI__builtin_constant_p: 3039 // __builtin_constant_p always has one operand: it returns true if that 3040 // operand can be folded, false otherwise. 3041 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E); 3042 3043 case Builtin::BI__builtin_eh_return_data_regno: { 3044 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 3045 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 3046 return Success(Operand, E); 3047 } 3048 3049 case Builtin::BI__builtin_expect: 3050 return Visit(E->getArg(0)); 3051 3052 case Builtin::BIstrlen: 3053 case Builtin::BI__builtin_strlen: 3054 // As an extension, we support strlen() and __builtin_strlen() as constant 3055 // expressions when the argument is a string literal. 3056 if (const StringLiteral *S 3057 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) { 3058 // The string literal may have embedded null characters. Find the first 3059 // one and truncate there. 3060 StringRef Str = S->getString(); 3061 StringRef::size_type Pos = Str.find(0); 3062 if (Pos != StringRef::npos) 3063 Str = Str.substr(0, Pos); 3064 3065 return Success(Str.size(), E); 3066 } 3067 3068 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 3069 3070 case Builtin::BI__atomic_is_lock_free: { 3071 APSInt SizeVal; 3072 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 3073 return false; 3074 3075 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 3076 // of two less than the maximum inline atomic width, we know it is 3077 // lock-free. If the size isn't a power of two, or greater than the 3078 // maximum alignment where we promote atomics, we know it is not lock-free 3079 // (at least not in the sense of atomic_is_lock_free). Otherwise, 3080 // the answer can only be determined at runtime; for example, 16-byte 3081 // atomics have lock-free implementations on some, but not all, 3082 // x86-64 processors. 3083 3084 // Check power-of-two. 3085 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 3086 if (!Size.isPowerOfTwo()) 3087 #if 0 3088 // FIXME: Suppress this folding until the ABI for the promotion width 3089 // settles. 3090 return Success(0, E); 3091 #else 3092 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 3093 #endif 3094 3095 #if 0 3096 // Check against promotion width. 3097 // FIXME: Suppress this folding until the ABI for the promotion width 3098 // settles. 3099 unsigned PromoteWidthBits = 3100 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth(); 3101 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits)) 3102 return Success(0, E); 3103 #endif 3104 3105 // Check against inlining width. 3106 unsigned InlineWidthBits = 3107 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 3108 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) 3109 return Success(1, E); 3110 3111 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 3112 } 3113 } 3114 } 3115 3116 static bool HasSameBase(const LValue &A, const LValue &B) { 3117 if (!A.getLValueBase()) 3118 return !B.getLValueBase(); 3119 if (!B.getLValueBase()) 3120 return false; 3121 3122 if (A.getLValueBase().getOpaqueValue() != 3123 B.getLValueBase().getOpaqueValue()) { 3124 const Decl *ADecl = GetLValueBaseDecl(A); 3125 if (!ADecl) 3126 return false; 3127 const Decl *BDecl = GetLValueBaseDecl(B); 3128 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 3129 return false; 3130 } 3131 3132 return IsGlobalLValue(A.getLValueBase()) || 3133 A.getLValueFrame() == B.getLValueFrame(); 3134 } 3135 3136 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 3137 if (E->isAssignmentOp()) 3138 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 3139 3140 if (E->getOpcode() == BO_Comma) { 3141 VisitIgnoredValue(E->getLHS()); 3142 return Visit(E->getRHS()); 3143 } 3144 3145 if (E->isLogicalOp()) { 3146 // These need to be handled specially because the operands aren't 3147 // necessarily integral 3148 bool lhsResult, rhsResult; 3149 3150 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) { 3151 // We were able to evaluate the LHS, see if we can get away with not 3152 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 3153 if (lhsResult == (E->getOpcode() == BO_LOr)) 3154 return Success(lhsResult, E); 3155 3156 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) { 3157 if (E->getOpcode() == BO_LOr) 3158 return Success(lhsResult || rhsResult, E); 3159 else 3160 return Success(lhsResult && rhsResult, E); 3161 } 3162 } else { 3163 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) { 3164 // We can't evaluate the LHS; however, sometimes the result 3165 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 3166 if (rhsResult == (E->getOpcode() == BO_LOr) || 3167 !rhsResult == (E->getOpcode() == BO_LAnd)) { 3168 // Since we weren't able to evaluate the left hand side, it 3169 // must have had side effects. 3170 Info.EvalStatus.HasSideEffects = true; 3171 3172 return Success(rhsResult, E); 3173 } 3174 } 3175 } 3176 3177 return false; 3178 } 3179 3180 QualType LHSTy = E->getLHS()->getType(); 3181 QualType RHSTy = E->getRHS()->getType(); 3182 3183 if (LHSTy->isAnyComplexType()) { 3184 assert(RHSTy->isAnyComplexType() && "Invalid comparison"); 3185 ComplexValue LHS, RHS; 3186 3187 if (!EvaluateComplex(E->getLHS(), LHS, Info)) 3188 return false; 3189 3190 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 3191 return false; 3192 3193 if (LHS.isComplexFloat()) { 3194 APFloat::cmpResult CR_r = 3195 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 3196 APFloat::cmpResult CR_i = 3197 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 3198 3199 if (E->getOpcode() == BO_EQ) 3200 return Success((CR_r == APFloat::cmpEqual && 3201 CR_i == APFloat::cmpEqual), E); 3202 else { 3203 assert(E->getOpcode() == BO_NE && 3204 "Invalid complex comparison."); 3205 return Success(((CR_r == APFloat::cmpGreaterThan || 3206 CR_r == APFloat::cmpLessThan || 3207 CR_r == APFloat::cmpUnordered) || 3208 (CR_i == APFloat::cmpGreaterThan || 3209 CR_i == APFloat::cmpLessThan || 3210 CR_i == APFloat::cmpUnordered)), E); 3211 } 3212 } else { 3213 if (E->getOpcode() == BO_EQ) 3214 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 3215 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 3216 else { 3217 assert(E->getOpcode() == BO_NE && 3218 "Invalid compex comparison."); 3219 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 3220 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 3221 } 3222 } 3223 } 3224 3225 if (LHSTy->isRealFloatingType() && 3226 RHSTy->isRealFloatingType()) { 3227 APFloat RHS(0.0), LHS(0.0); 3228 3229 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 3230 return false; 3231 3232 if (!EvaluateFloat(E->getLHS(), LHS, Info)) 3233 return false; 3234 3235 APFloat::cmpResult CR = LHS.compare(RHS); 3236 3237 switch (E->getOpcode()) { 3238 default: 3239 llvm_unreachable("Invalid binary operator!"); 3240 case BO_LT: 3241 return Success(CR == APFloat::cmpLessThan, E); 3242 case BO_GT: 3243 return Success(CR == APFloat::cmpGreaterThan, E); 3244 case BO_LE: 3245 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 3246 case BO_GE: 3247 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 3248 E); 3249 case BO_EQ: 3250 return Success(CR == APFloat::cmpEqual, E); 3251 case BO_NE: 3252 return Success(CR == APFloat::cmpGreaterThan 3253 || CR == APFloat::cmpLessThan 3254 || CR == APFloat::cmpUnordered, E); 3255 } 3256 } 3257 3258 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 3259 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) { 3260 LValue LHSValue; 3261 if (!EvaluatePointer(E->getLHS(), LHSValue, Info)) 3262 return false; 3263 3264 LValue RHSValue; 3265 if (!EvaluatePointer(E->getRHS(), RHSValue, Info)) 3266 return false; 3267 3268 // Reject differing bases from the normal codepath; we special-case 3269 // comparisons to null. 3270 if (!HasSameBase(LHSValue, RHSValue)) { 3271 // Inequalities and subtractions between unrelated pointers have 3272 // unspecified or undefined behavior. 3273 if (!E->isEqualityOp()) 3274 return false; 3275 // A constant address may compare equal to the address of a symbol. 3276 // The one exception is that address of an object cannot compare equal 3277 // to a null pointer constant. 3278 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 3279 (!RHSValue.Base && !RHSValue.Offset.isZero())) 3280 return false; 3281 // It's implementation-defined whether distinct literals will have 3282 // distinct addresses. In clang, we do not guarantee the addresses are 3283 // distinct. However, we do know that the address of a literal will be 3284 // non-null. 3285 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 3286 LHSValue.Base && RHSValue.Base) 3287 return false; 3288 // We can't tell whether weak symbols will end up pointing to the same 3289 // object. 3290 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 3291 return false; 3292 // Pointers with different bases cannot represent the same object. 3293 // (Note that clang defaults to -fmerge-all-constants, which can 3294 // lead to inconsistent results for comparisons involving the address 3295 // of a constant; this generally doesn't matter in practice.) 3296 return Success(E->getOpcode() == BO_NE, E); 3297 } 3298 3299 // FIXME: Implement the C++11 restrictions: 3300 // - Pointer subtractions must be on elements of the same array. 3301 // - Pointer comparisons must be between members with the same access. 3302 3303 if (E->getOpcode() == BO_Sub) { 3304 QualType Type = E->getLHS()->getType(); 3305 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 3306 3307 CharUnits ElementSize; 3308 if (!HandleSizeof(Info, ElementType, ElementSize)) 3309 return false; 3310 3311 CharUnits Diff = LHSValue.getLValueOffset() - 3312 RHSValue.getLValueOffset(); 3313 return Success(Diff / ElementSize, E); 3314 } 3315 3316 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 3317 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 3318 switch (E->getOpcode()) { 3319 default: llvm_unreachable("missing comparison operator"); 3320 case BO_LT: return Success(LHSOffset < RHSOffset, E); 3321 case BO_GT: return Success(LHSOffset > RHSOffset, E); 3322 case BO_LE: return Success(LHSOffset <= RHSOffset, E); 3323 case BO_GE: return Success(LHSOffset >= RHSOffset, E); 3324 case BO_EQ: return Success(LHSOffset == RHSOffset, E); 3325 case BO_NE: return Success(LHSOffset != RHSOffset, E); 3326 } 3327 } 3328 } 3329 if (!LHSTy->isIntegralOrEnumerationType() || 3330 !RHSTy->isIntegralOrEnumerationType()) { 3331 // We can't continue from here for non-integral types. 3332 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 3333 } 3334 3335 // The LHS of a constant expr is always evaluated and needed. 3336 CCValue LHSVal; 3337 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info)) 3338 return false; // error in subexpression. 3339 3340 if (!Visit(E->getRHS())) 3341 return false; 3342 CCValue &RHSVal = Result; 3343 3344 // Handle cases like (unsigned long)&a + 4. 3345 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 3346 CharUnits AdditionalOffset = CharUnits::fromQuantity( 3347 RHSVal.getInt().getZExtValue()); 3348 if (E->getOpcode() == BO_Add) 3349 LHSVal.getLValueOffset() += AdditionalOffset; 3350 else 3351 LHSVal.getLValueOffset() -= AdditionalOffset; 3352 Result = LHSVal; 3353 return true; 3354 } 3355 3356 // Handle cases like 4 + (unsigned long)&a 3357 if (E->getOpcode() == BO_Add && 3358 RHSVal.isLValue() && LHSVal.isInt()) { 3359 RHSVal.getLValueOffset() += CharUnits::fromQuantity( 3360 LHSVal.getInt().getZExtValue()); 3361 // Note that RHSVal is Result. 3362 return true; 3363 } 3364 3365 // All the following cases expect both operands to be an integer 3366 if (!LHSVal.isInt() || !RHSVal.isInt()) 3367 return false; 3368 3369 APSInt &LHS = LHSVal.getInt(); 3370 APSInt &RHS = RHSVal.getInt(); 3371 3372 switch (E->getOpcode()) { 3373 default: 3374 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 3375 case BO_Mul: return Success(LHS * RHS, E); 3376 case BO_Add: return Success(LHS + RHS, E); 3377 case BO_Sub: return Success(LHS - RHS, E); 3378 case BO_And: return Success(LHS & RHS, E); 3379 case BO_Xor: return Success(LHS ^ RHS, E); 3380 case BO_Or: return Success(LHS | RHS, E); 3381 case BO_Div: 3382 if (RHS == 0) 3383 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 3384 return Success(LHS / RHS, E); 3385 case BO_Rem: 3386 if (RHS == 0) 3387 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 3388 return Success(LHS % RHS, E); 3389 case BO_Shl: { 3390 // During constant-folding, a negative shift is an opposite shift. 3391 if (RHS.isSigned() && RHS.isNegative()) { 3392 RHS = -RHS; 3393 goto shift_right; 3394 } 3395 3396 shift_left: 3397 unsigned SA 3398 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 3399 return Success(LHS << SA, E); 3400 } 3401 case BO_Shr: { 3402 // During constant-folding, a negative shift is an opposite shift. 3403 if (RHS.isSigned() && RHS.isNegative()) { 3404 RHS = -RHS; 3405 goto shift_left; 3406 } 3407 3408 shift_right: 3409 unsigned SA = 3410 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 3411 return Success(LHS >> SA, E); 3412 } 3413 3414 case BO_LT: return Success(LHS < RHS, E); 3415 case BO_GT: return Success(LHS > RHS, E); 3416 case BO_LE: return Success(LHS <= RHS, E); 3417 case BO_GE: return Success(LHS >= RHS, E); 3418 case BO_EQ: return Success(LHS == RHS, E); 3419 case BO_NE: return Success(LHS != RHS, E); 3420 } 3421 } 3422 3423 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) { 3424 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3425 // the result is the size of the referenced type." 3426 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3427 // result shall be the alignment of the referenced type." 3428 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 3429 T = Ref->getPointeeType(); 3430 3431 // __alignof is defined to return the preferred alignment. 3432 return Info.Ctx.toCharUnitsFromBits( 3433 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 3434 } 3435 3436 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) { 3437 E = E->IgnoreParens(); 3438 3439 // alignof decl is always accepted, even if it doesn't make sense: we default 3440 // to 1 in those cases. 3441 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3442 return Info.Ctx.getDeclAlign(DRE->getDecl(), 3443 /*RefAsPointee*/true); 3444 3445 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 3446 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 3447 /*RefAsPointee*/true); 3448 3449 return GetAlignOfType(E->getType()); 3450 } 3451 3452 3453 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 3454 /// a result as the expression's type. 3455 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 3456 const UnaryExprOrTypeTraitExpr *E) { 3457 switch(E->getKind()) { 3458 case UETT_AlignOf: { 3459 if (E->isArgumentType()) 3460 return Success(GetAlignOfType(E->getArgumentType()), E); 3461 else 3462 return Success(GetAlignOfExpr(E->getArgumentExpr()), E); 3463 } 3464 3465 case UETT_VecStep: { 3466 QualType Ty = E->getTypeOfArgument(); 3467 3468 if (Ty->isVectorType()) { 3469 unsigned n = Ty->getAs<VectorType>()->getNumElements(); 3470 3471 // The vec_step built-in functions that take a 3-component 3472 // vector return 4. (OpenCL 1.1 spec 6.11.12) 3473 if (n == 3) 3474 n = 4; 3475 3476 return Success(n, E); 3477 } else 3478 return Success(1, E); 3479 } 3480 3481 case UETT_SizeOf: { 3482 QualType SrcTy = E->getTypeOfArgument(); 3483 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3484 // the result is the size of the referenced type." 3485 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3486 // result shall be the alignment of the referenced type." 3487 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 3488 SrcTy = Ref->getPointeeType(); 3489 3490 CharUnits Sizeof; 3491 if (!HandleSizeof(Info, SrcTy, Sizeof)) 3492 return false; 3493 return Success(Sizeof, E); 3494 } 3495 } 3496 3497 llvm_unreachable("unknown expr/type trait"); 3498 return false; 3499 } 3500 3501 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 3502 CharUnits Result; 3503 unsigned n = OOE->getNumComponents(); 3504 if (n == 0) 3505 return false; 3506 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 3507 for (unsigned i = 0; i != n; ++i) { 3508 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i); 3509 switch (ON.getKind()) { 3510 case OffsetOfExpr::OffsetOfNode::Array: { 3511 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 3512 APSInt IdxResult; 3513 if (!EvaluateInteger(Idx, IdxResult, Info)) 3514 return false; 3515 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 3516 if (!AT) 3517 return false; 3518 CurrentType = AT->getElementType(); 3519 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 3520 Result += IdxResult.getSExtValue() * ElementSize; 3521 break; 3522 } 3523 3524 case OffsetOfExpr::OffsetOfNode::Field: { 3525 FieldDecl *MemberDecl = ON.getField(); 3526 const RecordType *RT = CurrentType->getAs<RecordType>(); 3527 if (!RT) 3528 return false; 3529 RecordDecl *RD = RT->getDecl(); 3530 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 3531 unsigned i = MemberDecl->getFieldIndex(); 3532 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 3533 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 3534 CurrentType = MemberDecl->getType().getNonReferenceType(); 3535 break; 3536 } 3537 3538 case OffsetOfExpr::OffsetOfNode::Identifier: 3539 llvm_unreachable("dependent __builtin_offsetof"); 3540 return false; 3541 3542 case OffsetOfExpr::OffsetOfNode::Base: { 3543 CXXBaseSpecifier *BaseSpec = ON.getBase(); 3544 if (BaseSpec->isVirtual()) 3545 return false; 3546 3547 // Find the layout of the class whose base we are looking into. 3548 const RecordType *RT = CurrentType->getAs<RecordType>(); 3549 if (!RT) 3550 return false; 3551 RecordDecl *RD = RT->getDecl(); 3552 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 3553 3554 // Find the base class itself. 3555 CurrentType = BaseSpec->getType(); 3556 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 3557 if (!BaseRT) 3558 return false; 3559 3560 // Add the offset to the base. 3561 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 3562 break; 3563 } 3564 } 3565 } 3566 return Success(Result, OOE); 3567 } 3568 3569 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 3570 if (E->getOpcode() == UO_LNot) { 3571 // LNot's operand isn't necessarily an integer, so we handle it specially. 3572 bool bres; 3573 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 3574 return false; 3575 return Success(!bres, E); 3576 } 3577 3578 // Only handle integral operations... 3579 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType()) 3580 return false; 3581 3582 // Get the operand value. 3583 CCValue Val; 3584 if (!Evaluate(Val, Info, E->getSubExpr())) 3585 return false; 3586 3587 switch (E->getOpcode()) { 3588 default: 3589 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 3590 // See C99 6.6p3. 3591 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 3592 case UO_Extension: 3593 // FIXME: Should extension allow i-c-e extension expressions in its scope? 3594 // If so, we could clear the diagnostic ID. 3595 return Success(Val, E); 3596 case UO_Plus: 3597 // The result is just the value. 3598 return Success(Val, E); 3599 case UO_Minus: 3600 if (!Val.isInt()) return false; 3601 return Success(-Val.getInt(), E); 3602 case UO_Not: 3603 if (!Val.isInt()) return false; 3604 return Success(~Val.getInt(), E); 3605 } 3606 } 3607 3608 /// HandleCast - This is used to evaluate implicit or explicit casts where the 3609 /// result type is integer. 3610 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 3611 const Expr *SubExpr = E->getSubExpr(); 3612 QualType DestType = E->getType(); 3613 QualType SrcType = SubExpr->getType(); 3614 3615 switch (E->getCastKind()) { 3616 case CK_BaseToDerived: 3617 case CK_DerivedToBase: 3618 case CK_UncheckedDerivedToBase: 3619 case CK_Dynamic: 3620 case CK_ToUnion: 3621 case CK_ArrayToPointerDecay: 3622 case CK_FunctionToPointerDecay: 3623 case CK_NullToPointer: 3624 case CK_NullToMemberPointer: 3625 case CK_BaseToDerivedMemberPointer: 3626 case CK_DerivedToBaseMemberPointer: 3627 case CK_ConstructorConversion: 3628 case CK_IntegralToPointer: 3629 case CK_ToVoid: 3630 case CK_VectorSplat: 3631 case CK_IntegralToFloating: 3632 case CK_FloatingCast: 3633 case CK_CPointerToObjCPointerCast: 3634 case CK_BlockPointerToObjCPointerCast: 3635 case CK_AnyPointerToBlockPointerCast: 3636 case CK_ObjCObjectLValueCast: 3637 case CK_FloatingRealToComplex: 3638 case CK_FloatingComplexToReal: 3639 case CK_FloatingComplexCast: 3640 case CK_FloatingComplexToIntegralComplex: 3641 case CK_IntegralRealToComplex: 3642 case CK_IntegralComplexCast: 3643 case CK_IntegralComplexToFloatingComplex: 3644 llvm_unreachable("invalid cast kind for integral value"); 3645 3646 case CK_BitCast: 3647 case CK_Dependent: 3648 case CK_LValueBitCast: 3649 case CK_UserDefinedConversion: 3650 case CK_ARCProduceObject: 3651 case CK_ARCConsumeObject: 3652 case CK_ARCReclaimReturnedObject: 3653 case CK_ARCExtendBlockObject: 3654 return false; 3655 3656 case CK_LValueToRValue: 3657 case CK_NoOp: 3658 return ExprEvaluatorBaseTy::VisitCastExpr(E); 3659 3660 case CK_MemberPointerToBoolean: 3661 case CK_PointerToBoolean: 3662 case CK_IntegralToBoolean: 3663 case CK_FloatingToBoolean: 3664 case CK_FloatingComplexToBoolean: 3665 case CK_IntegralComplexToBoolean: { 3666 bool BoolResult; 3667 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 3668 return false; 3669 return Success(BoolResult, E); 3670 } 3671 3672 case CK_IntegralCast: { 3673 if (!Visit(SubExpr)) 3674 return false; 3675 3676 if (!Result.isInt()) { 3677 // Only allow casts of lvalues if they are lossless. 3678 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 3679 } 3680 3681 return Success(HandleIntToIntCast(DestType, SrcType, 3682 Result.getInt(), Info.Ctx), E); 3683 } 3684 3685 case CK_PointerToIntegral: { 3686 LValue LV; 3687 if (!EvaluatePointer(SubExpr, LV, Info)) 3688 return false; 3689 3690 if (LV.getLValueBase()) { 3691 // Only allow based lvalue casts if they are lossless. 3692 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 3693 return false; 3694 3695 LV.Designator.setInvalid(); 3696 LV.moveInto(Result); 3697 return true; 3698 } 3699 3700 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(), 3701 SrcType); 3702 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E); 3703 } 3704 3705 case CK_IntegralComplexToReal: { 3706 ComplexValue C; 3707 if (!EvaluateComplex(SubExpr, C, Info)) 3708 return false; 3709 return Success(C.getComplexIntReal(), E); 3710 } 3711 3712 case CK_FloatingToIntegral: { 3713 APFloat F(0.0); 3714 if (!EvaluateFloat(SubExpr, F, Info)) 3715 return false; 3716 3717 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E); 3718 } 3719 } 3720 3721 llvm_unreachable("unknown cast resulting in integral value"); 3722 return false; 3723 } 3724 3725 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 3726 if (E->getSubExpr()->getType()->isAnyComplexType()) { 3727 ComplexValue LV; 3728 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt()) 3729 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 3730 return Success(LV.getComplexIntReal(), E); 3731 } 3732 3733 return Visit(E->getSubExpr()); 3734 } 3735 3736 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 3737 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 3738 ComplexValue LV; 3739 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt()) 3740 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 3741 return Success(LV.getComplexIntImag(), E); 3742 } 3743 3744 VisitIgnoredValue(E->getSubExpr()); 3745 return Success(0, E); 3746 } 3747 3748 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 3749 return Success(E->getPackLength(), E); 3750 } 3751 3752 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 3753 return Success(E->getValue(), E); 3754 } 3755 3756 //===----------------------------------------------------------------------===// 3757 // Float Evaluation 3758 //===----------------------------------------------------------------------===// 3759 3760 namespace { 3761 class FloatExprEvaluator 3762 : public ExprEvaluatorBase<FloatExprEvaluator, bool> { 3763 APFloat &Result; 3764 public: 3765 FloatExprEvaluator(EvalInfo &info, APFloat &result) 3766 : ExprEvaluatorBaseTy(info), Result(result) {} 3767 3768 bool Success(const CCValue &V, const Expr *e) { 3769 Result = V.getFloat(); 3770 return true; 3771 } 3772 bool Error(const Stmt *S) { 3773 return false; 3774 } 3775 3776 bool ValueInitialization(const Expr *E) { 3777 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 3778 return true; 3779 } 3780 3781 bool VisitCallExpr(const CallExpr *E); 3782 3783 bool VisitUnaryOperator(const UnaryOperator *E); 3784 bool VisitBinaryOperator(const BinaryOperator *E); 3785 bool VisitFloatingLiteral(const FloatingLiteral *E); 3786 bool VisitCastExpr(const CastExpr *E); 3787 3788 bool VisitUnaryReal(const UnaryOperator *E); 3789 bool VisitUnaryImag(const UnaryOperator *E); 3790 3791 // FIXME: Missing: array subscript of vector, member of vector, 3792 // ImplicitValueInitExpr 3793 }; 3794 } // end anonymous namespace 3795 3796 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 3797 assert(E->isRValue() && E->getType()->isRealFloatingType()); 3798 return FloatExprEvaluator(Info, Result).Visit(E); 3799 } 3800 3801 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 3802 QualType ResultTy, 3803 const Expr *Arg, 3804 bool SNaN, 3805 llvm::APFloat &Result) { 3806 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 3807 if (!S) return false; 3808 3809 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 3810 3811 llvm::APInt fill; 3812 3813 // Treat empty strings as if they were zero. 3814 if (S->getString().empty()) 3815 fill = llvm::APInt(32, 0); 3816 else if (S->getString().getAsInteger(0, fill)) 3817 return false; 3818 3819 if (SNaN) 3820 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 3821 else 3822 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 3823 return true; 3824 } 3825 3826 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 3827 switch (E->isBuiltinCall()) { 3828 default: 3829 return ExprEvaluatorBaseTy::VisitCallExpr(E); 3830 3831 case Builtin::BI__builtin_huge_val: 3832 case Builtin::BI__builtin_huge_valf: 3833 case Builtin::BI__builtin_huge_vall: 3834 case Builtin::BI__builtin_inf: 3835 case Builtin::BI__builtin_inff: 3836 case Builtin::BI__builtin_infl: { 3837 const llvm::fltSemantics &Sem = 3838 Info.Ctx.getFloatTypeSemantics(E->getType()); 3839 Result = llvm::APFloat::getInf(Sem); 3840 return true; 3841 } 3842 3843 case Builtin::BI__builtin_nans: 3844 case Builtin::BI__builtin_nansf: 3845 case Builtin::BI__builtin_nansl: 3846 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 3847 true, Result); 3848 3849 case Builtin::BI__builtin_nan: 3850 case Builtin::BI__builtin_nanf: 3851 case Builtin::BI__builtin_nanl: 3852 // If this is __builtin_nan() turn this into a nan, otherwise we 3853 // can't constant fold it. 3854 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 3855 false, Result); 3856 3857 case Builtin::BI__builtin_fabs: 3858 case Builtin::BI__builtin_fabsf: 3859 case Builtin::BI__builtin_fabsl: 3860 if (!EvaluateFloat(E->getArg(0), Result, Info)) 3861 return false; 3862 3863 if (Result.isNegative()) 3864 Result.changeSign(); 3865 return true; 3866 3867 case Builtin::BI__builtin_copysign: 3868 case Builtin::BI__builtin_copysignf: 3869 case Builtin::BI__builtin_copysignl: { 3870 APFloat RHS(0.); 3871 if (!EvaluateFloat(E->getArg(0), Result, Info) || 3872 !EvaluateFloat(E->getArg(1), RHS, Info)) 3873 return false; 3874 Result.copySign(RHS); 3875 return true; 3876 } 3877 } 3878 } 3879 3880 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 3881 if (E->getSubExpr()->getType()->isAnyComplexType()) { 3882 ComplexValue CV; 3883 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 3884 return false; 3885 Result = CV.FloatReal; 3886 return true; 3887 } 3888 3889 return Visit(E->getSubExpr()); 3890 } 3891 3892 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 3893 if (E->getSubExpr()->getType()->isAnyComplexType()) { 3894 ComplexValue CV; 3895 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 3896 return false; 3897 Result = CV.FloatImag; 3898 return true; 3899 } 3900 3901 VisitIgnoredValue(E->getSubExpr()); 3902 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 3903 Result = llvm::APFloat::getZero(Sem); 3904 return true; 3905 } 3906 3907 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 3908 switch (E->getOpcode()) { 3909 default: return false; 3910 case UO_Plus: 3911 return EvaluateFloat(E->getSubExpr(), Result, Info); 3912 case UO_Minus: 3913 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 3914 return false; 3915 Result.changeSign(); 3916 return true; 3917 } 3918 } 3919 3920 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 3921 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 3922 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 3923 3924 APFloat RHS(0.0); 3925 if (!EvaluateFloat(E->getLHS(), Result, Info)) 3926 return false; 3927 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 3928 return false; 3929 3930 switch (E->getOpcode()) { 3931 default: return false; 3932 case BO_Mul: 3933 Result.multiply(RHS, APFloat::rmNearestTiesToEven); 3934 return true; 3935 case BO_Add: 3936 Result.add(RHS, APFloat::rmNearestTiesToEven); 3937 return true; 3938 case BO_Sub: 3939 Result.subtract(RHS, APFloat::rmNearestTiesToEven); 3940 return true; 3941 case BO_Div: 3942 Result.divide(RHS, APFloat::rmNearestTiesToEven); 3943 return true; 3944 } 3945 } 3946 3947 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 3948 Result = E->getValue(); 3949 return true; 3950 } 3951 3952 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 3953 const Expr* SubExpr = E->getSubExpr(); 3954 3955 switch (E->getCastKind()) { 3956 default: 3957 return ExprEvaluatorBaseTy::VisitCastExpr(E); 3958 3959 case CK_IntegralToFloating: { 3960 APSInt IntResult; 3961 if (!EvaluateInteger(SubExpr, IntResult, Info)) 3962 return false; 3963 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(), 3964 IntResult, Info.Ctx); 3965 return true; 3966 } 3967 3968 case CK_FloatingCast: { 3969 if (!Visit(SubExpr)) 3970 return false; 3971 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(), 3972 Result, Info.Ctx); 3973 return true; 3974 } 3975 3976 case CK_FloatingComplexToReal: { 3977 ComplexValue V; 3978 if (!EvaluateComplex(SubExpr, V, Info)) 3979 return false; 3980 Result = V.getComplexFloatReal(); 3981 return true; 3982 } 3983 } 3984 3985 return false; 3986 } 3987 3988 //===----------------------------------------------------------------------===// 3989 // Complex Evaluation (for float and integer) 3990 //===----------------------------------------------------------------------===// 3991 3992 namespace { 3993 class ComplexExprEvaluator 3994 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> { 3995 ComplexValue &Result; 3996 3997 public: 3998 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 3999 : ExprEvaluatorBaseTy(info), Result(Result) {} 4000 4001 bool Success(const CCValue &V, const Expr *e) { 4002 Result.setFrom(V); 4003 return true; 4004 } 4005 bool Error(const Expr *E) { 4006 return false; 4007 } 4008 4009 //===--------------------------------------------------------------------===// 4010 // Visitor Methods 4011 //===--------------------------------------------------------------------===// 4012 4013 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 4014 4015 bool VisitCastExpr(const CastExpr *E); 4016 4017 bool VisitBinaryOperator(const BinaryOperator *E); 4018 bool VisitUnaryOperator(const UnaryOperator *E); 4019 // FIXME Missing: ImplicitValueInitExpr, InitListExpr 4020 }; 4021 } // end anonymous namespace 4022 4023 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 4024 EvalInfo &Info) { 4025 assert(E->isRValue() && E->getType()->isAnyComplexType()); 4026 return ComplexExprEvaluator(Info, Result).Visit(E); 4027 } 4028 4029 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 4030 const Expr* SubExpr = E->getSubExpr(); 4031 4032 if (SubExpr->getType()->isRealFloatingType()) { 4033 Result.makeComplexFloat(); 4034 APFloat &Imag = Result.FloatImag; 4035 if (!EvaluateFloat(SubExpr, Imag, Info)) 4036 return false; 4037 4038 Result.FloatReal = APFloat(Imag.getSemantics()); 4039 return true; 4040 } else { 4041 assert(SubExpr->getType()->isIntegerType() && 4042 "Unexpected imaginary literal."); 4043 4044 Result.makeComplexInt(); 4045 APSInt &Imag = Result.IntImag; 4046 if (!EvaluateInteger(SubExpr, Imag, Info)) 4047 return false; 4048 4049 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 4050 return true; 4051 } 4052 } 4053 4054 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 4055 4056 switch (E->getCastKind()) { 4057 case CK_BitCast: 4058 case CK_BaseToDerived: 4059 case CK_DerivedToBase: 4060 case CK_UncheckedDerivedToBase: 4061 case CK_Dynamic: 4062 case CK_ToUnion: 4063 case CK_ArrayToPointerDecay: 4064 case CK_FunctionToPointerDecay: 4065 case CK_NullToPointer: 4066 case CK_NullToMemberPointer: 4067 case CK_BaseToDerivedMemberPointer: 4068 case CK_DerivedToBaseMemberPointer: 4069 case CK_MemberPointerToBoolean: 4070 case CK_ConstructorConversion: 4071 case CK_IntegralToPointer: 4072 case CK_PointerToIntegral: 4073 case CK_PointerToBoolean: 4074 case CK_ToVoid: 4075 case CK_VectorSplat: 4076 case CK_IntegralCast: 4077 case CK_IntegralToBoolean: 4078 case CK_IntegralToFloating: 4079 case CK_FloatingToIntegral: 4080 case CK_FloatingToBoolean: 4081 case CK_FloatingCast: 4082 case CK_CPointerToObjCPointerCast: 4083 case CK_BlockPointerToObjCPointerCast: 4084 case CK_AnyPointerToBlockPointerCast: 4085 case CK_ObjCObjectLValueCast: 4086 case CK_FloatingComplexToReal: 4087 case CK_FloatingComplexToBoolean: 4088 case CK_IntegralComplexToReal: 4089 case CK_IntegralComplexToBoolean: 4090 case CK_ARCProduceObject: 4091 case CK_ARCConsumeObject: 4092 case CK_ARCReclaimReturnedObject: 4093 case CK_ARCExtendBlockObject: 4094 llvm_unreachable("invalid cast kind for complex value"); 4095 4096 case CK_LValueToRValue: 4097 case CK_NoOp: 4098 return ExprEvaluatorBaseTy::VisitCastExpr(E); 4099 4100 case CK_Dependent: 4101 case CK_LValueBitCast: 4102 case CK_UserDefinedConversion: 4103 return false; 4104 4105 case CK_FloatingRealToComplex: { 4106 APFloat &Real = Result.FloatReal; 4107 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 4108 return false; 4109 4110 Result.makeComplexFloat(); 4111 Result.FloatImag = APFloat(Real.getSemantics()); 4112 return true; 4113 } 4114 4115 case CK_FloatingComplexCast: { 4116 if (!Visit(E->getSubExpr())) 4117 return false; 4118 4119 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 4120 QualType From 4121 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 4122 4123 Result.FloatReal 4124 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx); 4125 Result.FloatImag 4126 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx); 4127 return true; 4128 } 4129 4130 case CK_FloatingComplexToIntegralComplex: { 4131 if (!Visit(E->getSubExpr())) 4132 return false; 4133 4134 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 4135 QualType From 4136 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 4137 Result.makeComplexInt(); 4138 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx); 4139 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx); 4140 return true; 4141 } 4142 4143 case CK_IntegralRealToComplex: { 4144 APSInt &Real = Result.IntReal; 4145 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 4146 return false; 4147 4148 Result.makeComplexInt(); 4149 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 4150 return true; 4151 } 4152 4153 case CK_IntegralComplexCast: { 4154 if (!Visit(E->getSubExpr())) 4155 return false; 4156 4157 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 4158 QualType From 4159 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 4160 4161 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx); 4162 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx); 4163 return true; 4164 } 4165 4166 case CK_IntegralComplexToFloatingComplex: { 4167 if (!Visit(E->getSubExpr())) 4168 return false; 4169 4170 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 4171 QualType From 4172 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 4173 Result.makeComplexFloat(); 4174 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx); 4175 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx); 4176 return true; 4177 } 4178 } 4179 4180 llvm_unreachable("unknown cast resulting in complex value"); 4181 return false; 4182 } 4183 4184 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 4185 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 4186 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 4187 4188 if (!Visit(E->getLHS())) 4189 return false; 4190 4191 ComplexValue RHS; 4192 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 4193 return false; 4194 4195 assert(Result.isComplexFloat() == RHS.isComplexFloat() && 4196 "Invalid operands to binary operator."); 4197 switch (E->getOpcode()) { 4198 default: return false; 4199 case BO_Add: 4200 if (Result.isComplexFloat()) { 4201 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 4202 APFloat::rmNearestTiesToEven); 4203 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 4204 APFloat::rmNearestTiesToEven); 4205 } else { 4206 Result.getComplexIntReal() += RHS.getComplexIntReal(); 4207 Result.getComplexIntImag() += RHS.getComplexIntImag(); 4208 } 4209 break; 4210 case BO_Sub: 4211 if (Result.isComplexFloat()) { 4212 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 4213 APFloat::rmNearestTiesToEven); 4214 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 4215 APFloat::rmNearestTiesToEven); 4216 } else { 4217 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 4218 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 4219 } 4220 break; 4221 case BO_Mul: 4222 if (Result.isComplexFloat()) { 4223 ComplexValue LHS = Result; 4224 APFloat &LHS_r = LHS.getComplexFloatReal(); 4225 APFloat &LHS_i = LHS.getComplexFloatImag(); 4226 APFloat &RHS_r = RHS.getComplexFloatReal(); 4227 APFloat &RHS_i = RHS.getComplexFloatImag(); 4228 4229 APFloat Tmp = LHS_r; 4230 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 4231 Result.getComplexFloatReal() = Tmp; 4232 Tmp = LHS_i; 4233 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 4234 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven); 4235 4236 Tmp = LHS_r; 4237 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 4238 Result.getComplexFloatImag() = Tmp; 4239 Tmp = LHS_i; 4240 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 4241 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven); 4242 } else { 4243 ComplexValue LHS = Result; 4244 Result.getComplexIntReal() = 4245 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 4246 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 4247 Result.getComplexIntImag() = 4248 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 4249 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 4250 } 4251 break; 4252 case BO_Div: 4253 if (Result.isComplexFloat()) { 4254 ComplexValue LHS = Result; 4255 APFloat &LHS_r = LHS.getComplexFloatReal(); 4256 APFloat &LHS_i = LHS.getComplexFloatImag(); 4257 APFloat &RHS_r = RHS.getComplexFloatReal(); 4258 APFloat &RHS_i = RHS.getComplexFloatImag(); 4259 APFloat &Res_r = Result.getComplexFloatReal(); 4260 APFloat &Res_i = Result.getComplexFloatImag(); 4261 4262 APFloat Den = RHS_r; 4263 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven); 4264 APFloat Tmp = RHS_i; 4265 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 4266 Den.add(Tmp, APFloat::rmNearestTiesToEven); 4267 4268 Res_r = LHS_r; 4269 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven); 4270 Tmp = LHS_i; 4271 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 4272 Res_r.add(Tmp, APFloat::rmNearestTiesToEven); 4273 Res_r.divide(Den, APFloat::rmNearestTiesToEven); 4274 4275 Res_i = LHS_i; 4276 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven); 4277 Tmp = LHS_r; 4278 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 4279 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven); 4280 Res_i.divide(Den, APFloat::rmNearestTiesToEven); 4281 } else { 4282 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) { 4283 // FIXME: what about diagnostics? 4284 return false; 4285 } 4286 ComplexValue LHS = Result; 4287 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 4288 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 4289 Result.getComplexIntReal() = 4290 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 4291 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 4292 Result.getComplexIntImag() = 4293 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 4294 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 4295 } 4296 break; 4297 } 4298 4299 return true; 4300 } 4301 4302 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 4303 // Get the operand value into 'Result'. 4304 if (!Visit(E->getSubExpr())) 4305 return false; 4306 4307 switch (E->getOpcode()) { 4308 default: 4309 // FIXME: what about diagnostics? 4310 return false; 4311 case UO_Extension: 4312 return true; 4313 case UO_Plus: 4314 // The result is always just the subexpr. 4315 return true; 4316 case UO_Minus: 4317 if (Result.isComplexFloat()) { 4318 Result.getComplexFloatReal().changeSign(); 4319 Result.getComplexFloatImag().changeSign(); 4320 } 4321 else { 4322 Result.getComplexIntReal() = -Result.getComplexIntReal(); 4323 Result.getComplexIntImag() = -Result.getComplexIntImag(); 4324 } 4325 return true; 4326 case UO_Not: 4327 if (Result.isComplexFloat()) 4328 Result.getComplexFloatImag().changeSign(); 4329 else 4330 Result.getComplexIntImag() = -Result.getComplexIntImag(); 4331 return true; 4332 } 4333 } 4334 4335 //===----------------------------------------------------------------------===// 4336 // Void expression evaluation, primarily for a cast to void on the LHS of a 4337 // comma operator 4338 //===----------------------------------------------------------------------===// 4339 4340 namespace { 4341 class VoidExprEvaluator 4342 : public ExprEvaluatorBase<VoidExprEvaluator, bool> { 4343 public: 4344 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 4345 4346 bool Success(const CCValue &V, const Expr *e) { return true; } 4347 bool Error(const Expr *E) { return false; } 4348 4349 bool VisitCastExpr(const CastExpr *E) { 4350 switch (E->getCastKind()) { 4351 default: 4352 return ExprEvaluatorBaseTy::VisitCastExpr(E); 4353 case CK_ToVoid: 4354 VisitIgnoredValue(E->getSubExpr()); 4355 return true; 4356 } 4357 } 4358 }; 4359 } // end anonymous namespace 4360 4361 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 4362 assert(E->isRValue() && E->getType()->isVoidType()); 4363 return VoidExprEvaluator(Info).Visit(E); 4364 } 4365 4366 //===----------------------------------------------------------------------===// 4367 // Top level Expr::EvaluateAsRValue method. 4368 //===----------------------------------------------------------------------===// 4369 4370 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) { 4371 // In C, function designators are not lvalues, but we evaluate them as if they 4372 // are. 4373 if (E->isGLValue() || E->getType()->isFunctionType()) { 4374 LValue LV; 4375 if (!EvaluateLValue(E, LV, Info)) 4376 return false; 4377 LV.moveInto(Result); 4378 } else if (E->getType()->isVectorType()) { 4379 if (!EvaluateVector(E, Result, Info)) 4380 return false; 4381 } else if (E->getType()->isIntegralOrEnumerationType()) { 4382 if (!IntExprEvaluator(Info, Result).Visit(E)) 4383 return false; 4384 } else if (E->getType()->hasPointerRepresentation()) { 4385 LValue LV; 4386 if (!EvaluatePointer(E, LV, Info)) 4387 return false; 4388 LV.moveInto(Result); 4389 } else if (E->getType()->isRealFloatingType()) { 4390 llvm::APFloat F(0.0); 4391 if (!EvaluateFloat(E, F, Info)) 4392 return false; 4393 Result = CCValue(F); 4394 } else if (E->getType()->isAnyComplexType()) { 4395 ComplexValue C; 4396 if (!EvaluateComplex(E, C, Info)) 4397 return false; 4398 C.moveInto(Result); 4399 } else if (E->getType()->isMemberPointerType()) { 4400 MemberPtr P; 4401 if (!EvaluateMemberPointer(E, P, Info)) 4402 return false; 4403 P.moveInto(Result); 4404 return true; 4405 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) { 4406 LValue LV; 4407 LV.set(E, Info.CurrentCall); 4408 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info)) 4409 return false; 4410 Result = Info.CurrentCall->Temporaries[E]; 4411 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) { 4412 LValue LV; 4413 LV.set(E, Info.CurrentCall); 4414 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info)) 4415 return false; 4416 Result = Info.CurrentCall->Temporaries[E]; 4417 } else if (E->getType()->isVoidType()) { 4418 if (!EvaluateVoid(E, Info)) 4419 return false; 4420 } else 4421 return false; 4422 4423 return true; 4424 } 4425 4426 /// EvaluateConstantExpression - Evaluate an expression as a constant expression 4427 /// in-place in an APValue. In some cases, the in-place evaluation is essential, 4428 /// since later initializers for an object can indirectly refer to subobjects 4429 /// which were initialized earlier. 4430 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info, 4431 const LValue &This, const Expr *E) { 4432 if (E->isRValue() && E->getType()->isLiteralType()) { 4433 // Evaluate arrays and record types in-place, so that later initializers can 4434 // refer to earlier-initialized members of the object. 4435 if (E->getType()->isArrayType()) 4436 return EvaluateArray(E, This, Result, Info); 4437 else if (E->getType()->isRecordType()) 4438 return EvaluateRecord(E, This, Result, Info); 4439 } 4440 4441 // For any other type, in-place evaluation is unimportant. 4442 CCValue CoreConstResult; 4443 return Evaluate(CoreConstResult, Info, E) && 4444 CheckConstantExpression(CoreConstResult, Result); 4445 } 4446 4447 4448 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 4449 /// any crazy technique (that has nothing to do with language standards) that 4450 /// we want to. If this function returns true, it returns the folded constant 4451 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 4452 /// will be applied to the result. 4453 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 4454 // FIXME: Evaluating initializers for large arrays can cause performance 4455 // problems, and we don't use such values yet. Once we have a more efficient 4456 // array representation, this should be reinstated, and used by CodeGen. 4457 // The same problem affects large records. 4458 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 4459 !Ctx.getLangOptions().CPlusPlus0x) 4460 return false; 4461 4462 EvalInfo Info(Ctx, Result); 4463 4464 // FIXME: If this is the initializer for an lvalue, pass that in. 4465 CCValue Value; 4466 if (!::Evaluate(Value, Info, this)) 4467 return false; 4468 4469 if (isGLValue()) { 4470 LValue LV; 4471 LV.setFrom(Value); 4472 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value)) 4473 return false; 4474 } 4475 4476 // Check this core constant expression is a constant expression, and if so, 4477 // convert it to one. 4478 return CheckConstantExpression(Value, Result.Val); 4479 } 4480 4481 bool Expr::EvaluateAsBooleanCondition(bool &Result, 4482 const ASTContext &Ctx) const { 4483 EvalResult Scratch; 4484 return EvaluateAsRValue(Scratch, Ctx) && 4485 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()), 4486 Result); 4487 } 4488 4489 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const { 4490 EvalResult ExprResult; 4491 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects || 4492 !ExprResult.Val.isInt()) { 4493 return false; 4494 } 4495 Result = ExprResult.Val.getInt(); 4496 return true; 4497 } 4498 4499 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 4500 EvalInfo Info(Ctx, Result); 4501 4502 LValue LV; 4503 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects && 4504 CheckLValueConstantExpression(LV, Result.Val); 4505 } 4506 4507 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 4508 /// constant folded, but discard the result. 4509 bool Expr::isEvaluatable(const ASTContext &Ctx) const { 4510 EvalResult Result; 4511 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects; 4512 } 4513 4514 bool Expr::HasSideEffects(const ASTContext &Ctx) const { 4515 return HasSideEffect(Ctx).Visit(this); 4516 } 4517 4518 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const { 4519 EvalResult EvalResult; 4520 bool Result = EvaluateAsRValue(EvalResult, Ctx); 4521 (void)Result; 4522 assert(Result && "Could not evaluate expression"); 4523 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 4524 4525 return EvalResult.Val.getInt(); 4526 } 4527 4528 bool Expr::EvalResult::isGlobalLValue() const { 4529 assert(Val.isLValue()); 4530 return IsGlobalLValue(Val.getLValueBase()); 4531 } 4532 4533 4534 /// isIntegerConstantExpr - this recursive routine will test if an expression is 4535 /// an integer constant expression. 4536 4537 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 4538 /// comma, etc 4539 /// 4540 /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof 4541 /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer 4542 /// cast+dereference. 4543 4544 // CheckICE - This function does the fundamental ICE checking: the returned 4545 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation. 4546 // Note that to reduce code duplication, this helper does no evaluation 4547 // itself; the caller checks whether the expression is evaluatable, and 4548 // in the rare cases where CheckICE actually cares about the evaluated 4549 // value, it calls into Evalute. 4550 // 4551 // Meanings of Val: 4552 // 0: This expression is an ICE. 4553 // 1: This expression is not an ICE, but if it isn't evaluated, it's 4554 // a legal subexpression for an ICE. This return value is used to handle 4555 // the comma operator in C99 mode. 4556 // 2: This expression is not an ICE, and is not a legal subexpression for one. 4557 4558 namespace { 4559 4560 struct ICEDiag { 4561 unsigned Val; 4562 SourceLocation Loc; 4563 4564 public: 4565 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {} 4566 ICEDiag() : Val(0) {} 4567 }; 4568 4569 } 4570 4571 static ICEDiag NoDiag() { return ICEDiag(); } 4572 4573 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) { 4574 Expr::EvalResult EVResult; 4575 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 4576 !EVResult.Val.isInt()) { 4577 return ICEDiag(2, E->getLocStart()); 4578 } 4579 return NoDiag(); 4580 } 4581 4582 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { 4583 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 4584 if (!E->getType()->isIntegralOrEnumerationType()) { 4585 return ICEDiag(2, E->getLocStart()); 4586 } 4587 4588 switch (E->getStmtClass()) { 4589 #define ABSTRACT_STMT(Node) 4590 #define STMT(Node, Base) case Expr::Node##Class: 4591 #define EXPR(Node, Base) 4592 #include "clang/AST/StmtNodes.inc" 4593 case Expr::PredefinedExprClass: 4594 case Expr::FloatingLiteralClass: 4595 case Expr::ImaginaryLiteralClass: 4596 case Expr::StringLiteralClass: 4597 case Expr::ArraySubscriptExprClass: 4598 case Expr::MemberExprClass: 4599 case Expr::CompoundAssignOperatorClass: 4600 case Expr::CompoundLiteralExprClass: 4601 case Expr::ExtVectorElementExprClass: 4602 case Expr::DesignatedInitExprClass: 4603 case Expr::ImplicitValueInitExprClass: 4604 case Expr::ParenListExprClass: 4605 case Expr::VAArgExprClass: 4606 case Expr::AddrLabelExprClass: 4607 case Expr::StmtExprClass: 4608 case Expr::CXXMemberCallExprClass: 4609 case Expr::CUDAKernelCallExprClass: 4610 case Expr::CXXDynamicCastExprClass: 4611 case Expr::CXXTypeidExprClass: 4612 case Expr::CXXUuidofExprClass: 4613 case Expr::CXXNullPtrLiteralExprClass: 4614 case Expr::CXXThisExprClass: 4615 case Expr::CXXThrowExprClass: 4616 case Expr::CXXNewExprClass: 4617 case Expr::CXXDeleteExprClass: 4618 case Expr::CXXPseudoDestructorExprClass: 4619 case Expr::UnresolvedLookupExprClass: 4620 case Expr::DependentScopeDeclRefExprClass: 4621 case Expr::CXXConstructExprClass: 4622 case Expr::CXXBindTemporaryExprClass: 4623 case Expr::ExprWithCleanupsClass: 4624 case Expr::CXXTemporaryObjectExprClass: 4625 case Expr::CXXUnresolvedConstructExprClass: 4626 case Expr::CXXDependentScopeMemberExprClass: 4627 case Expr::UnresolvedMemberExprClass: 4628 case Expr::ObjCStringLiteralClass: 4629 case Expr::ObjCEncodeExprClass: 4630 case Expr::ObjCMessageExprClass: 4631 case Expr::ObjCSelectorExprClass: 4632 case Expr::ObjCProtocolExprClass: 4633 case Expr::ObjCIvarRefExprClass: 4634 case Expr::ObjCPropertyRefExprClass: 4635 case Expr::ObjCIsaExprClass: 4636 case Expr::ShuffleVectorExprClass: 4637 case Expr::BlockExprClass: 4638 case Expr::BlockDeclRefExprClass: 4639 case Expr::NoStmtClass: 4640 case Expr::OpaqueValueExprClass: 4641 case Expr::PackExpansionExprClass: 4642 case Expr::SubstNonTypeTemplateParmPackExprClass: 4643 case Expr::AsTypeExprClass: 4644 case Expr::ObjCIndirectCopyRestoreExprClass: 4645 case Expr::MaterializeTemporaryExprClass: 4646 case Expr::PseudoObjectExprClass: 4647 case Expr::AtomicExprClass: 4648 return ICEDiag(2, E->getLocStart()); 4649 4650 case Expr::InitListExprClass: 4651 if (Ctx.getLangOptions().CPlusPlus0x) { 4652 const InitListExpr *ILE = cast<InitListExpr>(E); 4653 if (ILE->getNumInits() == 0) 4654 return NoDiag(); 4655 if (ILE->getNumInits() == 1) 4656 return CheckICE(ILE->getInit(0), Ctx); 4657 // Fall through for more than 1 expression. 4658 } 4659 return ICEDiag(2, E->getLocStart()); 4660 4661 case Expr::SizeOfPackExprClass: 4662 case Expr::GNUNullExprClass: 4663 // GCC considers the GNU __null value to be an integral constant expression. 4664 return NoDiag(); 4665 4666 case Expr::SubstNonTypeTemplateParmExprClass: 4667 return 4668 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 4669 4670 case Expr::ParenExprClass: 4671 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 4672 case Expr::GenericSelectionExprClass: 4673 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 4674 case Expr::IntegerLiteralClass: 4675 case Expr::CharacterLiteralClass: 4676 case Expr::CXXBoolLiteralExprClass: 4677 case Expr::CXXScalarValueInitExprClass: 4678 case Expr::UnaryTypeTraitExprClass: 4679 case Expr::BinaryTypeTraitExprClass: 4680 case Expr::ArrayTypeTraitExprClass: 4681 case Expr::ExpressionTraitExprClass: 4682 case Expr::CXXNoexceptExprClass: 4683 return NoDiag(); 4684 case Expr::CallExprClass: 4685 case Expr::CXXOperatorCallExprClass: { 4686 // C99 6.6/3 allows function calls within unevaluated subexpressions of 4687 // constant expressions, but they can never be ICEs because an ICE cannot 4688 // contain an operand of (pointer to) function type. 4689 const CallExpr *CE = cast<CallExpr>(E); 4690 if (CE->isBuiltinCall()) 4691 return CheckEvalInICE(E, Ctx); 4692 return ICEDiag(2, E->getLocStart()); 4693 } 4694 case Expr::DeclRefExprClass: 4695 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 4696 return NoDiag(); 4697 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) { 4698 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 4699 4700 // Parameter variables are never constants. Without this check, 4701 // getAnyInitializer() can find a default argument, which leads 4702 // to chaos. 4703 if (isa<ParmVarDecl>(D)) 4704 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 4705 4706 // C++ 7.1.5.1p2 4707 // A variable of non-volatile const-qualified integral or enumeration 4708 // type initialized by an ICE can be used in ICEs. 4709 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 4710 if (!Dcl->getType()->isIntegralOrEnumerationType()) 4711 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 4712 4713 // Look for a declaration of this variable that has an initializer. 4714 const VarDecl *ID = 0; 4715 const Expr *Init = Dcl->getAnyInitializer(ID); 4716 if (Init) { 4717 if (ID->isInitKnownICE()) { 4718 // We have already checked whether this subexpression is an 4719 // integral constant expression. 4720 if (ID->isInitICE()) 4721 return NoDiag(); 4722 else 4723 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 4724 } 4725 4726 // It's an ICE whether or not the definition we found is 4727 // out-of-line. See DR 721 and the discussion in Clang PR 4728 // 6206 for details. 4729 4730 if (Dcl->isCheckingICE()) { 4731 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 4732 } 4733 4734 Dcl->setCheckingICE(); 4735 ICEDiag Result = CheckICE(Init, Ctx); 4736 // Cache the result of the ICE test. 4737 Dcl->setInitKnownICE(Result.Val == 0); 4738 return Result; 4739 } 4740 } 4741 } 4742 return ICEDiag(2, E->getLocStart()); 4743 case Expr::UnaryOperatorClass: { 4744 const UnaryOperator *Exp = cast<UnaryOperator>(E); 4745 switch (Exp->getOpcode()) { 4746 case UO_PostInc: 4747 case UO_PostDec: 4748 case UO_PreInc: 4749 case UO_PreDec: 4750 case UO_AddrOf: 4751 case UO_Deref: 4752 // C99 6.6/3 allows increment and decrement within unevaluated 4753 // subexpressions of constant expressions, but they can never be ICEs 4754 // because an ICE cannot contain an lvalue operand. 4755 return ICEDiag(2, E->getLocStart()); 4756 case UO_Extension: 4757 case UO_LNot: 4758 case UO_Plus: 4759 case UO_Minus: 4760 case UO_Not: 4761 case UO_Real: 4762 case UO_Imag: 4763 return CheckICE(Exp->getSubExpr(), Ctx); 4764 } 4765 4766 // OffsetOf falls through here. 4767 } 4768 case Expr::OffsetOfExprClass: { 4769 // Note that per C99, offsetof must be an ICE. And AFAIK, using 4770 // EvaluateAsRValue matches the proposed gcc behavior for cases like 4771 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 4772 // compliance: we should warn earlier for offsetof expressions with 4773 // array subscripts that aren't ICEs, and if the array subscripts 4774 // are ICEs, the value of the offsetof must be an integer constant. 4775 return CheckEvalInICE(E, Ctx); 4776 } 4777 case Expr::UnaryExprOrTypeTraitExprClass: { 4778 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 4779 if ((Exp->getKind() == UETT_SizeOf) && 4780 Exp->getTypeOfArgument()->isVariableArrayType()) 4781 return ICEDiag(2, E->getLocStart()); 4782 return NoDiag(); 4783 } 4784 case Expr::BinaryOperatorClass: { 4785 const BinaryOperator *Exp = cast<BinaryOperator>(E); 4786 switch (Exp->getOpcode()) { 4787 case BO_PtrMemD: 4788 case BO_PtrMemI: 4789 case BO_Assign: 4790 case BO_MulAssign: 4791 case BO_DivAssign: 4792 case BO_RemAssign: 4793 case BO_AddAssign: 4794 case BO_SubAssign: 4795 case BO_ShlAssign: 4796 case BO_ShrAssign: 4797 case BO_AndAssign: 4798 case BO_XorAssign: 4799 case BO_OrAssign: 4800 // C99 6.6/3 allows assignments within unevaluated subexpressions of 4801 // constant expressions, but they can never be ICEs because an ICE cannot 4802 // contain an lvalue operand. 4803 return ICEDiag(2, E->getLocStart()); 4804 4805 case BO_Mul: 4806 case BO_Div: 4807 case BO_Rem: 4808 case BO_Add: 4809 case BO_Sub: 4810 case BO_Shl: 4811 case BO_Shr: 4812 case BO_LT: 4813 case BO_GT: 4814 case BO_LE: 4815 case BO_GE: 4816 case BO_EQ: 4817 case BO_NE: 4818 case BO_And: 4819 case BO_Xor: 4820 case BO_Or: 4821 case BO_Comma: { 4822 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 4823 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 4824 if (Exp->getOpcode() == BO_Div || 4825 Exp->getOpcode() == BO_Rem) { 4826 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 4827 // we don't evaluate one. 4828 if (LHSResult.Val == 0 && RHSResult.Val == 0) { 4829 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 4830 if (REval == 0) 4831 return ICEDiag(1, E->getLocStart()); 4832 if (REval.isSigned() && REval.isAllOnesValue()) { 4833 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 4834 if (LEval.isMinSignedValue()) 4835 return ICEDiag(1, E->getLocStart()); 4836 } 4837 } 4838 } 4839 if (Exp->getOpcode() == BO_Comma) { 4840 if (Ctx.getLangOptions().C99) { 4841 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 4842 // if it isn't evaluated. 4843 if (LHSResult.Val == 0 && RHSResult.Val == 0) 4844 return ICEDiag(1, E->getLocStart()); 4845 } else { 4846 // In both C89 and C++, commas in ICEs are illegal. 4847 return ICEDiag(2, E->getLocStart()); 4848 } 4849 } 4850 if (LHSResult.Val >= RHSResult.Val) 4851 return LHSResult; 4852 return RHSResult; 4853 } 4854 case BO_LAnd: 4855 case BO_LOr: { 4856 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 4857 4858 // C++0x [expr.const]p2: 4859 // [...] subexpressions of logical AND (5.14), logical OR 4860 // (5.15), and condi- tional (5.16) operations that are not 4861 // evaluated are not considered. 4862 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) { 4863 if (Exp->getOpcode() == BO_LAnd && 4864 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0) 4865 return LHSResult; 4866 4867 if (Exp->getOpcode() == BO_LOr && 4868 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0) 4869 return LHSResult; 4870 } 4871 4872 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 4873 if (LHSResult.Val == 0 && RHSResult.Val == 1) { 4874 // Rare case where the RHS has a comma "side-effect"; we need 4875 // to actually check the condition to see whether the side 4876 // with the comma is evaluated. 4877 if ((Exp->getOpcode() == BO_LAnd) != 4878 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 4879 return RHSResult; 4880 return NoDiag(); 4881 } 4882 4883 if (LHSResult.Val >= RHSResult.Val) 4884 return LHSResult; 4885 return RHSResult; 4886 } 4887 } 4888 } 4889 case Expr::ImplicitCastExprClass: 4890 case Expr::CStyleCastExprClass: 4891 case Expr::CXXFunctionalCastExprClass: 4892 case Expr::CXXStaticCastExprClass: 4893 case Expr::CXXReinterpretCastExprClass: 4894 case Expr::CXXConstCastExprClass: 4895 case Expr::ObjCBridgedCastExprClass: { 4896 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 4897 if (isa<ExplicitCastExpr>(E) && 4898 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) 4899 return NoDiag(); 4900 switch (cast<CastExpr>(E)->getCastKind()) { 4901 case CK_LValueToRValue: 4902 case CK_NoOp: 4903 case CK_IntegralToBoolean: 4904 case CK_IntegralCast: 4905 return CheckICE(SubExpr, Ctx); 4906 default: 4907 return ICEDiag(2, E->getLocStart()); 4908 } 4909 } 4910 case Expr::BinaryConditionalOperatorClass: { 4911 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 4912 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 4913 if (CommonResult.Val == 2) return CommonResult; 4914 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 4915 if (FalseResult.Val == 2) return FalseResult; 4916 if (CommonResult.Val == 1) return CommonResult; 4917 if (FalseResult.Val == 1 && 4918 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag(); 4919 return FalseResult; 4920 } 4921 case Expr::ConditionalOperatorClass: { 4922 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 4923 // If the condition (ignoring parens) is a __builtin_constant_p call, 4924 // then only the true side is actually considered in an integer constant 4925 // expression, and it is fully evaluated. This is an important GNU 4926 // extension. See GCC PR38377 for discussion. 4927 if (const CallExpr *CallCE 4928 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 4929 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) { 4930 Expr::EvalResult EVResult; 4931 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 4932 !EVResult.Val.isInt()) { 4933 return ICEDiag(2, E->getLocStart()); 4934 } 4935 return NoDiag(); 4936 } 4937 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 4938 if (CondResult.Val == 2) 4939 return CondResult; 4940 4941 // C++0x [expr.const]p2: 4942 // subexpressions of [...] conditional (5.16) operations that 4943 // are not evaluated are not considered 4944 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x 4945 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0 4946 : false; 4947 ICEDiag TrueResult = NoDiag(); 4948 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch) 4949 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 4950 ICEDiag FalseResult = NoDiag(); 4951 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch) 4952 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 4953 4954 if (TrueResult.Val == 2) 4955 return TrueResult; 4956 if (FalseResult.Val == 2) 4957 return FalseResult; 4958 if (CondResult.Val == 1) 4959 return CondResult; 4960 if (TrueResult.Val == 0 && FalseResult.Val == 0) 4961 return NoDiag(); 4962 // Rare case where the diagnostics depend on which side is evaluated 4963 // Note that if we get here, CondResult is 0, and at least one of 4964 // TrueResult and FalseResult is non-zero. 4965 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) { 4966 return FalseResult; 4967 } 4968 return TrueResult; 4969 } 4970 case Expr::CXXDefaultArgExprClass: 4971 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 4972 case Expr::ChooseExprClass: { 4973 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx); 4974 } 4975 } 4976 4977 // Silence a GCC warning 4978 return ICEDiag(2, E->getLocStart()); 4979 } 4980 4981 bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, 4982 SourceLocation *Loc, bool isEvaluated) const { 4983 ICEDiag d = CheckICE(this, Ctx); 4984 if (d.Val != 0) { 4985 if (Loc) *Loc = d.Loc; 4986 return false; 4987 } 4988 if (!EvaluateAsInt(Result, Ctx)) 4989 llvm_unreachable("ICE cannot be evaluated!"); 4990 return true; 4991 } 4992