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 EvalInfo { 47 const ASTContext &Ctx; 48 49 /// EvalResult - Contains information about the evaluation. 50 Expr::EvalResult &EvalResult; 51 52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy; 53 MapTy OpaqueValues; 54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const { 55 MapTy::const_iterator i = OpaqueValues.find(e); 56 if (i == OpaqueValues.end()) return 0; 57 return &i->second; 58 } 59 60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult) 61 : Ctx(ctx), EvalResult(evalresult) {} 62 }; 63 64 struct ComplexValue { 65 private: 66 bool IsInt; 67 68 public: 69 APSInt IntReal, IntImag; 70 APFloat FloatReal, FloatImag; 71 72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {} 73 74 void makeComplexFloat() { IsInt = false; } 75 bool isComplexFloat() const { return !IsInt; } 76 APFloat &getComplexFloatReal() { return FloatReal; } 77 APFloat &getComplexFloatImag() { return FloatImag; } 78 79 void makeComplexInt() { IsInt = true; } 80 bool isComplexInt() const { return IsInt; } 81 APSInt &getComplexIntReal() { return IntReal; } 82 APSInt &getComplexIntImag() { return IntImag; } 83 84 void moveInto(APValue &v) const { 85 if (isComplexFloat()) 86 v = APValue(FloatReal, FloatImag); 87 else 88 v = APValue(IntReal, IntImag); 89 } 90 void setFrom(const APValue &v) { 91 assert(v.isComplexFloat() || v.isComplexInt()); 92 if (v.isComplexFloat()) { 93 makeComplexFloat(); 94 FloatReal = v.getComplexFloatReal(); 95 FloatImag = v.getComplexFloatImag(); 96 } else { 97 makeComplexInt(); 98 IntReal = v.getComplexIntReal(); 99 IntImag = v.getComplexIntImag(); 100 } 101 } 102 }; 103 104 struct LValue { 105 const Expr *Base; 106 CharUnits Offset; 107 108 const Expr *getLValueBase() { return Base; } 109 CharUnits getLValueOffset() { return Offset; } 110 111 void moveInto(APValue &v) const { 112 v = APValue(Base, Offset); 113 } 114 void setFrom(const APValue &v) { 115 assert(v.isLValue()); 116 Base = v.getLValueBase(); 117 Offset = v.getLValueOffset(); 118 } 119 }; 120 } 121 122 static bool Evaluate(EvalInfo &info, const Expr *E); 123 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info); 124 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info); 125 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 126 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 127 EvalInfo &Info); 128 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 129 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 130 131 //===----------------------------------------------------------------------===// 132 // Misc utilities 133 //===----------------------------------------------------------------------===// 134 135 static bool IsGlobalLValue(const Expr* E) { 136 if (!E) return true; 137 138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 139 if (isa<FunctionDecl>(DRE->getDecl())) 140 return true; 141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 142 return VD->hasGlobalStorage(); 143 return false; 144 } 145 146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E)) 147 return CLE->isFileScope(); 148 149 return true; 150 } 151 152 static bool EvalPointerValueAsBool(LValue& Value, bool& Result) { 153 const Expr* Base = Value.Base; 154 155 // A null base expression indicates a null pointer. These are always 156 // evaluatable, and they are false unless the offset is zero. 157 if (!Base) { 158 Result = !Value.Offset.isZero(); 159 return true; 160 } 161 162 // Require the base expression to be a global l-value. 163 if (!IsGlobalLValue(Base)) return false; 164 165 // We have a non-null base expression. These are generally known to 166 // be true, but if it'a decl-ref to a weak symbol it can be null at 167 // runtime. 168 Result = true; 169 170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base); 171 if (!DeclRef) 172 return true; 173 174 // If it's a weak symbol, it isn't constant-evaluable. 175 const ValueDecl* Decl = DeclRef->getDecl(); 176 if (Decl->hasAttr<WeakAttr>() || 177 Decl->hasAttr<WeakRefAttr>() || 178 Decl->isWeakImported()) 179 return false; 180 181 return true; 182 } 183 184 static bool HandleConversionToBool(const Expr* E, bool& Result, 185 EvalInfo &Info) { 186 if (E->getType()->isIntegralOrEnumerationType()) { 187 APSInt IntResult; 188 if (!EvaluateInteger(E, IntResult, Info)) 189 return false; 190 Result = IntResult != 0; 191 return true; 192 } else if (E->getType()->isRealFloatingType()) { 193 APFloat FloatResult(0.0); 194 if (!EvaluateFloat(E, FloatResult, Info)) 195 return false; 196 Result = !FloatResult.isZero(); 197 return true; 198 } else if (E->getType()->hasPointerRepresentation()) { 199 LValue PointerResult; 200 if (!EvaluatePointer(E, PointerResult, Info)) 201 return false; 202 return EvalPointerValueAsBool(PointerResult, Result); 203 } else if (E->getType()->isAnyComplexType()) { 204 ComplexValue ComplexResult; 205 if (!EvaluateComplex(E, ComplexResult, Info)) 206 return false; 207 if (ComplexResult.isComplexFloat()) { 208 Result = !ComplexResult.getComplexFloatReal().isZero() || 209 !ComplexResult.getComplexFloatImag().isZero(); 210 } else { 211 Result = ComplexResult.getComplexIntReal().getBoolValue() || 212 ComplexResult.getComplexIntImag().getBoolValue(); 213 } 214 return true; 215 } 216 217 return false; 218 } 219 220 static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType, 221 APFloat &Value, const ASTContext &Ctx) { 222 unsigned DestWidth = Ctx.getIntWidth(DestType); 223 // Determine whether we are converting to unsigned or signed. 224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 225 226 // FIXME: Warning for overflow. 227 APSInt Result(DestWidth, !DestSigned); 228 bool ignored; 229 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored); 230 return Result; 231 } 232 233 static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType, 234 APFloat &Value, const ASTContext &Ctx) { 235 bool ignored; 236 APFloat Result = Value; 237 Result.convert(Ctx.getFloatTypeSemantics(DestType), 238 APFloat::rmNearestTiesToEven, &ignored); 239 return Result; 240 } 241 242 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, 243 APSInt &Value, const ASTContext &Ctx) { 244 unsigned DestWidth = Ctx.getIntWidth(DestType); 245 APSInt Result = Value; 246 // Figure out if this is a truncate, extend or noop cast. 247 // If the input is signed, do a sign extend, noop, or truncate. 248 Result = Result.extOrTrunc(DestWidth); 249 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 250 return Result; 251 } 252 253 static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType, 254 APSInt &Value, const ASTContext &Ctx) { 255 256 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1); 257 Result.convertFromAPInt(Value, Value.isSigned(), 258 APFloat::rmNearestTiesToEven); 259 return Result; 260 } 261 262 namespace { 263 class HasSideEffect 264 : public ConstStmtVisitor<HasSideEffect, bool> { 265 EvalInfo &Info; 266 public: 267 268 HasSideEffect(EvalInfo &info) : Info(info) {} 269 270 // Unhandled nodes conservatively default to having side effects. 271 bool VisitStmt(const Stmt *S) { 272 return true; 273 } 274 275 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); } 276 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) { 277 return Visit(E->getResultExpr()); 278 } 279 bool VisitDeclRefExpr(const DeclRefExpr *E) { 280 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 281 return true; 282 return false; 283 } 284 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) { 285 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 286 return true; 287 return false; 288 } 289 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) { 290 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 291 return true; 292 return false; 293 } 294 295 // We don't want to evaluate BlockExprs multiple times, as they generate 296 // a ton of code. 297 bool VisitBlockExpr(const BlockExpr *E) { return true; } 298 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; } 299 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) 300 { return Visit(E->getInitializer()); } 301 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); } 302 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; } 303 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; } 304 bool VisitStringLiteral(const StringLiteral *E) { return false; } 305 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; } 306 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) 307 { return false; } 308 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E) 309 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 310 bool VisitChooseExpr(const ChooseExpr *E) 311 { return Visit(E->getChosenSubExpr(Info.Ctx)); } 312 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); } 313 bool VisitBinAssign(const BinaryOperator *E) { return true; } 314 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; } 315 bool VisitBinaryOperator(const BinaryOperator *E) 316 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 317 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; } 318 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; } 319 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; } 320 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; } 321 bool VisitUnaryDeref(const UnaryOperator *E) { 322 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 323 return true; 324 return Visit(E->getSubExpr()); 325 } 326 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); } 327 328 // Has side effects if any element does. 329 bool VisitInitListExpr(const InitListExpr *E) { 330 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i) 331 if (Visit(E->getInit(i))) return true; 332 if (const Expr *filler = E->getArrayFiller()) 333 return Visit(filler); 334 return false; 335 } 336 337 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; } 338 }; 339 340 class OpaqueValueEvaluation { 341 EvalInfo &info; 342 OpaqueValueExpr *opaqueValue; 343 344 public: 345 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue, 346 Expr *value) 347 : info(info), opaqueValue(opaqueValue) { 348 349 // If evaluation fails, fail immediately. 350 if (!Evaluate(info, value)) { 351 this->opaqueValue = 0; 352 return; 353 } 354 info.OpaqueValues[opaqueValue] = info.EvalResult.Val; 355 } 356 357 bool hasError() const { return opaqueValue == 0; } 358 359 ~OpaqueValueEvaluation() { 360 if (opaqueValue) info.OpaqueValues.erase(opaqueValue); 361 } 362 }; 363 364 } // end anonymous namespace 365 366 //===----------------------------------------------------------------------===// 367 // Generic Evaluation 368 //===----------------------------------------------------------------------===// 369 namespace { 370 371 template <class Derived, typename RetTy=void> 372 class ExprEvaluatorBase 373 : public ConstStmtVisitor<Derived, RetTy> { 374 private: 375 RetTy DerivedSuccess(const APValue &V, const Expr *E) { 376 return static_cast<Derived*>(this)->Success(V, E); 377 } 378 RetTy DerivedError(const Expr *E) { 379 return static_cast<Derived*>(this)->Error(E); 380 } 381 382 protected: 383 EvalInfo &Info; 384 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy; 385 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 386 387 public: 388 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 389 390 RetTy VisitStmt(const Stmt *) { 391 llvm_unreachable("Expression evaluator should not be called on stmts"); 392 } 393 RetTy VisitExpr(const Expr *E) { 394 return DerivedError(E); 395 } 396 397 RetTy VisitParenExpr(const ParenExpr *E) 398 { return StmtVisitorTy::Visit(E->getSubExpr()); } 399 RetTy VisitUnaryExtension(const UnaryOperator *E) 400 { return StmtVisitorTy::Visit(E->getSubExpr()); } 401 RetTy VisitUnaryPlus(const UnaryOperator *E) 402 { return StmtVisitorTy::Visit(E->getSubExpr()); } 403 RetTy VisitChooseExpr(const ChooseExpr *E) 404 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); } 405 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E) 406 { return StmtVisitorTy::Visit(E->getResultExpr()); } 407 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 408 { return StmtVisitorTy::Visit(E->getReplacement()); } 409 410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon()); 412 if (opaque.hasError()) 413 return DerivedError(E); 414 415 bool cond; 416 if (!HandleConversionToBool(E->getCond(), cond, Info)) 417 return DerivedError(E); 418 419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr()); 420 } 421 422 RetTy VisitConditionalOperator(const ConditionalOperator *E) { 423 bool BoolResult; 424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info)) 425 return DerivedError(E); 426 427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 428 return StmtVisitorTy::Visit(EvalExpr); 429 } 430 431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 432 const APValue *value = Info.getOpaqueValue(E); 433 if (!value) 434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr()) 435 : DerivedError(E)); 436 return DerivedSuccess(*value, E); 437 } 438 }; 439 440 } 441 442 //===----------------------------------------------------------------------===// 443 // LValue Evaluation 444 //===----------------------------------------------------------------------===// 445 namespace { 446 class LValueExprEvaluator 447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> { 448 LValue &Result; 449 const Decl *PrevDecl; 450 451 bool Success(const Expr *E) { 452 Result.Base = E; 453 Result.Offset = CharUnits::Zero(); 454 return true; 455 } 456 public: 457 458 LValueExprEvaluator(EvalInfo &info, LValue &Result) : 459 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {} 460 461 bool Success(const APValue &V, const Expr *E) { 462 Result.setFrom(V); 463 return true; 464 } 465 bool Error(const Expr *E) { 466 return false; 467 } 468 469 bool VisitDeclRefExpr(const DeclRefExpr *E); 470 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 471 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 472 bool VisitMemberExpr(const MemberExpr *E); 473 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 474 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 475 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 476 bool VisitUnaryDeref(const UnaryOperator *E); 477 478 bool VisitCastExpr(const CastExpr *E) { 479 switch (E->getCastKind()) { 480 default: 481 return false; 482 483 case CK_NoOp: 484 return Visit(E->getSubExpr()); 485 } 486 } 487 488 bool VisitInitListExpr(const InitListExpr *E) { 489 if (Info.Ctx.getLangOptions().CPlusPlus0x && E->getNumInits() == 1) 490 return Visit(E->getInit(0)); 491 return Error(E); 492 } 493 494 // FIXME: Missing: __real__, __imag__ 495 496 }; 497 } // end anonymous namespace 498 499 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) { 500 return LValueExprEvaluator(Info, Result).Visit(E); 501 } 502 503 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 504 if (isa<FunctionDecl>(E->getDecl())) { 505 return Success(E); 506 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) { 507 if (!VD->getType()->isReferenceType()) 508 return Success(E); 509 // Reference parameters can refer to anything even if they have an 510 // "initializer" in the form of a default argument. 511 if (!isa<ParmVarDecl>(VD)) { 512 // FIXME: Check whether VD might be overridden! 513 514 // Check for recursive initializers of references. 515 if (PrevDecl == VD) 516 return Error(E); 517 PrevDecl = VD; 518 if (const Expr *Init = VD->getAnyInitializer()) 519 return Visit(Init); 520 } 521 } 522 523 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 524 } 525 526 bool 527 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 528 return Success(E); 529 } 530 531 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 532 QualType Ty; 533 if (E->isArrow()) { 534 if (!EvaluatePointer(E->getBase(), Result, Info)) 535 return false; 536 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType(); 537 } else { 538 if (!Visit(E->getBase())) 539 return false; 540 Ty = E->getBase()->getType(); 541 } 542 543 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl(); 544 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 545 546 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 547 if (!FD) // FIXME: deal with other kinds of member expressions 548 return false; 549 550 if (FD->getType()->isReferenceType()) 551 return false; 552 553 unsigned i = FD->getFieldIndex(); 554 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 555 return true; 556 } 557 558 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 559 if (!EvaluatePointer(E->getBase(), Result, Info)) 560 return false; 561 562 APSInt Index; 563 if (!EvaluateInteger(E->getIdx(), Index, Info)) 564 return false; 565 566 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType()); 567 Result.Offset += Index.getSExtValue() * ElementSize; 568 return true; 569 } 570 571 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 572 return EvaluatePointer(E->getSubExpr(), Result, Info); 573 } 574 575 //===----------------------------------------------------------------------===// 576 // Pointer Evaluation 577 //===----------------------------------------------------------------------===// 578 579 namespace { 580 class PointerExprEvaluator 581 : public ExprEvaluatorBase<PointerExprEvaluator, bool> { 582 LValue &Result; 583 584 bool Success(const Expr *E) { 585 Result.Base = E; 586 Result.Offset = CharUnits::Zero(); 587 return true; 588 } 589 public: 590 591 PointerExprEvaluator(EvalInfo &info, LValue &Result) 592 : ExprEvaluatorBaseTy(info), Result(Result) {} 593 594 bool Success(const APValue &V, const Expr *E) { 595 Result.setFrom(V); 596 return true; 597 } 598 bool Error(const Stmt *S) { 599 return false; 600 } 601 602 bool VisitBinaryOperator(const BinaryOperator *E); 603 bool VisitCastExpr(const CastExpr* E); 604 bool VisitUnaryAddrOf(const UnaryOperator *E); 605 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 606 { return Success(E); } 607 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 608 { return Success(E); } 609 bool VisitCallExpr(const CallExpr *E); 610 bool VisitBlockExpr(const BlockExpr *E) { 611 if (!E->getBlockDecl()->hasCaptures()) 612 return Success(E); 613 return false; 614 } 615 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) 616 { return Success((Expr*)0); } 617 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) 618 { return Success((Expr*)0); } 619 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) 620 { return Success((Expr*)0); } 621 622 // FIXME: Missing: @protocol, @selector 623 }; 624 } // end anonymous namespace 625 626 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) { 627 assert(E->getType()->hasPointerRepresentation()); 628 return PointerExprEvaluator(Info, Result).Visit(E); 629 } 630 631 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 632 if (E->getOpcode() != BO_Add && 633 E->getOpcode() != BO_Sub) 634 return false; 635 636 const Expr *PExp = E->getLHS(); 637 const Expr *IExp = E->getRHS(); 638 if (IExp->getType()->isPointerType()) 639 std::swap(PExp, IExp); 640 641 if (!EvaluatePointer(PExp, Result, Info)) 642 return false; 643 644 llvm::APSInt Offset; 645 if (!EvaluateInteger(IExp, Offset, Info)) 646 return false; 647 int64_t AdditionalOffset 648 = Offset.isSigned() ? Offset.getSExtValue() 649 : static_cast<int64_t>(Offset.getZExtValue()); 650 651 // Compute the new offset in the appropriate width. 652 653 QualType PointeeType = 654 PExp->getType()->getAs<PointerType>()->getPointeeType(); 655 CharUnits SizeOfPointee; 656 657 // Explicitly handle GNU void* and function pointer arithmetic extensions. 658 if (PointeeType->isVoidType() || PointeeType->isFunctionType()) 659 SizeOfPointee = CharUnits::One(); 660 else 661 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType); 662 663 if (E->getOpcode() == BO_Add) 664 Result.Offset += AdditionalOffset * SizeOfPointee; 665 else 666 Result.Offset -= AdditionalOffset * SizeOfPointee; 667 668 return true; 669 } 670 671 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 672 return EvaluateLValue(E->getSubExpr(), Result, Info); 673 } 674 675 676 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 677 const Expr* SubExpr = E->getSubExpr(); 678 679 switch (E->getCastKind()) { 680 default: 681 break; 682 683 case CK_NoOp: 684 case CK_BitCast: 685 case CK_CPointerToObjCPointerCast: 686 case CK_BlockPointerToObjCPointerCast: 687 case CK_AnyPointerToBlockPointerCast: 688 return Visit(SubExpr); 689 690 case CK_DerivedToBase: 691 case CK_UncheckedDerivedToBase: { 692 LValue BaseLV; 693 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info)) 694 return false; 695 696 // Now figure out the necessary offset to add to the baseLV to get from 697 // the derived class to the base class. 698 CharUnits Offset = CharUnits::Zero(); 699 700 QualType Ty = E->getSubExpr()->getType(); 701 const CXXRecordDecl *DerivedDecl = 702 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl(); 703 704 for (CastExpr::path_const_iterator PathI = E->path_begin(), 705 PathE = E->path_end(); PathI != PathE; ++PathI) { 706 const CXXBaseSpecifier *Base = *PathI; 707 708 // FIXME: If the base is virtual, we'd need to determine the type of the 709 // most derived class and we don't support that right now. 710 if (Base->isVirtual()) 711 return false; 712 713 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 714 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 715 716 Offset += Layout.getBaseClassOffset(BaseDecl); 717 DerivedDecl = BaseDecl; 718 } 719 720 Result.Base = BaseLV.getLValueBase(); 721 Result.Offset = BaseLV.getLValueOffset() + Offset; 722 return true; 723 } 724 725 case CK_NullToPointer: { 726 Result.Base = 0; 727 Result.Offset = CharUnits::Zero(); 728 return true; 729 } 730 731 case CK_IntegralToPointer: { 732 APValue Value; 733 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 734 break; 735 736 if (Value.isInt()) { 737 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType())); 738 Result.Base = 0; 739 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue()); 740 return true; 741 } else { 742 // Cast is of an lvalue, no need to change value. 743 Result.Base = Value.getLValueBase(); 744 Result.Offset = Value.getLValueOffset(); 745 return true; 746 } 747 } 748 case CK_ArrayToPointerDecay: 749 case CK_FunctionToPointerDecay: 750 return EvaluateLValue(SubExpr, Result, Info); 751 } 752 753 return false; 754 } 755 756 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 757 if (E->isBuiltinCall(Info.Ctx) == 758 Builtin::BI__builtin___CFStringMakeConstantString || 759 E->isBuiltinCall(Info.Ctx) == 760 Builtin::BI__builtin___NSStringMakeConstantString) 761 return Success(E); 762 763 return ExprEvaluatorBaseTy::VisitCallExpr(E); 764 } 765 766 //===----------------------------------------------------------------------===// 767 // Vector Evaluation 768 //===----------------------------------------------------------------------===// 769 770 namespace { 771 class VectorExprEvaluator 772 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> { 773 APValue GetZeroVector(QualType VecType); 774 public: 775 776 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {} 777 778 APValue Success(const APValue &V, const Expr *E) { return V; } 779 APValue Error(const Expr *E) { return APValue(); } 780 781 APValue VisitUnaryReal(const UnaryOperator *E) 782 { return Visit(E->getSubExpr()); } 783 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) 784 { return GetZeroVector(E->getType()); } 785 APValue VisitCastExpr(const CastExpr* E); 786 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 787 APValue VisitInitListExpr(const InitListExpr *E); 788 APValue VisitUnaryImag(const UnaryOperator *E); 789 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 790 // binary comparisons, binary and/or/xor, 791 // shufflevector, ExtVectorElementExpr 792 // (Note that these require implementing conversions 793 // between vector types.) 794 }; 795 } // end anonymous namespace 796 797 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 798 if (!E->getType()->isVectorType()) 799 return false; 800 Result = VectorExprEvaluator(Info).Visit(E); 801 return !Result.isUninit(); 802 } 803 804 APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { 805 const VectorType *VTy = E->getType()->getAs<VectorType>(); 806 QualType EltTy = VTy->getElementType(); 807 unsigned NElts = VTy->getNumElements(); 808 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy); 809 810 const Expr* SE = E->getSubExpr(); 811 QualType SETy = SE->getType(); 812 813 switch (E->getCastKind()) { 814 case CK_VectorSplat: { 815 APValue Result = APValue(); 816 if (SETy->isIntegerType()) { 817 APSInt IntResult; 818 if (!EvaluateInteger(SE, IntResult, Info)) 819 return APValue(); 820 Result = APValue(IntResult); 821 } else if (SETy->isRealFloatingType()) { 822 APFloat F(0.0); 823 if (!EvaluateFloat(SE, F, Info)) 824 return APValue(); 825 Result = APValue(F); 826 } else { 827 return APValue(); 828 } 829 830 // Splat and create vector APValue. 831 SmallVector<APValue, 4> Elts(NElts, Result); 832 return APValue(&Elts[0], Elts.size()); 833 } 834 case CK_BitCast: { 835 if (SETy->isVectorType()) 836 return Visit(SE); 837 838 if (!SETy->isIntegerType()) 839 return APValue(); 840 841 APSInt Init; 842 if (!EvaluateInteger(SE, Init, Info)) 843 return APValue(); 844 845 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) && 846 "Vectors must be composed of ints or floats"); 847 848 SmallVector<APValue, 4> Elts; 849 for (unsigned i = 0; i != NElts; ++i) { 850 APSInt Tmp = Init.extOrTrunc(EltWidth); 851 852 if (EltTy->isIntegerType()) 853 Elts.push_back(APValue(Tmp)); 854 else 855 Elts.push_back(APValue(APFloat(Tmp))); 856 857 Init >>= EltWidth; 858 } 859 return APValue(&Elts[0], Elts.size()); 860 } 861 case CK_LValueToRValue: 862 case CK_NoOp: 863 return Visit(SE); 864 default: 865 return APValue(); 866 } 867 } 868 869 APValue 870 VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 871 return this->Visit(E->getInitializer()); 872 } 873 874 APValue 875 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 876 const VectorType *VT = E->getType()->getAs<VectorType>(); 877 unsigned NumInits = E->getNumInits(); 878 unsigned NumElements = VT->getNumElements(); 879 880 QualType EltTy = VT->getElementType(); 881 SmallVector<APValue, 4> Elements; 882 883 // If a vector is initialized with a single element, that value 884 // becomes every element of the vector, not just the first. 885 // This is the behavior described in the IBM AltiVec documentation. 886 if (NumInits == 1) { 887 888 // Handle the case where the vector is initialized by a another 889 // vector (OpenCL 6.1.6). 890 if (E->getInit(0)->getType()->isVectorType()) 891 return this->Visit(const_cast<Expr*>(E->getInit(0))); 892 893 APValue InitValue; 894 if (EltTy->isIntegerType()) { 895 llvm::APSInt sInt(32); 896 if (!EvaluateInteger(E->getInit(0), sInt, Info)) 897 return APValue(); 898 InitValue = APValue(sInt); 899 } else { 900 llvm::APFloat f(0.0); 901 if (!EvaluateFloat(E->getInit(0), f, Info)) 902 return APValue(); 903 InitValue = APValue(f); 904 } 905 for (unsigned i = 0; i < NumElements; i++) { 906 Elements.push_back(InitValue); 907 } 908 } else { 909 for (unsigned i = 0; i < NumElements; i++) { 910 if (EltTy->isIntegerType()) { 911 llvm::APSInt sInt(32); 912 if (i < NumInits) { 913 if (!EvaluateInteger(E->getInit(i), sInt, Info)) 914 return APValue(); 915 } else { 916 sInt = Info.Ctx.MakeIntValue(0, EltTy); 917 } 918 Elements.push_back(APValue(sInt)); 919 } else { 920 llvm::APFloat f(0.0); 921 if (i < NumInits) { 922 if (!EvaluateFloat(E->getInit(i), f, Info)) 923 return APValue(); 924 } else { 925 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 926 } 927 Elements.push_back(APValue(f)); 928 } 929 } 930 } 931 return APValue(&Elements[0], Elements.size()); 932 } 933 934 APValue 935 VectorExprEvaluator::GetZeroVector(QualType T) { 936 const VectorType *VT = T->getAs<VectorType>(); 937 QualType EltTy = VT->getElementType(); 938 APValue ZeroElement; 939 if (EltTy->isIntegerType()) 940 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 941 else 942 ZeroElement = 943 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 944 945 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 946 return APValue(&Elements[0], Elements.size()); 947 } 948 949 APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 950 if (!E->getSubExpr()->isEvaluatable(Info.Ctx)) 951 Info.EvalResult.HasSideEffects = true; 952 return GetZeroVector(E->getType()); 953 } 954 955 //===----------------------------------------------------------------------===// 956 // Integer Evaluation 957 //===----------------------------------------------------------------------===// 958 959 namespace { 960 class IntExprEvaluator 961 : public ExprEvaluatorBase<IntExprEvaluator, bool> { 962 APValue &Result; 963 public: 964 IntExprEvaluator(EvalInfo &info, APValue &result) 965 : ExprEvaluatorBaseTy(info), Result(result) {} 966 967 bool Success(const llvm::APSInt &SI, const Expr *E) { 968 assert(E->getType()->isIntegralOrEnumerationType() && 969 "Invalid evaluation result."); 970 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 971 "Invalid evaluation result."); 972 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 973 "Invalid evaluation result."); 974 Result = APValue(SI); 975 return true; 976 } 977 978 bool Success(const llvm::APInt &I, const Expr *E) { 979 assert(E->getType()->isIntegralOrEnumerationType() && 980 "Invalid evaluation result."); 981 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 982 "Invalid evaluation result."); 983 Result = APValue(APSInt(I)); 984 Result.getInt().setIsUnsigned( 985 E->getType()->isUnsignedIntegerOrEnumerationType()); 986 return true; 987 } 988 989 bool Success(uint64_t Value, const Expr *E) { 990 assert(E->getType()->isIntegralOrEnumerationType() && 991 "Invalid evaluation result."); 992 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 993 return true; 994 } 995 996 bool Success(CharUnits Size, const Expr *E) { 997 return Success(Size.getQuantity(), E); 998 } 999 1000 1001 bool Error(SourceLocation L, diag::kind D, const Expr *E) { 1002 // Take the first error. 1003 if (Info.EvalResult.Diag == 0) { 1004 Info.EvalResult.DiagLoc = L; 1005 Info.EvalResult.Diag = D; 1006 Info.EvalResult.DiagExpr = E; 1007 } 1008 return false; 1009 } 1010 1011 bool Success(const APValue &V, const Expr *E) { 1012 return Success(V.getInt(), E); 1013 } 1014 bool Error(const Expr *E) { 1015 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1016 } 1017 1018 //===--------------------------------------------------------------------===// 1019 // Visitor Methods 1020 //===--------------------------------------------------------------------===// 1021 1022 bool VisitIntegerLiteral(const IntegerLiteral *E) { 1023 return Success(E->getValue(), E); 1024 } 1025 bool VisitCharacterLiteral(const CharacterLiteral *E) { 1026 return Success(E->getValue(), E); 1027 } 1028 1029 bool CheckReferencedDecl(const Expr *E, const Decl *D); 1030 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1031 if (CheckReferencedDecl(E, E->getDecl())) 1032 return true; 1033 1034 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 1035 } 1036 bool VisitMemberExpr(const MemberExpr *E) { 1037 if (CheckReferencedDecl(E, E->getMemberDecl())) { 1038 // Conservatively assume a MemberExpr will have side-effects 1039 Info.EvalResult.HasSideEffects = true; 1040 return true; 1041 } 1042 1043 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 1044 } 1045 1046 bool VisitCallExpr(const CallExpr *E); 1047 bool VisitBinaryOperator(const BinaryOperator *E); 1048 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 1049 bool VisitUnaryOperator(const UnaryOperator *E); 1050 1051 bool VisitCastExpr(const CastExpr* E); 1052 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 1053 1054 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 1055 return Success(E->getValue(), E); 1056 } 1057 1058 bool VisitGNUNullExpr(const GNUNullExpr *E) { 1059 return Success(0, E); 1060 } 1061 1062 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 1063 return Success(0, E); 1064 } 1065 1066 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 1067 return Success(0, E); 1068 } 1069 1070 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 1071 return Success(E->getValue(), E); 1072 } 1073 1074 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 1075 return Success(E->getValue(), E); 1076 } 1077 1078 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 1079 return Success(E->getValue(), E); 1080 } 1081 1082 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 1083 return Success(E->getValue(), E); 1084 } 1085 1086 bool VisitUnaryReal(const UnaryOperator *E); 1087 bool VisitUnaryImag(const UnaryOperator *E); 1088 1089 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 1090 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 1091 1092 bool VisitInitListExpr(const InitListExpr *E); 1093 1094 private: 1095 CharUnits GetAlignOfExpr(const Expr *E); 1096 CharUnits GetAlignOfType(QualType T); 1097 static QualType GetObjectType(const Expr *E); 1098 bool TryEvaluateBuiltinObjectSize(const CallExpr *E); 1099 // FIXME: Missing: array subscript of vector, member of vector 1100 }; 1101 } // end anonymous namespace 1102 1103 static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) { 1104 assert(E->getType()->isIntegralOrEnumerationType()); 1105 return IntExprEvaluator(Info, Result).Visit(E); 1106 } 1107 1108 static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) { 1109 assert(E->getType()->isIntegralOrEnumerationType()); 1110 1111 APValue Val; 1112 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt()) 1113 return false; 1114 Result = Val.getInt(); 1115 return true; 1116 } 1117 1118 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 1119 // Enums are integer constant exprs. 1120 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 1121 // Check for signedness/width mismatches between E type and ECD value. 1122 bool SameSign = (ECD->getInitVal().isSigned() 1123 == E->getType()->isSignedIntegerOrEnumerationType()); 1124 bool SameWidth = (ECD->getInitVal().getBitWidth() 1125 == Info.Ctx.getIntWidth(E->getType())); 1126 if (SameSign && SameWidth) 1127 return Success(ECD->getInitVal(), E); 1128 else { 1129 // Get rid of mismatch (otherwise Success assertions will fail) 1130 // by computing a new value matching the type of E. 1131 llvm::APSInt Val = ECD->getInitVal(); 1132 if (!SameSign) 1133 Val.setIsSigned(!ECD->getInitVal().isSigned()); 1134 if (!SameWidth) 1135 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 1136 return Success(Val, E); 1137 } 1138 } 1139 1140 // In C++, const, non-volatile integers initialized with ICEs are ICEs. 1141 // In C, they can also be folded, although they are not ICEs. 1142 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers() 1143 == Qualifiers::Const) { 1144 1145 if (isa<ParmVarDecl>(D)) 1146 return false; 1147 1148 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1149 if (const Expr *Init = VD->getAnyInitializer()) { 1150 if (APValue *V = VD->getEvaluatedValue()) { 1151 if (V->isInt()) 1152 return Success(V->getInt(), E); 1153 return false; 1154 } 1155 1156 if (VD->isEvaluatingValue()) 1157 return false; 1158 1159 VD->setEvaluatingValue(); 1160 1161 Expr::EvalResult EResult; 1162 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects && 1163 EResult.Val.isInt()) { 1164 // Cache the evaluated value in the variable declaration. 1165 Result = EResult.Val; 1166 VD->setEvaluatedValue(Result); 1167 return true; 1168 } 1169 1170 VD->setEvaluatedValue(APValue()); 1171 } 1172 } 1173 } 1174 1175 // Otherwise, random variable references are not constants. 1176 return false; 1177 } 1178 1179 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 1180 /// as GCC. 1181 static int EvaluateBuiltinClassifyType(const CallExpr *E) { 1182 // The following enum mimics the values returned by GCC. 1183 // FIXME: Does GCC differ between lvalue and rvalue references here? 1184 enum gcc_type_class { 1185 no_type_class = -1, 1186 void_type_class, integer_type_class, char_type_class, 1187 enumeral_type_class, boolean_type_class, 1188 pointer_type_class, reference_type_class, offset_type_class, 1189 real_type_class, complex_type_class, 1190 function_type_class, method_type_class, 1191 record_type_class, union_type_class, 1192 array_type_class, string_type_class, 1193 lang_type_class 1194 }; 1195 1196 // If no argument was supplied, default to "no_type_class". This isn't 1197 // ideal, however it is what gcc does. 1198 if (E->getNumArgs() == 0) 1199 return no_type_class; 1200 1201 QualType ArgTy = E->getArg(0)->getType(); 1202 if (ArgTy->isVoidType()) 1203 return void_type_class; 1204 else if (ArgTy->isEnumeralType()) 1205 return enumeral_type_class; 1206 else if (ArgTy->isBooleanType()) 1207 return boolean_type_class; 1208 else if (ArgTy->isCharType()) 1209 return string_type_class; // gcc doesn't appear to use char_type_class 1210 else if (ArgTy->isIntegerType()) 1211 return integer_type_class; 1212 else if (ArgTy->isPointerType()) 1213 return pointer_type_class; 1214 else if (ArgTy->isReferenceType()) 1215 return reference_type_class; 1216 else if (ArgTy->isRealType()) 1217 return real_type_class; 1218 else if (ArgTy->isComplexType()) 1219 return complex_type_class; 1220 else if (ArgTy->isFunctionType()) 1221 return function_type_class; 1222 else if (ArgTy->isStructureOrClassType()) 1223 return record_type_class; 1224 else if (ArgTy->isUnionType()) 1225 return union_type_class; 1226 else if (ArgTy->isArrayType()) 1227 return array_type_class; 1228 else if (ArgTy->isUnionType()) 1229 return union_type_class; 1230 else // FIXME: offset_type_class, method_type_class, & lang_type_class? 1231 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 1232 return -1; 1233 } 1234 1235 /// Retrieves the "underlying object type" of the given expression, 1236 /// as used by __builtin_object_size. 1237 QualType IntExprEvaluator::GetObjectType(const Expr *E) { 1238 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 1239 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1240 return VD->getType(); 1241 } else if (isa<CompoundLiteralExpr>(E)) { 1242 return E->getType(); 1243 } 1244 1245 return QualType(); 1246 } 1247 1248 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) { 1249 // TODO: Perhaps we should let LLVM lower this? 1250 LValue Base; 1251 if (!EvaluatePointer(E->getArg(0), Base, Info)) 1252 return false; 1253 1254 // If we can prove the base is null, lower to zero now. 1255 const Expr *LVBase = Base.getLValueBase(); 1256 if (!LVBase) return Success(0, E); 1257 1258 QualType T = GetObjectType(LVBase); 1259 if (T.isNull() || 1260 T->isIncompleteType() || 1261 T->isFunctionType() || 1262 T->isVariablyModifiedType() || 1263 T->isDependentType()) 1264 return false; 1265 1266 CharUnits Size = Info.Ctx.getTypeSizeInChars(T); 1267 CharUnits Offset = Base.getLValueOffset(); 1268 1269 if (!Offset.isNegative() && Offset <= Size) 1270 Size -= Offset; 1271 else 1272 Size = CharUnits::Zero(); 1273 return Success(Size, E); 1274 } 1275 1276 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 1277 switch (E->isBuiltinCall(Info.Ctx)) { 1278 default: 1279 return ExprEvaluatorBaseTy::VisitCallExpr(E); 1280 1281 case Builtin::BI__builtin_object_size: { 1282 if (TryEvaluateBuiltinObjectSize(E)) 1283 return true; 1284 1285 // If evaluating the argument has side-effects we can't determine 1286 // the size of the object and lower it to unknown now. 1287 if (E->getArg(0)->HasSideEffects(Info.Ctx)) { 1288 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1) 1289 return Success(-1ULL, E); 1290 return Success(0, E); 1291 } 1292 1293 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1294 } 1295 1296 case Builtin::BI__builtin_classify_type: 1297 return Success(EvaluateBuiltinClassifyType(E), E); 1298 1299 case Builtin::BI__builtin_constant_p: 1300 // __builtin_constant_p always has one operand: it returns true if that 1301 // operand can be folded, false otherwise. 1302 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E); 1303 1304 case Builtin::BI__builtin_eh_return_data_regno: { 1305 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue(); 1306 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 1307 return Success(Operand, E); 1308 } 1309 1310 case Builtin::BI__builtin_expect: 1311 return Visit(E->getArg(0)); 1312 1313 case Builtin::BIstrlen: 1314 case Builtin::BI__builtin_strlen: 1315 // As an extension, we support strlen() and __builtin_strlen() as constant 1316 // expressions when the argument is a string literal. 1317 if (const StringLiteral *S 1318 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) { 1319 // The string literal may have embedded null characters. Find the first 1320 // one and truncate there. 1321 StringRef Str = S->getString(); 1322 StringRef::size_type Pos = Str.find(0); 1323 if (Pos != StringRef::npos) 1324 Str = Str.substr(0, Pos); 1325 1326 return Success(Str.size(), E); 1327 } 1328 1329 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1330 } 1331 } 1332 1333 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 1334 if (E->getOpcode() == BO_Comma) { 1335 if (!Visit(E->getRHS())) 1336 return false; 1337 1338 // If we can't evaluate the LHS, it might have side effects; 1339 // conservatively mark it. 1340 if (!E->getLHS()->isEvaluatable(Info.Ctx)) 1341 Info.EvalResult.HasSideEffects = true; 1342 1343 return true; 1344 } 1345 1346 if (E->isLogicalOp()) { 1347 // These need to be handled specially because the operands aren't 1348 // necessarily integral 1349 bool lhsResult, rhsResult; 1350 1351 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) { 1352 // We were able to evaluate the LHS, see if we can get away with not 1353 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 1354 if (lhsResult == (E->getOpcode() == BO_LOr)) 1355 return Success(lhsResult, E); 1356 1357 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) { 1358 if (E->getOpcode() == BO_LOr) 1359 return Success(lhsResult || rhsResult, E); 1360 else 1361 return Success(lhsResult && rhsResult, E); 1362 } 1363 } else { 1364 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) { 1365 // We can't evaluate the LHS; however, sometimes the result 1366 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 1367 if (rhsResult == (E->getOpcode() == BO_LOr) || 1368 !rhsResult == (E->getOpcode() == BO_LAnd)) { 1369 // Since we weren't able to evaluate the left hand side, it 1370 // must have had side effects. 1371 Info.EvalResult.HasSideEffects = true; 1372 1373 return Success(rhsResult, E); 1374 } 1375 } 1376 } 1377 1378 return false; 1379 } 1380 1381 QualType LHSTy = E->getLHS()->getType(); 1382 QualType RHSTy = E->getRHS()->getType(); 1383 1384 if (LHSTy->isAnyComplexType()) { 1385 assert(RHSTy->isAnyComplexType() && "Invalid comparison"); 1386 ComplexValue LHS, RHS; 1387 1388 if (!EvaluateComplex(E->getLHS(), LHS, Info)) 1389 return false; 1390 1391 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 1392 return false; 1393 1394 if (LHS.isComplexFloat()) { 1395 APFloat::cmpResult CR_r = 1396 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 1397 APFloat::cmpResult CR_i = 1398 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 1399 1400 if (E->getOpcode() == BO_EQ) 1401 return Success((CR_r == APFloat::cmpEqual && 1402 CR_i == APFloat::cmpEqual), E); 1403 else { 1404 assert(E->getOpcode() == BO_NE && 1405 "Invalid complex comparison."); 1406 return Success(((CR_r == APFloat::cmpGreaterThan || 1407 CR_r == APFloat::cmpLessThan || 1408 CR_r == APFloat::cmpUnordered) || 1409 (CR_i == APFloat::cmpGreaterThan || 1410 CR_i == APFloat::cmpLessThan || 1411 CR_i == APFloat::cmpUnordered)), E); 1412 } 1413 } else { 1414 if (E->getOpcode() == BO_EQ) 1415 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 1416 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 1417 else { 1418 assert(E->getOpcode() == BO_NE && 1419 "Invalid compex comparison."); 1420 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 1421 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 1422 } 1423 } 1424 } 1425 1426 if (LHSTy->isRealFloatingType() && 1427 RHSTy->isRealFloatingType()) { 1428 APFloat RHS(0.0), LHS(0.0); 1429 1430 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 1431 return false; 1432 1433 if (!EvaluateFloat(E->getLHS(), LHS, Info)) 1434 return false; 1435 1436 APFloat::cmpResult CR = LHS.compare(RHS); 1437 1438 switch (E->getOpcode()) { 1439 default: 1440 llvm_unreachable("Invalid binary operator!"); 1441 case BO_LT: 1442 return Success(CR == APFloat::cmpLessThan, E); 1443 case BO_GT: 1444 return Success(CR == APFloat::cmpGreaterThan, E); 1445 case BO_LE: 1446 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 1447 case BO_GE: 1448 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 1449 E); 1450 case BO_EQ: 1451 return Success(CR == APFloat::cmpEqual, E); 1452 case BO_NE: 1453 return Success(CR == APFloat::cmpGreaterThan 1454 || CR == APFloat::cmpLessThan 1455 || CR == APFloat::cmpUnordered, E); 1456 } 1457 } 1458 1459 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 1460 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) { 1461 LValue LHSValue; 1462 if (!EvaluatePointer(E->getLHS(), LHSValue, Info)) 1463 return false; 1464 1465 LValue RHSValue; 1466 if (!EvaluatePointer(E->getRHS(), RHSValue, Info)) 1467 return false; 1468 1469 // Reject any bases from the normal codepath; we special-case comparisons 1470 // to null. 1471 if (LHSValue.getLValueBase()) { 1472 if (!E->isEqualityOp()) 1473 return false; 1474 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero()) 1475 return false; 1476 bool bres; 1477 if (!EvalPointerValueAsBool(LHSValue, bres)) 1478 return false; 1479 return Success(bres ^ (E->getOpcode() == BO_EQ), E); 1480 } else if (RHSValue.getLValueBase()) { 1481 if (!E->isEqualityOp()) 1482 return false; 1483 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero()) 1484 return false; 1485 bool bres; 1486 if (!EvalPointerValueAsBool(RHSValue, bres)) 1487 return false; 1488 return Success(bres ^ (E->getOpcode() == BO_EQ), E); 1489 } 1490 1491 if (E->getOpcode() == BO_Sub) { 1492 QualType Type = E->getLHS()->getType(); 1493 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 1494 1495 CharUnits ElementSize = CharUnits::One(); 1496 if (!ElementType->isVoidType() && !ElementType->isFunctionType()) 1497 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType); 1498 1499 CharUnits Diff = LHSValue.getLValueOffset() - 1500 RHSValue.getLValueOffset(); 1501 return Success(Diff / ElementSize, E); 1502 } 1503 bool Result; 1504 if (E->getOpcode() == BO_EQ) { 1505 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset(); 1506 } else { 1507 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset(); 1508 } 1509 return Success(Result, E); 1510 } 1511 } 1512 if (!LHSTy->isIntegralOrEnumerationType() || 1513 !RHSTy->isIntegralOrEnumerationType()) { 1514 // We can't continue from here for non-integral types, and they 1515 // could potentially confuse the following operations. 1516 return false; 1517 } 1518 1519 // The LHS of a constant expr is always evaluated and needed. 1520 if (!Visit(E->getLHS())) 1521 return false; // error in subexpression. 1522 1523 APValue RHSVal; 1524 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info)) 1525 return false; 1526 1527 // Handle cases like (unsigned long)&a + 4. 1528 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) { 1529 CharUnits Offset = Result.getLValueOffset(); 1530 CharUnits AdditionalOffset = CharUnits::fromQuantity( 1531 RHSVal.getInt().getZExtValue()); 1532 if (E->getOpcode() == BO_Add) 1533 Offset += AdditionalOffset; 1534 else 1535 Offset -= AdditionalOffset; 1536 Result = APValue(Result.getLValueBase(), Offset); 1537 return true; 1538 } 1539 1540 // Handle cases like 4 + (unsigned long)&a 1541 if (E->getOpcode() == BO_Add && 1542 RHSVal.isLValue() && Result.isInt()) { 1543 CharUnits Offset = RHSVal.getLValueOffset(); 1544 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue()); 1545 Result = APValue(RHSVal.getLValueBase(), Offset); 1546 return true; 1547 } 1548 1549 // All the following cases expect both operands to be an integer 1550 if (!Result.isInt() || !RHSVal.isInt()) 1551 return false; 1552 1553 APSInt& RHS = RHSVal.getInt(); 1554 1555 switch (E->getOpcode()) { 1556 default: 1557 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 1558 case BO_Mul: return Success(Result.getInt() * RHS, E); 1559 case BO_Add: return Success(Result.getInt() + RHS, E); 1560 case BO_Sub: return Success(Result.getInt() - RHS, E); 1561 case BO_And: return Success(Result.getInt() & RHS, E); 1562 case BO_Xor: return Success(Result.getInt() ^ RHS, E); 1563 case BO_Or: return Success(Result.getInt() | RHS, E); 1564 case BO_Div: 1565 if (RHS == 0) 1566 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 1567 return Success(Result.getInt() / RHS, E); 1568 case BO_Rem: 1569 if (RHS == 0) 1570 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 1571 return Success(Result.getInt() % RHS, E); 1572 case BO_Shl: { 1573 // During constant-folding, a negative shift is an opposite shift. 1574 if (RHS.isSigned() && RHS.isNegative()) { 1575 RHS = -RHS; 1576 goto shift_right; 1577 } 1578 1579 shift_left: 1580 unsigned SA 1581 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1); 1582 return Success(Result.getInt() << SA, E); 1583 } 1584 case BO_Shr: { 1585 // During constant-folding, a negative shift is an opposite shift. 1586 if (RHS.isSigned() && RHS.isNegative()) { 1587 RHS = -RHS; 1588 goto shift_left; 1589 } 1590 1591 shift_right: 1592 unsigned SA = 1593 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1); 1594 return Success(Result.getInt() >> SA, E); 1595 } 1596 1597 case BO_LT: return Success(Result.getInt() < RHS, E); 1598 case BO_GT: return Success(Result.getInt() > RHS, E); 1599 case BO_LE: return Success(Result.getInt() <= RHS, E); 1600 case BO_GE: return Success(Result.getInt() >= RHS, E); 1601 case BO_EQ: return Success(Result.getInt() == RHS, E); 1602 case BO_NE: return Success(Result.getInt() != RHS, E); 1603 } 1604 } 1605 1606 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) { 1607 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1608 // the result is the size of the referenced type." 1609 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 1610 // result shall be the alignment of the referenced type." 1611 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 1612 T = Ref->getPointeeType(); 1613 1614 // __alignof is defined to return the preferred alignment. 1615 return Info.Ctx.toCharUnitsFromBits( 1616 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 1617 } 1618 1619 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) { 1620 E = E->IgnoreParens(); 1621 1622 // alignof decl is always accepted, even if it doesn't make sense: we default 1623 // to 1 in those cases. 1624 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1625 return Info.Ctx.getDeclAlign(DRE->getDecl(), 1626 /*RefAsPointee*/true); 1627 1628 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 1629 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 1630 /*RefAsPointee*/true); 1631 1632 return GetAlignOfType(E->getType()); 1633 } 1634 1635 1636 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 1637 /// a result as the expression's type. 1638 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 1639 const UnaryExprOrTypeTraitExpr *E) { 1640 switch(E->getKind()) { 1641 case UETT_AlignOf: { 1642 if (E->isArgumentType()) 1643 return Success(GetAlignOfType(E->getArgumentType()), E); 1644 else 1645 return Success(GetAlignOfExpr(E->getArgumentExpr()), E); 1646 } 1647 1648 case UETT_VecStep: { 1649 QualType Ty = E->getTypeOfArgument(); 1650 1651 if (Ty->isVectorType()) { 1652 unsigned n = Ty->getAs<VectorType>()->getNumElements(); 1653 1654 // The vec_step built-in functions that take a 3-component 1655 // vector return 4. (OpenCL 1.1 spec 6.11.12) 1656 if (n == 3) 1657 n = 4; 1658 1659 return Success(n, E); 1660 } else 1661 return Success(1, E); 1662 } 1663 1664 case UETT_SizeOf: { 1665 QualType SrcTy = E->getTypeOfArgument(); 1666 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1667 // the result is the size of the referenced type." 1668 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 1669 // result shall be the alignment of the referenced type." 1670 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 1671 SrcTy = Ref->getPointeeType(); 1672 1673 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 1674 // extension. 1675 if (SrcTy->isVoidType() || SrcTy->isFunctionType()) 1676 return Success(1, E); 1677 1678 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 1679 if (!SrcTy->isConstantSizeType()) 1680 return false; 1681 1682 // Get information about the size. 1683 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E); 1684 } 1685 } 1686 1687 llvm_unreachable("unknown expr/type trait"); 1688 return false; 1689 } 1690 1691 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 1692 CharUnits Result; 1693 unsigned n = OOE->getNumComponents(); 1694 if (n == 0) 1695 return false; 1696 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 1697 for (unsigned i = 0; i != n; ++i) { 1698 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i); 1699 switch (ON.getKind()) { 1700 case OffsetOfExpr::OffsetOfNode::Array: { 1701 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 1702 APSInt IdxResult; 1703 if (!EvaluateInteger(Idx, IdxResult, Info)) 1704 return false; 1705 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 1706 if (!AT) 1707 return false; 1708 CurrentType = AT->getElementType(); 1709 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 1710 Result += IdxResult.getSExtValue() * ElementSize; 1711 break; 1712 } 1713 1714 case OffsetOfExpr::OffsetOfNode::Field: { 1715 FieldDecl *MemberDecl = ON.getField(); 1716 const RecordType *RT = CurrentType->getAs<RecordType>(); 1717 if (!RT) 1718 return false; 1719 RecordDecl *RD = RT->getDecl(); 1720 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 1721 unsigned i = MemberDecl->getFieldIndex(); 1722 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 1723 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 1724 CurrentType = MemberDecl->getType().getNonReferenceType(); 1725 break; 1726 } 1727 1728 case OffsetOfExpr::OffsetOfNode::Identifier: 1729 llvm_unreachable("dependent __builtin_offsetof"); 1730 return false; 1731 1732 case OffsetOfExpr::OffsetOfNode::Base: { 1733 CXXBaseSpecifier *BaseSpec = ON.getBase(); 1734 if (BaseSpec->isVirtual()) 1735 return false; 1736 1737 // Find the layout of the class whose base we are looking into. 1738 const RecordType *RT = CurrentType->getAs<RecordType>(); 1739 if (!RT) 1740 return false; 1741 RecordDecl *RD = RT->getDecl(); 1742 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 1743 1744 // Find the base class itself. 1745 CurrentType = BaseSpec->getType(); 1746 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 1747 if (!BaseRT) 1748 return false; 1749 1750 // Add the offset to the base. 1751 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 1752 break; 1753 } 1754 } 1755 } 1756 return Success(Result, OOE); 1757 } 1758 1759 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 1760 if (E->getOpcode() == UO_LNot) { 1761 // LNot's operand isn't necessarily an integer, so we handle it specially. 1762 bool bres; 1763 if (!HandleConversionToBool(E->getSubExpr(), bres, Info)) 1764 return false; 1765 return Success(!bres, E); 1766 } 1767 1768 // Only handle integral operations... 1769 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType()) 1770 return false; 1771 1772 // Get the operand value into 'Result'. 1773 if (!Visit(E->getSubExpr())) 1774 return false; 1775 1776 switch (E->getOpcode()) { 1777 default: 1778 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1779 // See C99 6.6p3. 1780 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 1781 case UO_Extension: 1782 // FIXME: Should extension allow i-c-e extension expressions in its scope? 1783 // If so, we could clear the diagnostic ID. 1784 return true; 1785 case UO_Plus: 1786 // The result is always just the subexpr. 1787 return true; 1788 case UO_Minus: 1789 if (!Result.isInt()) return false; 1790 return Success(-Result.getInt(), E); 1791 case UO_Not: 1792 if (!Result.isInt()) return false; 1793 return Success(~Result.getInt(), E); 1794 } 1795 } 1796 1797 /// HandleCast - This is used to evaluate implicit or explicit casts where the 1798 /// result type is integer. 1799 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 1800 const Expr *SubExpr = E->getSubExpr(); 1801 QualType DestType = E->getType(); 1802 QualType SrcType = SubExpr->getType(); 1803 1804 switch (E->getCastKind()) { 1805 case CK_BaseToDerived: 1806 case CK_DerivedToBase: 1807 case CK_UncheckedDerivedToBase: 1808 case CK_Dynamic: 1809 case CK_ToUnion: 1810 case CK_ArrayToPointerDecay: 1811 case CK_FunctionToPointerDecay: 1812 case CK_NullToPointer: 1813 case CK_NullToMemberPointer: 1814 case CK_BaseToDerivedMemberPointer: 1815 case CK_DerivedToBaseMemberPointer: 1816 case CK_ConstructorConversion: 1817 case CK_IntegralToPointer: 1818 case CK_ToVoid: 1819 case CK_VectorSplat: 1820 case CK_IntegralToFloating: 1821 case CK_FloatingCast: 1822 case CK_CPointerToObjCPointerCast: 1823 case CK_BlockPointerToObjCPointerCast: 1824 case CK_AnyPointerToBlockPointerCast: 1825 case CK_ObjCObjectLValueCast: 1826 case CK_FloatingRealToComplex: 1827 case CK_FloatingComplexToReal: 1828 case CK_FloatingComplexCast: 1829 case CK_FloatingComplexToIntegralComplex: 1830 case CK_IntegralRealToComplex: 1831 case CK_IntegralComplexCast: 1832 case CK_IntegralComplexToFloatingComplex: 1833 llvm_unreachable("invalid cast kind for integral value"); 1834 1835 case CK_BitCast: 1836 case CK_Dependent: 1837 case CK_GetObjCProperty: 1838 case CK_LValueBitCast: 1839 case CK_UserDefinedConversion: 1840 case CK_ARCProduceObject: 1841 case CK_ARCConsumeObject: 1842 case CK_ARCReclaimReturnedObject: 1843 case CK_ARCExtendBlockObject: 1844 return false; 1845 1846 case CK_LValueToRValue: 1847 case CK_NoOp: 1848 return Visit(E->getSubExpr()); 1849 1850 case CK_MemberPointerToBoolean: 1851 case CK_PointerToBoolean: 1852 case CK_IntegralToBoolean: 1853 case CK_FloatingToBoolean: 1854 case CK_FloatingComplexToBoolean: 1855 case CK_IntegralComplexToBoolean: { 1856 bool BoolResult; 1857 if (!HandleConversionToBool(SubExpr, BoolResult, Info)) 1858 return false; 1859 return Success(BoolResult, E); 1860 } 1861 1862 case CK_IntegralCast: { 1863 if (!Visit(SubExpr)) 1864 return false; 1865 1866 if (!Result.isInt()) { 1867 // Only allow casts of lvalues if they are lossless. 1868 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 1869 } 1870 1871 return Success(HandleIntToIntCast(DestType, SrcType, 1872 Result.getInt(), Info.Ctx), E); 1873 } 1874 1875 case CK_PointerToIntegral: { 1876 LValue LV; 1877 if (!EvaluatePointer(SubExpr, LV, Info)) 1878 return false; 1879 1880 if (LV.getLValueBase()) { 1881 // Only allow based lvalue casts if they are lossless. 1882 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 1883 return false; 1884 1885 LV.moveInto(Result); 1886 return true; 1887 } 1888 1889 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(), 1890 SrcType); 1891 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E); 1892 } 1893 1894 case CK_IntegralComplexToReal: { 1895 ComplexValue C; 1896 if (!EvaluateComplex(SubExpr, C, Info)) 1897 return false; 1898 return Success(C.getComplexIntReal(), E); 1899 } 1900 1901 case CK_FloatingToIntegral: { 1902 APFloat F(0.0); 1903 if (!EvaluateFloat(SubExpr, F, Info)) 1904 return false; 1905 1906 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E); 1907 } 1908 } 1909 1910 llvm_unreachable("unknown cast resulting in integral value"); 1911 return false; 1912 } 1913 1914 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 1915 if (E->getSubExpr()->getType()->isAnyComplexType()) { 1916 ComplexValue LV; 1917 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt()) 1918 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 1919 return Success(LV.getComplexIntReal(), E); 1920 } 1921 1922 return Visit(E->getSubExpr()); 1923 } 1924 1925 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 1926 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 1927 ComplexValue LV; 1928 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt()) 1929 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 1930 return Success(LV.getComplexIntImag(), E); 1931 } 1932 1933 if (!E->getSubExpr()->isEvaluatable(Info.Ctx)) 1934 Info.EvalResult.HasSideEffects = true; 1935 return Success(0, E); 1936 } 1937 1938 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 1939 return Success(E->getPackLength(), E); 1940 } 1941 1942 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 1943 return Success(E->getValue(), E); 1944 } 1945 1946 bool IntExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 1947 if (!Info.Ctx.getLangOptions().CPlusPlus0x) 1948 return Error(E); 1949 1950 if (E->getNumInits() == 0) 1951 return Success(0, E); 1952 1953 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11."); 1954 return Visit(E->getInit(0)); 1955 } 1956 1957 //===----------------------------------------------------------------------===// 1958 // Float Evaluation 1959 //===----------------------------------------------------------------------===// 1960 1961 namespace { 1962 class FloatExprEvaluator 1963 : public ExprEvaluatorBase<FloatExprEvaluator, bool> { 1964 APFloat &Result; 1965 public: 1966 FloatExprEvaluator(EvalInfo &info, APFloat &result) 1967 : ExprEvaluatorBaseTy(info), Result(result) {} 1968 1969 bool Success(const APValue &V, const Expr *e) { 1970 Result = V.getFloat(); 1971 return true; 1972 } 1973 bool Error(const Stmt *S) { 1974 return false; 1975 } 1976 1977 bool VisitCallExpr(const CallExpr *E); 1978 1979 bool VisitUnaryOperator(const UnaryOperator *E); 1980 bool VisitBinaryOperator(const BinaryOperator *E); 1981 bool VisitFloatingLiteral(const FloatingLiteral *E); 1982 bool VisitCastExpr(const CastExpr *E); 1983 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E); 1984 1985 bool VisitUnaryReal(const UnaryOperator *E); 1986 bool VisitUnaryImag(const UnaryOperator *E); 1987 1988 bool VisitDeclRefExpr(const DeclRefExpr *E); 1989 1990 bool VisitInitListExpr(const InitListExpr *E); 1991 1992 // FIXME: Missing: array subscript of vector, member of vector, 1993 // ImplicitValueInitExpr 1994 }; 1995 } // end anonymous namespace 1996 1997 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 1998 assert(E->getType()->isRealFloatingType()); 1999 return FloatExprEvaluator(Info, Result).Visit(E); 2000 } 2001 2002 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 2003 QualType ResultTy, 2004 const Expr *Arg, 2005 bool SNaN, 2006 llvm::APFloat &Result) { 2007 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 2008 if (!S) return false; 2009 2010 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 2011 2012 llvm::APInt fill; 2013 2014 // Treat empty strings as if they were zero. 2015 if (S->getString().empty()) 2016 fill = llvm::APInt(32, 0); 2017 else if (S->getString().getAsInteger(0, fill)) 2018 return false; 2019 2020 if (SNaN) 2021 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 2022 else 2023 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 2024 return true; 2025 } 2026 2027 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 2028 switch (E->isBuiltinCall(Info.Ctx)) { 2029 default: 2030 return ExprEvaluatorBaseTy::VisitCallExpr(E); 2031 2032 case Builtin::BI__builtin_huge_val: 2033 case Builtin::BI__builtin_huge_valf: 2034 case Builtin::BI__builtin_huge_vall: 2035 case Builtin::BI__builtin_inf: 2036 case Builtin::BI__builtin_inff: 2037 case Builtin::BI__builtin_infl: { 2038 const llvm::fltSemantics &Sem = 2039 Info.Ctx.getFloatTypeSemantics(E->getType()); 2040 Result = llvm::APFloat::getInf(Sem); 2041 return true; 2042 } 2043 2044 case Builtin::BI__builtin_nans: 2045 case Builtin::BI__builtin_nansf: 2046 case Builtin::BI__builtin_nansl: 2047 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 2048 true, Result); 2049 2050 case Builtin::BI__builtin_nan: 2051 case Builtin::BI__builtin_nanf: 2052 case Builtin::BI__builtin_nanl: 2053 // If this is __builtin_nan() turn this into a nan, otherwise we 2054 // can't constant fold it. 2055 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 2056 false, Result); 2057 2058 case Builtin::BI__builtin_fabs: 2059 case Builtin::BI__builtin_fabsf: 2060 case Builtin::BI__builtin_fabsl: 2061 if (!EvaluateFloat(E->getArg(0), Result, Info)) 2062 return false; 2063 2064 if (Result.isNegative()) 2065 Result.changeSign(); 2066 return true; 2067 2068 case Builtin::BI__builtin_copysign: 2069 case Builtin::BI__builtin_copysignf: 2070 case Builtin::BI__builtin_copysignl: { 2071 APFloat RHS(0.); 2072 if (!EvaluateFloat(E->getArg(0), Result, Info) || 2073 !EvaluateFloat(E->getArg(1), RHS, Info)) 2074 return false; 2075 Result.copySign(RHS); 2076 return true; 2077 } 2078 } 2079 } 2080 2081 bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 2082 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E)) 2083 return true; 2084 2085 const Decl *D = E->getDecl(); 2086 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false; 2087 const VarDecl *VD = cast<VarDecl>(D); 2088 2089 // Require the qualifiers to be const and not volatile. 2090 CanQualType T = Info.Ctx.getCanonicalType(E->getType()); 2091 if (!T.isConstQualified() || T.isVolatileQualified()) 2092 return false; 2093 2094 const Expr *Init = VD->getAnyInitializer(); 2095 if (!Init) return false; 2096 2097 if (APValue *V = VD->getEvaluatedValue()) { 2098 if (V->isFloat()) { 2099 Result = V->getFloat(); 2100 return true; 2101 } 2102 return false; 2103 } 2104 2105 if (VD->isEvaluatingValue()) 2106 return false; 2107 2108 VD->setEvaluatingValue(); 2109 2110 Expr::EvalResult InitResult; 2111 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects && 2112 InitResult.Val.isFloat()) { 2113 // Cache the evaluated value in the variable declaration. 2114 Result = InitResult.Val.getFloat(); 2115 VD->setEvaluatedValue(InitResult.Val); 2116 return true; 2117 } 2118 2119 VD->setEvaluatedValue(APValue()); 2120 return false; 2121 } 2122 2123 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 2124 if (E->getSubExpr()->getType()->isAnyComplexType()) { 2125 ComplexValue CV; 2126 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 2127 return false; 2128 Result = CV.FloatReal; 2129 return true; 2130 } 2131 2132 return Visit(E->getSubExpr()); 2133 } 2134 2135 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 2136 if (E->getSubExpr()->getType()->isAnyComplexType()) { 2137 ComplexValue CV; 2138 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 2139 return false; 2140 Result = CV.FloatImag; 2141 return true; 2142 } 2143 2144 if (!E->getSubExpr()->isEvaluatable(Info.Ctx)) 2145 Info.EvalResult.HasSideEffects = true; 2146 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 2147 Result = llvm::APFloat::getZero(Sem); 2148 return true; 2149 } 2150 2151 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 2152 if (E->getOpcode() == UO_Deref) 2153 return false; 2154 2155 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 2156 return false; 2157 2158 switch (E->getOpcode()) { 2159 default: return false; 2160 case UO_Plus: 2161 return true; 2162 case UO_Minus: 2163 Result.changeSign(); 2164 return true; 2165 } 2166 } 2167 2168 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 2169 if (E->getOpcode() == BO_Comma) { 2170 if (!EvaluateFloat(E->getRHS(), Result, Info)) 2171 return false; 2172 2173 // If we can't evaluate the LHS, it might have side effects; 2174 // conservatively mark it. 2175 if (!E->getLHS()->isEvaluatable(Info.Ctx)) 2176 Info.EvalResult.HasSideEffects = true; 2177 2178 return true; 2179 } 2180 2181 // We can't evaluate pointer-to-member operations. 2182 if (E->isPtrMemOp()) 2183 return false; 2184 2185 // FIXME: Diagnostics? I really don't understand how the warnings 2186 // and errors are supposed to work. 2187 APFloat RHS(0.0); 2188 if (!EvaluateFloat(E->getLHS(), Result, Info)) 2189 return false; 2190 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 2191 return false; 2192 2193 switch (E->getOpcode()) { 2194 default: return false; 2195 case BO_Mul: 2196 Result.multiply(RHS, APFloat::rmNearestTiesToEven); 2197 return true; 2198 case BO_Add: 2199 Result.add(RHS, APFloat::rmNearestTiesToEven); 2200 return true; 2201 case BO_Sub: 2202 Result.subtract(RHS, APFloat::rmNearestTiesToEven); 2203 return true; 2204 case BO_Div: 2205 Result.divide(RHS, APFloat::rmNearestTiesToEven); 2206 return true; 2207 } 2208 } 2209 2210 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 2211 Result = E->getValue(); 2212 return true; 2213 } 2214 2215 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 2216 const Expr* SubExpr = E->getSubExpr(); 2217 2218 switch (E->getCastKind()) { 2219 default: 2220 return false; 2221 2222 case CK_LValueToRValue: 2223 case CK_NoOp: 2224 return Visit(SubExpr); 2225 2226 case CK_IntegralToFloating: { 2227 APSInt IntResult; 2228 if (!EvaluateInteger(SubExpr, IntResult, Info)) 2229 return false; 2230 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(), 2231 IntResult, Info.Ctx); 2232 return true; 2233 } 2234 2235 case CK_FloatingCast: { 2236 if (!Visit(SubExpr)) 2237 return false; 2238 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(), 2239 Result, Info.Ctx); 2240 return true; 2241 } 2242 2243 case CK_FloatingComplexToReal: { 2244 ComplexValue V; 2245 if (!EvaluateComplex(SubExpr, V, Info)) 2246 return false; 2247 Result = V.getComplexFloatReal(); 2248 return true; 2249 } 2250 } 2251 2252 return false; 2253 } 2254 2255 bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 2256 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 2257 return true; 2258 } 2259 2260 bool FloatExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 2261 if (!Info.Ctx.getLangOptions().CPlusPlus0x) 2262 return Error(E); 2263 2264 if (E->getNumInits() == 0) { 2265 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 2266 return true; 2267 } 2268 2269 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11."); 2270 return Visit(E->getInit(0)); 2271 } 2272 2273 //===----------------------------------------------------------------------===// 2274 // Complex Evaluation (for float and integer) 2275 //===----------------------------------------------------------------------===// 2276 2277 namespace { 2278 class ComplexExprEvaluator 2279 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> { 2280 ComplexValue &Result; 2281 2282 public: 2283 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 2284 : ExprEvaluatorBaseTy(info), Result(Result) {} 2285 2286 bool Success(const APValue &V, const Expr *e) { 2287 Result.setFrom(V); 2288 return true; 2289 } 2290 bool Error(const Expr *E) { 2291 return false; 2292 } 2293 2294 //===--------------------------------------------------------------------===// 2295 // Visitor Methods 2296 //===--------------------------------------------------------------------===// 2297 2298 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 2299 2300 bool VisitCastExpr(const CastExpr *E); 2301 2302 bool VisitBinaryOperator(const BinaryOperator *E); 2303 bool VisitUnaryOperator(const UnaryOperator *E); 2304 // FIXME Missing: ImplicitValueInitExpr, InitListExpr 2305 }; 2306 } // end anonymous namespace 2307 2308 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 2309 EvalInfo &Info) { 2310 assert(E->getType()->isAnyComplexType()); 2311 return ComplexExprEvaluator(Info, Result).Visit(E); 2312 } 2313 2314 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 2315 const Expr* SubExpr = E->getSubExpr(); 2316 2317 if (SubExpr->getType()->isRealFloatingType()) { 2318 Result.makeComplexFloat(); 2319 APFloat &Imag = Result.FloatImag; 2320 if (!EvaluateFloat(SubExpr, Imag, Info)) 2321 return false; 2322 2323 Result.FloatReal = APFloat(Imag.getSemantics()); 2324 return true; 2325 } else { 2326 assert(SubExpr->getType()->isIntegerType() && 2327 "Unexpected imaginary literal."); 2328 2329 Result.makeComplexInt(); 2330 APSInt &Imag = Result.IntImag; 2331 if (!EvaluateInteger(SubExpr, Imag, Info)) 2332 return false; 2333 2334 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 2335 return true; 2336 } 2337 } 2338 2339 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 2340 2341 switch (E->getCastKind()) { 2342 case CK_BitCast: 2343 case CK_BaseToDerived: 2344 case CK_DerivedToBase: 2345 case CK_UncheckedDerivedToBase: 2346 case CK_Dynamic: 2347 case CK_ToUnion: 2348 case CK_ArrayToPointerDecay: 2349 case CK_FunctionToPointerDecay: 2350 case CK_NullToPointer: 2351 case CK_NullToMemberPointer: 2352 case CK_BaseToDerivedMemberPointer: 2353 case CK_DerivedToBaseMemberPointer: 2354 case CK_MemberPointerToBoolean: 2355 case CK_ConstructorConversion: 2356 case CK_IntegralToPointer: 2357 case CK_PointerToIntegral: 2358 case CK_PointerToBoolean: 2359 case CK_ToVoid: 2360 case CK_VectorSplat: 2361 case CK_IntegralCast: 2362 case CK_IntegralToBoolean: 2363 case CK_IntegralToFloating: 2364 case CK_FloatingToIntegral: 2365 case CK_FloatingToBoolean: 2366 case CK_FloatingCast: 2367 case CK_CPointerToObjCPointerCast: 2368 case CK_BlockPointerToObjCPointerCast: 2369 case CK_AnyPointerToBlockPointerCast: 2370 case CK_ObjCObjectLValueCast: 2371 case CK_FloatingComplexToReal: 2372 case CK_FloatingComplexToBoolean: 2373 case CK_IntegralComplexToReal: 2374 case CK_IntegralComplexToBoolean: 2375 case CK_ARCProduceObject: 2376 case CK_ARCConsumeObject: 2377 case CK_ARCReclaimReturnedObject: 2378 case CK_ARCExtendBlockObject: 2379 llvm_unreachable("invalid cast kind for complex value"); 2380 2381 case CK_LValueToRValue: 2382 case CK_NoOp: 2383 return Visit(E->getSubExpr()); 2384 2385 case CK_Dependent: 2386 case CK_GetObjCProperty: 2387 case CK_LValueBitCast: 2388 case CK_UserDefinedConversion: 2389 return false; 2390 2391 case CK_FloatingRealToComplex: { 2392 APFloat &Real = Result.FloatReal; 2393 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 2394 return false; 2395 2396 Result.makeComplexFloat(); 2397 Result.FloatImag = APFloat(Real.getSemantics()); 2398 return true; 2399 } 2400 2401 case CK_FloatingComplexCast: { 2402 if (!Visit(E->getSubExpr())) 2403 return false; 2404 2405 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2406 QualType From 2407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2408 2409 Result.FloatReal 2410 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx); 2411 Result.FloatImag 2412 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx); 2413 return true; 2414 } 2415 2416 case CK_FloatingComplexToIntegralComplex: { 2417 if (!Visit(E->getSubExpr())) 2418 return false; 2419 2420 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2421 QualType From 2422 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2423 Result.makeComplexInt(); 2424 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx); 2425 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx); 2426 return true; 2427 } 2428 2429 case CK_IntegralRealToComplex: { 2430 APSInt &Real = Result.IntReal; 2431 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 2432 return false; 2433 2434 Result.makeComplexInt(); 2435 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 2436 return true; 2437 } 2438 2439 case CK_IntegralComplexCast: { 2440 if (!Visit(E->getSubExpr())) 2441 return false; 2442 2443 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2444 QualType From 2445 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2446 2447 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx); 2448 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx); 2449 return true; 2450 } 2451 2452 case CK_IntegralComplexToFloatingComplex: { 2453 if (!Visit(E->getSubExpr())) 2454 return false; 2455 2456 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2457 QualType From 2458 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2459 Result.makeComplexFloat(); 2460 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx); 2461 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx); 2462 return true; 2463 } 2464 } 2465 2466 llvm_unreachable("unknown cast resulting in complex value"); 2467 return false; 2468 } 2469 2470 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 2471 if (E->getOpcode() == BO_Comma) { 2472 if (!Visit(E->getRHS())) 2473 return false; 2474 2475 // If we can't evaluate the LHS, it might have side effects; 2476 // conservatively mark it. 2477 if (!E->getLHS()->isEvaluatable(Info.Ctx)) 2478 Info.EvalResult.HasSideEffects = true; 2479 2480 return true; 2481 } 2482 if (!Visit(E->getLHS())) 2483 return false; 2484 2485 ComplexValue RHS; 2486 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 2487 return false; 2488 2489 assert(Result.isComplexFloat() == RHS.isComplexFloat() && 2490 "Invalid operands to binary operator."); 2491 switch (E->getOpcode()) { 2492 default: return false; 2493 case BO_Add: 2494 if (Result.isComplexFloat()) { 2495 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 2496 APFloat::rmNearestTiesToEven); 2497 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 2498 APFloat::rmNearestTiesToEven); 2499 } else { 2500 Result.getComplexIntReal() += RHS.getComplexIntReal(); 2501 Result.getComplexIntImag() += RHS.getComplexIntImag(); 2502 } 2503 break; 2504 case BO_Sub: 2505 if (Result.isComplexFloat()) { 2506 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 2507 APFloat::rmNearestTiesToEven); 2508 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 2509 APFloat::rmNearestTiesToEven); 2510 } else { 2511 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 2512 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 2513 } 2514 break; 2515 case BO_Mul: 2516 if (Result.isComplexFloat()) { 2517 ComplexValue LHS = Result; 2518 APFloat &LHS_r = LHS.getComplexFloatReal(); 2519 APFloat &LHS_i = LHS.getComplexFloatImag(); 2520 APFloat &RHS_r = RHS.getComplexFloatReal(); 2521 APFloat &RHS_i = RHS.getComplexFloatImag(); 2522 2523 APFloat Tmp = LHS_r; 2524 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2525 Result.getComplexFloatReal() = Tmp; 2526 Tmp = LHS_i; 2527 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2528 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven); 2529 2530 Tmp = LHS_r; 2531 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2532 Result.getComplexFloatImag() = Tmp; 2533 Tmp = LHS_i; 2534 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2535 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven); 2536 } else { 2537 ComplexValue LHS = Result; 2538 Result.getComplexIntReal() = 2539 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 2540 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 2541 Result.getComplexIntImag() = 2542 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 2543 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 2544 } 2545 break; 2546 case BO_Div: 2547 if (Result.isComplexFloat()) { 2548 ComplexValue LHS = Result; 2549 APFloat &LHS_r = LHS.getComplexFloatReal(); 2550 APFloat &LHS_i = LHS.getComplexFloatImag(); 2551 APFloat &RHS_r = RHS.getComplexFloatReal(); 2552 APFloat &RHS_i = RHS.getComplexFloatImag(); 2553 APFloat &Res_r = Result.getComplexFloatReal(); 2554 APFloat &Res_i = Result.getComplexFloatImag(); 2555 2556 APFloat Den = RHS_r; 2557 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2558 APFloat Tmp = RHS_i; 2559 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2560 Den.add(Tmp, APFloat::rmNearestTiesToEven); 2561 2562 Res_r = LHS_r; 2563 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2564 Tmp = LHS_i; 2565 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2566 Res_r.add(Tmp, APFloat::rmNearestTiesToEven); 2567 Res_r.divide(Den, APFloat::rmNearestTiesToEven); 2568 2569 Res_i = LHS_i; 2570 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2571 Tmp = LHS_r; 2572 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2573 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven); 2574 Res_i.divide(Den, APFloat::rmNearestTiesToEven); 2575 } else { 2576 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) { 2577 // FIXME: what about diagnostics? 2578 return false; 2579 } 2580 ComplexValue LHS = Result; 2581 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 2582 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 2583 Result.getComplexIntReal() = 2584 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 2585 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 2586 Result.getComplexIntImag() = 2587 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 2588 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 2589 } 2590 break; 2591 } 2592 2593 return true; 2594 } 2595 2596 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 2597 // Get the operand value into 'Result'. 2598 if (!Visit(E->getSubExpr())) 2599 return false; 2600 2601 switch (E->getOpcode()) { 2602 default: 2603 // FIXME: what about diagnostics? 2604 return false; 2605 case UO_Extension: 2606 return true; 2607 case UO_Plus: 2608 // The result is always just the subexpr. 2609 return true; 2610 case UO_Minus: 2611 if (Result.isComplexFloat()) { 2612 Result.getComplexFloatReal().changeSign(); 2613 Result.getComplexFloatImag().changeSign(); 2614 } 2615 else { 2616 Result.getComplexIntReal() = -Result.getComplexIntReal(); 2617 Result.getComplexIntImag() = -Result.getComplexIntImag(); 2618 } 2619 return true; 2620 case UO_Not: 2621 if (Result.isComplexFloat()) 2622 Result.getComplexFloatImag().changeSign(); 2623 else 2624 Result.getComplexIntImag() = -Result.getComplexIntImag(); 2625 return true; 2626 } 2627 } 2628 2629 //===----------------------------------------------------------------------===// 2630 // Top level Expr::Evaluate method. 2631 //===----------------------------------------------------------------------===// 2632 2633 static bool Evaluate(EvalInfo &Info, const Expr *E) { 2634 if (E->getType()->isVectorType()) { 2635 if (!EvaluateVector(E, Info.EvalResult.Val, Info)) 2636 return false; 2637 } else if (E->getType()->isIntegralOrEnumerationType()) { 2638 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E)) 2639 return false; 2640 if (Info.EvalResult.Val.isLValue() && 2641 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase())) 2642 return false; 2643 } else if (E->getType()->hasPointerRepresentation()) { 2644 LValue LV; 2645 if (!EvaluatePointer(E, LV, Info)) 2646 return false; 2647 if (!IsGlobalLValue(LV.Base)) 2648 return false; 2649 LV.moveInto(Info.EvalResult.Val); 2650 } else if (E->getType()->isRealFloatingType()) { 2651 llvm::APFloat F(0.0); 2652 if (!EvaluateFloat(E, F, Info)) 2653 return false; 2654 2655 Info.EvalResult.Val = APValue(F); 2656 } else if (E->getType()->isAnyComplexType()) { 2657 ComplexValue C; 2658 if (!EvaluateComplex(E, C, Info)) 2659 return false; 2660 C.moveInto(Info.EvalResult.Val); 2661 } else 2662 return false; 2663 2664 return true; 2665 } 2666 2667 /// Evaluate - Return true if this is a constant which we can fold using 2668 /// any crazy technique (that has nothing to do with language standards) that 2669 /// we want to. If this function returns true, it returns the folded constant 2670 /// in Result. 2671 bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const { 2672 EvalInfo Info(Ctx, Result); 2673 return ::Evaluate(Info, this); 2674 } 2675 2676 bool Expr::EvaluateAsBooleanCondition(bool &Result, 2677 const ASTContext &Ctx) const { 2678 EvalResult Scratch; 2679 EvalInfo Info(Ctx, Scratch); 2680 2681 return HandleConversionToBool(this, Result, Info); 2682 } 2683 2684 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 2685 EvalInfo Info(Ctx, Result); 2686 2687 LValue LV; 2688 if (EvaluateLValue(this, LV, Info) && 2689 !Result.HasSideEffects && 2690 IsGlobalLValue(LV.Base)) { 2691 LV.moveInto(Result.Val); 2692 return true; 2693 } 2694 return false; 2695 } 2696 2697 bool Expr::EvaluateAsAnyLValue(EvalResult &Result, 2698 const ASTContext &Ctx) const { 2699 EvalInfo Info(Ctx, Result); 2700 2701 LValue LV; 2702 if (EvaluateLValue(this, LV, Info)) { 2703 LV.moveInto(Result.Val); 2704 return true; 2705 } 2706 return false; 2707 } 2708 2709 /// isEvaluatable - Call Evaluate to see if this expression can be constant 2710 /// folded, but discard the result. 2711 bool Expr::isEvaluatable(const ASTContext &Ctx) const { 2712 EvalResult Result; 2713 return Evaluate(Result, Ctx) && !Result.HasSideEffects; 2714 } 2715 2716 bool Expr::HasSideEffects(const ASTContext &Ctx) const { 2717 Expr::EvalResult Result; 2718 EvalInfo Info(Ctx, Result); 2719 return HasSideEffect(Info).Visit(this); 2720 } 2721 2722 APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const { 2723 EvalResult EvalResult; 2724 bool Result = Evaluate(EvalResult, Ctx); 2725 (void)Result; 2726 assert(Result && "Could not evaluate expression"); 2727 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 2728 2729 return EvalResult.Val.getInt(); 2730 } 2731 2732 bool Expr::EvalResult::isGlobalLValue() const { 2733 assert(Val.isLValue()); 2734 return IsGlobalLValue(Val.getLValueBase()); 2735 } 2736 2737 2738 /// isIntegerConstantExpr - this recursive routine will test if an expression is 2739 /// an integer constant expression. 2740 2741 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 2742 /// comma, etc 2743 /// 2744 /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof 2745 /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer 2746 /// cast+dereference. 2747 2748 // CheckICE - This function does the fundamental ICE checking: the returned 2749 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation. 2750 // Note that to reduce code duplication, this helper does no evaluation 2751 // itself; the caller checks whether the expression is evaluatable, and 2752 // in the rare cases where CheckICE actually cares about the evaluated 2753 // value, it calls into Evalute. 2754 // 2755 // Meanings of Val: 2756 // 0: This expression is an ICE if it can be evaluated by Evaluate. 2757 // 1: This expression is not an ICE, but if it isn't evaluated, it's 2758 // a legal subexpression for an ICE. This return value is used to handle 2759 // the comma operator in C99 mode. 2760 // 2: This expression is not an ICE, and is not a legal subexpression for one. 2761 2762 namespace { 2763 2764 struct ICEDiag { 2765 unsigned Val; 2766 SourceLocation Loc; 2767 2768 public: 2769 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {} 2770 ICEDiag() : Val(0) {} 2771 }; 2772 2773 } 2774 2775 static ICEDiag NoDiag() { return ICEDiag(); } 2776 2777 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) { 2778 Expr::EvalResult EVResult; 2779 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects || 2780 !EVResult.Val.isInt()) { 2781 return ICEDiag(2, E->getLocStart()); 2782 } 2783 return NoDiag(); 2784 } 2785 2786 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { 2787 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 2788 if (!E->getType()->isIntegralOrEnumerationType()) { 2789 return ICEDiag(2, E->getLocStart()); 2790 } 2791 2792 switch (E->getStmtClass()) { 2793 #define ABSTRACT_STMT(Node) 2794 #define STMT(Node, Base) case Expr::Node##Class: 2795 #define EXPR(Node, Base) 2796 #include "clang/AST/StmtNodes.inc" 2797 case Expr::PredefinedExprClass: 2798 case Expr::FloatingLiteralClass: 2799 case Expr::ImaginaryLiteralClass: 2800 case Expr::StringLiteralClass: 2801 case Expr::ArraySubscriptExprClass: 2802 case Expr::MemberExprClass: 2803 case Expr::CompoundAssignOperatorClass: 2804 case Expr::CompoundLiteralExprClass: 2805 case Expr::ExtVectorElementExprClass: 2806 case Expr::DesignatedInitExprClass: 2807 case Expr::ImplicitValueInitExprClass: 2808 case Expr::ParenListExprClass: 2809 case Expr::VAArgExprClass: 2810 case Expr::AddrLabelExprClass: 2811 case Expr::StmtExprClass: 2812 case Expr::CXXMemberCallExprClass: 2813 case Expr::CUDAKernelCallExprClass: 2814 case Expr::CXXDynamicCastExprClass: 2815 case Expr::CXXTypeidExprClass: 2816 case Expr::CXXUuidofExprClass: 2817 case Expr::CXXNullPtrLiteralExprClass: 2818 case Expr::CXXThisExprClass: 2819 case Expr::CXXThrowExprClass: 2820 case Expr::CXXNewExprClass: 2821 case Expr::CXXDeleteExprClass: 2822 case Expr::CXXPseudoDestructorExprClass: 2823 case Expr::UnresolvedLookupExprClass: 2824 case Expr::DependentScopeDeclRefExprClass: 2825 case Expr::CXXConstructExprClass: 2826 case Expr::CXXBindTemporaryExprClass: 2827 case Expr::ExprWithCleanupsClass: 2828 case Expr::CXXTemporaryObjectExprClass: 2829 case Expr::CXXUnresolvedConstructExprClass: 2830 case Expr::CXXDependentScopeMemberExprClass: 2831 case Expr::UnresolvedMemberExprClass: 2832 case Expr::ObjCStringLiteralClass: 2833 case Expr::ObjCEncodeExprClass: 2834 case Expr::ObjCMessageExprClass: 2835 case Expr::ObjCSelectorExprClass: 2836 case Expr::ObjCProtocolExprClass: 2837 case Expr::ObjCIvarRefExprClass: 2838 case Expr::ObjCPropertyRefExprClass: 2839 case Expr::ObjCIsaExprClass: 2840 case Expr::ShuffleVectorExprClass: 2841 case Expr::BlockExprClass: 2842 case Expr::BlockDeclRefExprClass: 2843 case Expr::NoStmtClass: 2844 case Expr::OpaqueValueExprClass: 2845 case Expr::PackExpansionExprClass: 2846 case Expr::SubstNonTypeTemplateParmPackExprClass: 2847 case Expr::AsTypeExprClass: 2848 case Expr::ObjCIndirectCopyRestoreExprClass: 2849 case Expr::MaterializeTemporaryExprClass: 2850 return ICEDiag(2, E->getLocStart()); 2851 2852 case Expr::InitListExprClass: 2853 if (Ctx.getLangOptions().CPlusPlus0x) { 2854 const InitListExpr *ILE = cast<InitListExpr>(E); 2855 if (ILE->getNumInits() == 0) 2856 return NoDiag(); 2857 if (ILE->getNumInits() == 1) 2858 return CheckICE(ILE->getInit(0), Ctx); 2859 // Fall through for more than 1 expression. 2860 } 2861 return ICEDiag(2, E->getLocStart()); 2862 2863 case Expr::SizeOfPackExprClass: 2864 case Expr::GNUNullExprClass: 2865 // GCC considers the GNU __null value to be an integral constant expression. 2866 return NoDiag(); 2867 2868 case Expr::SubstNonTypeTemplateParmExprClass: 2869 return 2870 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 2871 2872 case Expr::ParenExprClass: 2873 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 2874 case Expr::GenericSelectionExprClass: 2875 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 2876 case Expr::IntegerLiteralClass: 2877 case Expr::CharacterLiteralClass: 2878 case Expr::CXXBoolLiteralExprClass: 2879 case Expr::CXXScalarValueInitExprClass: 2880 case Expr::UnaryTypeTraitExprClass: 2881 case Expr::BinaryTypeTraitExprClass: 2882 case Expr::ArrayTypeTraitExprClass: 2883 case Expr::ExpressionTraitExprClass: 2884 case Expr::CXXNoexceptExprClass: 2885 return NoDiag(); 2886 case Expr::CallExprClass: 2887 case Expr::CXXOperatorCallExprClass: { 2888 const CallExpr *CE = cast<CallExpr>(E); 2889 if (CE->isBuiltinCall(Ctx)) 2890 return CheckEvalInICE(E, Ctx); 2891 return ICEDiag(2, E->getLocStart()); 2892 } 2893 case Expr::DeclRefExprClass: 2894 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 2895 return NoDiag(); 2896 if (Ctx.getLangOptions().CPlusPlus && 2897 E->getType().getCVRQualifiers() == Qualifiers::Const) { 2898 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 2899 2900 // Parameter variables are never constants. Without this check, 2901 // getAnyInitializer() can find a default argument, which leads 2902 // to chaos. 2903 if (isa<ParmVarDecl>(D)) 2904 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2905 2906 // C++ 7.1.5.1p2 2907 // A variable of non-volatile const-qualified integral or enumeration 2908 // type initialized by an ICE can be used in ICEs. 2909 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 2910 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers(); 2911 if (Quals.hasVolatile() || !Quals.hasConst()) 2912 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2913 2914 // Look for a declaration of this variable that has an initializer. 2915 const VarDecl *ID = 0; 2916 const Expr *Init = Dcl->getAnyInitializer(ID); 2917 if (Init) { 2918 if (ID->isInitKnownICE()) { 2919 // We have already checked whether this subexpression is an 2920 // integral constant expression. 2921 if (ID->isInitICE()) 2922 return NoDiag(); 2923 else 2924 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2925 } 2926 2927 // It's an ICE whether or not the definition we found is 2928 // out-of-line. See DR 721 and the discussion in Clang PR 2929 // 6206 for details. 2930 2931 if (Dcl->isCheckingICE()) { 2932 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2933 } 2934 2935 Dcl->setCheckingICE(); 2936 ICEDiag Result = CheckICE(Init, Ctx); 2937 // Cache the result of the ICE test. 2938 Dcl->setInitKnownICE(Result.Val == 0); 2939 return Result; 2940 } 2941 } 2942 } 2943 return ICEDiag(2, E->getLocStart()); 2944 case Expr::UnaryOperatorClass: { 2945 const UnaryOperator *Exp = cast<UnaryOperator>(E); 2946 switch (Exp->getOpcode()) { 2947 case UO_PostInc: 2948 case UO_PostDec: 2949 case UO_PreInc: 2950 case UO_PreDec: 2951 case UO_AddrOf: 2952 case UO_Deref: 2953 return ICEDiag(2, E->getLocStart()); 2954 case UO_Extension: 2955 case UO_LNot: 2956 case UO_Plus: 2957 case UO_Minus: 2958 case UO_Not: 2959 case UO_Real: 2960 case UO_Imag: 2961 return CheckICE(Exp->getSubExpr(), Ctx); 2962 } 2963 2964 // OffsetOf falls through here. 2965 } 2966 case Expr::OffsetOfExprClass: { 2967 // Note that per C99, offsetof must be an ICE. And AFAIK, using 2968 // Evaluate matches the proposed gcc behavior for cases like 2969 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect 2970 // compliance: we should warn earlier for offsetof expressions with 2971 // array subscripts that aren't ICEs, and if the array subscripts 2972 // are ICEs, the value of the offsetof must be an integer constant. 2973 return CheckEvalInICE(E, Ctx); 2974 } 2975 case Expr::UnaryExprOrTypeTraitExprClass: { 2976 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 2977 if ((Exp->getKind() == UETT_SizeOf) && 2978 Exp->getTypeOfArgument()->isVariableArrayType()) 2979 return ICEDiag(2, E->getLocStart()); 2980 return NoDiag(); 2981 } 2982 case Expr::BinaryOperatorClass: { 2983 const BinaryOperator *Exp = cast<BinaryOperator>(E); 2984 switch (Exp->getOpcode()) { 2985 case BO_PtrMemD: 2986 case BO_PtrMemI: 2987 case BO_Assign: 2988 case BO_MulAssign: 2989 case BO_DivAssign: 2990 case BO_RemAssign: 2991 case BO_AddAssign: 2992 case BO_SubAssign: 2993 case BO_ShlAssign: 2994 case BO_ShrAssign: 2995 case BO_AndAssign: 2996 case BO_XorAssign: 2997 case BO_OrAssign: 2998 return ICEDiag(2, E->getLocStart()); 2999 3000 case BO_Mul: 3001 case BO_Div: 3002 case BO_Rem: 3003 case BO_Add: 3004 case BO_Sub: 3005 case BO_Shl: 3006 case BO_Shr: 3007 case BO_LT: 3008 case BO_GT: 3009 case BO_LE: 3010 case BO_GE: 3011 case BO_EQ: 3012 case BO_NE: 3013 case BO_And: 3014 case BO_Xor: 3015 case BO_Or: 3016 case BO_Comma: { 3017 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 3018 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 3019 if (Exp->getOpcode() == BO_Div || 3020 Exp->getOpcode() == BO_Rem) { 3021 // Evaluate gives an error for undefined Div/Rem, so make sure 3022 // we don't evaluate one. 3023 if (LHSResult.Val == 0 && RHSResult.Val == 0) { 3024 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx); 3025 if (REval == 0) 3026 return ICEDiag(1, E->getLocStart()); 3027 if (REval.isSigned() && REval.isAllOnesValue()) { 3028 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx); 3029 if (LEval.isMinSignedValue()) 3030 return ICEDiag(1, E->getLocStart()); 3031 } 3032 } 3033 } 3034 if (Exp->getOpcode() == BO_Comma) { 3035 if (Ctx.getLangOptions().C99) { 3036 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 3037 // if it isn't evaluated. 3038 if (LHSResult.Val == 0 && RHSResult.Val == 0) 3039 return ICEDiag(1, E->getLocStart()); 3040 } else { 3041 // In both C89 and C++, commas in ICEs are illegal. 3042 return ICEDiag(2, E->getLocStart()); 3043 } 3044 } 3045 if (LHSResult.Val >= RHSResult.Val) 3046 return LHSResult; 3047 return RHSResult; 3048 } 3049 case BO_LAnd: 3050 case BO_LOr: { 3051 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 3052 3053 // C++0x [expr.const]p2: 3054 // [...] subexpressions of logical AND (5.14), logical OR 3055 // (5.15), and condi- tional (5.16) operations that are not 3056 // evaluated are not considered. 3057 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) { 3058 if (Exp->getOpcode() == BO_LAnd && 3059 Exp->getLHS()->EvaluateAsInt(Ctx) == 0) 3060 return LHSResult; 3061 3062 if (Exp->getOpcode() == BO_LOr && 3063 Exp->getLHS()->EvaluateAsInt(Ctx) != 0) 3064 return LHSResult; 3065 } 3066 3067 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 3068 if (LHSResult.Val == 0 && RHSResult.Val == 1) { 3069 // Rare case where the RHS has a comma "side-effect"; we need 3070 // to actually check the condition to see whether the side 3071 // with the comma is evaluated. 3072 if ((Exp->getOpcode() == BO_LAnd) != 3073 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0)) 3074 return RHSResult; 3075 return NoDiag(); 3076 } 3077 3078 if (LHSResult.Val >= RHSResult.Val) 3079 return LHSResult; 3080 return RHSResult; 3081 } 3082 } 3083 } 3084 case Expr::ImplicitCastExprClass: 3085 case Expr::CStyleCastExprClass: 3086 case Expr::CXXFunctionalCastExprClass: 3087 case Expr::CXXStaticCastExprClass: 3088 case Expr::CXXReinterpretCastExprClass: 3089 case Expr::CXXConstCastExprClass: 3090 case Expr::ObjCBridgedCastExprClass: { 3091 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 3092 switch (cast<CastExpr>(E)->getCastKind()) { 3093 case CK_LValueToRValue: 3094 case CK_NoOp: 3095 case CK_IntegralToBoolean: 3096 case CK_IntegralCast: 3097 return CheckICE(SubExpr, Ctx); 3098 default: 3099 if (isa<FloatingLiteral>(SubExpr->IgnoreParens())) 3100 return NoDiag(); 3101 return ICEDiag(2, E->getLocStart()); 3102 } 3103 } 3104 case Expr::BinaryConditionalOperatorClass: { 3105 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 3106 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 3107 if (CommonResult.Val == 2) return CommonResult; 3108 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 3109 if (FalseResult.Val == 2) return FalseResult; 3110 if (CommonResult.Val == 1) return CommonResult; 3111 if (FalseResult.Val == 1 && 3112 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag(); 3113 return FalseResult; 3114 } 3115 case Expr::ConditionalOperatorClass: { 3116 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 3117 // If the condition (ignoring parens) is a __builtin_constant_p call, 3118 // then only the true side is actually considered in an integer constant 3119 // expression, and it is fully evaluated. This is an important GNU 3120 // extension. See GCC PR38377 for discussion. 3121 if (const CallExpr *CallCE 3122 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 3123 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) { 3124 Expr::EvalResult EVResult; 3125 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects || 3126 !EVResult.Val.isInt()) { 3127 return ICEDiag(2, E->getLocStart()); 3128 } 3129 return NoDiag(); 3130 } 3131 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 3132 if (CondResult.Val == 2) 3133 return CondResult; 3134 3135 // C++0x [expr.const]p2: 3136 // subexpressions of [...] conditional (5.16) operations that 3137 // are not evaluated are not considered 3138 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x 3139 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0 3140 : false; 3141 ICEDiag TrueResult = NoDiag(); 3142 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch) 3143 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 3144 ICEDiag FalseResult = NoDiag(); 3145 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch) 3146 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 3147 3148 if (TrueResult.Val == 2) 3149 return TrueResult; 3150 if (FalseResult.Val == 2) 3151 return FalseResult; 3152 if (CondResult.Val == 1) 3153 return CondResult; 3154 if (TrueResult.Val == 0 && FalseResult.Val == 0) 3155 return NoDiag(); 3156 // Rare case where the diagnostics depend on which side is evaluated 3157 // Note that if we get here, CondResult is 0, and at least one of 3158 // TrueResult and FalseResult is non-zero. 3159 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) { 3160 return FalseResult; 3161 } 3162 return TrueResult; 3163 } 3164 case Expr::CXXDefaultArgExprClass: 3165 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 3166 case Expr::ChooseExprClass: { 3167 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx); 3168 } 3169 } 3170 3171 // Silence a GCC warning 3172 return ICEDiag(2, E->getLocStart()); 3173 } 3174 3175 bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, 3176 SourceLocation *Loc, bool isEvaluated) const { 3177 ICEDiag d = CheckICE(this, Ctx); 3178 if (d.Val != 0) { 3179 if (Loc) *Loc = d.Loc; 3180 return false; 3181 } 3182 EvalResult EvalResult; 3183 if (!Evaluate(EvalResult, Ctx)) 3184 llvm_unreachable("ICE cannot be evaluated!"); 3185 assert(!EvalResult.HasSideEffects && "ICE with side effects!"); 3186 assert(EvalResult.Val.isInt() && "ICE that isn't integer!"); 3187 Result = EvalResult.Val.getInt(); 3188 return true; 3189 } 3190