ExprConstant.cpp revision 4087e24f73d05d96ac2d259679751d054d3ddfbc
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/RecordLayout.h" 17#include "clang/AST/StmtVisitor.h" 18#include "clang/AST/ASTDiagnostic.h" 19#include "clang/Basic/TargetInfo.h" 20#include "llvm/Support/Compiler.h" 21using namespace clang; 22using llvm::APSInt; 23using llvm::APFloat; 24 25/// EvalInfo - This is a private struct used by the evaluator to capture 26/// information about a subexpression as it is folded. It retains information 27/// about the AST context, but also maintains information about the folded 28/// expression. 29/// 30/// If an expression could be evaluated, it is still possible it is not a C 31/// "integer constant expression" or constant expression. If not, this struct 32/// captures information about how and why not. 33/// 34/// One bit of information passed *into* the request for constant folding 35/// indicates whether the subexpression is "evaluated" or not according to C 36/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 37/// evaluate the expression regardless of what the RHS is, but C only allows 38/// certain things in certain situations. 39struct EvalInfo { 40 ASTContext &Ctx; 41 42 /// EvalResult - Contains information about the evaluation. 43 Expr::EvalResult &EvalResult; 44 45 /// ShortCircuit - will be greater than zero if the current subexpression has 46 /// will not be evaluated because it's short-circuited (according to C rules). 47 unsigned ShortCircuit; 48 49 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx), 50 EvalResult(evalresult), ShortCircuit(0) {} 51}; 52 53 54static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info); 55static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info); 56static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 57static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 58static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info); 59 60//===----------------------------------------------------------------------===// 61// Misc utilities 62//===----------------------------------------------------------------------===// 63 64static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) { 65 if (E->getType()->isIntegralType()) { 66 APSInt IntResult; 67 if (!EvaluateInteger(E, IntResult, Info)) 68 return false; 69 Result = IntResult != 0; 70 return true; 71 } else if (E->getType()->isRealFloatingType()) { 72 APFloat FloatResult(0.0); 73 if (!EvaluateFloat(E, FloatResult, Info)) 74 return false; 75 Result = !FloatResult.isZero(); 76 return true; 77 } else if (E->getType()->isPointerType()) { 78 APValue PointerResult; 79 if (!EvaluatePointer(E, PointerResult, Info)) 80 return false; 81 // FIXME: Is this accurate for all kinds of bases? If not, what would 82 // the check look like? 83 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset(); 84 return true; 85 } 86 87 return false; 88} 89 90static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType, 91 APFloat &Value, ASTContext &Ctx) { 92 unsigned DestWidth = Ctx.getIntWidth(DestType); 93 // Determine whether we are converting to unsigned or signed. 94 bool DestSigned = DestType->isSignedIntegerType(); 95 96 // FIXME: Warning for overflow. 97 uint64_t Space[4]; 98 bool ignored; 99 (void)Value.convertToInteger(Space, DestWidth, DestSigned, 100 llvm::APFloat::rmTowardZero, &ignored); 101 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned); 102} 103 104static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType, 105 APFloat &Value, ASTContext &Ctx) { 106 bool ignored; 107 APFloat Result = Value; 108 Result.convert(Ctx.getFloatTypeSemantics(DestType), 109 APFloat::rmNearestTiesToEven, &ignored); 110 return Result; 111} 112 113static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, 114 APSInt &Value, ASTContext &Ctx) { 115 unsigned DestWidth = Ctx.getIntWidth(DestType); 116 APSInt Result = Value; 117 // Figure out if this is a truncate, extend or noop cast. 118 // If the input is signed, do a sign extend, noop, or truncate. 119 Result.extOrTrunc(DestWidth); 120 Result.setIsUnsigned(DestType->isUnsignedIntegerType()); 121 return Result; 122} 123 124static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType, 125 APSInt &Value, ASTContext &Ctx) { 126 127 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1); 128 Result.convertFromAPInt(Value, Value.isSigned(), 129 APFloat::rmNearestTiesToEven); 130 return Result; 131} 132 133//===----------------------------------------------------------------------===// 134// LValue Evaluation 135//===----------------------------------------------------------------------===// 136namespace { 137class VISIBILITY_HIDDEN LValueExprEvaluator 138 : public StmtVisitor<LValueExprEvaluator, APValue> { 139 EvalInfo &Info; 140public: 141 142 LValueExprEvaluator(EvalInfo &info) : Info(info) {} 143 144 APValue VisitStmt(Stmt *S) { 145#if 0 146 // FIXME: Remove this when we support more expressions. 147 printf("Unhandled pointer statement\n"); 148 S->dump(); 149#endif 150 return APValue(); 151 } 152 153 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 154 APValue VisitDeclRefExpr(DeclRefExpr *E); 155 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); } 156 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 157 APValue VisitMemberExpr(MemberExpr *E); 158 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); } 159 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E); 160}; 161} // end anonymous namespace 162 163static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) { 164 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E)); 165 return Result.isLValue(); 166} 167 168APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) 169{ 170 if (!E->hasGlobalStorage()) 171 return APValue(); 172 173 return APValue(E, 0); 174} 175 176APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 177 if (E->isFileScope()) 178 return APValue(E, 0); 179 return APValue(); 180} 181 182APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) { 183 APValue result; 184 QualType Ty; 185 if (E->isArrow()) { 186 if (!EvaluatePointer(E->getBase(), result, Info)) 187 return APValue(); 188 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType(); 189 } else { 190 result = Visit(E->getBase()); 191 if (result.isUninit()) 192 return APValue(); 193 Ty = E->getBase()->getType(); 194 } 195 196 RecordDecl *RD = Ty->getAsRecordType()->getDecl(); 197 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 198 199 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 200 if (!FD) // FIXME: deal with other kinds of member expressions 201 return APValue(); 202 203 // FIXME: This is linear time. 204 unsigned i = 0; 205 for (RecordDecl::field_iterator Field = RD->field_begin(), 206 FieldEnd = RD->field_end(); 207 Field != FieldEnd; (void)++Field, ++i) { 208 if (*Field == FD) 209 break; 210 } 211 212 result.setLValue(result.getLValueBase(), 213 result.getLValueOffset() + RL.getFieldOffset(i) / 8); 214 215 return result; 216} 217 218APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) 219{ 220 APValue Result; 221 222 if (!EvaluatePointer(E->getBase(), Result, Info)) 223 return APValue(); 224 225 APSInt Index; 226 if (!EvaluateInteger(E->getIdx(), Index, Info)) 227 return APValue(); 228 229 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8; 230 231 uint64_t Offset = Index.getSExtValue() * ElementSize; 232 Result.setLValue(Result.getLValueBase(), 233 Result.getLValueOffset() + Offset); 234 return Result; 235} 236 237//===----------------------------------------------------------------------===// 238// Pointer Evaluation 239//===----------------------------------------------------------------------===// 240 241namespace { 242class VISIBILITY_HIDDEN PointerExprEvaluator 243 : public StmtVisitor<PointerExprEvaluator, APValue> { 244 EvalInfo &Info; 245public: 246 247 PointerExprEvaluator(EvalInfo &info) : Info(info) {} 248 249 APValue VisitStmt(Stmt *S) { 250 return APValue(); 251 } 252 253 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 254 255 APValue VisitBinaryOperator(const BinaryOperator *E); 256 APValue VisitCastExpr(const CastExpr* E); 257 APValue VisitUnaryOperator(const UnaryOperator *E); 258 APValue VisitObjCStringLiteral(ObjCStringLiteral *E) 259 { return APValue(E, 0); } 260 APValue VisitAddrLabelExpr(AddrLabelExpr *E) 261 { return APValue(E, 0); } 262 APValue VisitCallExpr(CallExpr *E); 263 APValue VisitConditionalOperator(ConditionalOperator *E); 264}; 265} // end anonymous namespace 266 267static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) { 268 if (!E->getType()->isPointerType()) 269 return false; 270 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E)); 271 return Result.isLValue(); 272} 273 274APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 275 if (E->getOpcode() != BinaryOperator::Add && 276 E->getOpcode() != BinaryOperator::Sub) 277 return APValue(); 278 279 const Expr *PExp = E->getLHS(); 280 const Expr *IExp = E->getRHS(); 281 if (IExp->getType()->isPointerType()) 282 std::swap(PExp, IExp); 283 284 APValue ResultLValue; 285 if (!EvaluatePointer(PExp, ResultLValue, Info)) 286 return APValue(); 287 288 llvm::APSInt AdditionalOffset(32); 289 if (!EvaluateInteger(IExp, AdditionalOffset, Info)) 290 return APValue(); 291 292 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType(); 293 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8; 294 295 uint64_t Offset = ResultLValue.getLValueOffset(); 296 297 if (E->getOpcode() == BinaryOperator::Add) 298 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee; 299 else 300 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee; 301 302 return APValue(ResultLValue.getLValueBase(), Offset); 303} 304 305APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 306 if (E->getOpcode() == UnaryOperator::Extension) { 307 // FIXME: Deal with warnings? 308 return Visit(E->getSubExpr()); 309 } 310 311 if (E->getOpcode() == UnaryOperator::AddrOf) { 312 APValue result; 313 if (EvaluateLValue(E->getSubExpr(), result, Info)) 314 return result; 315 } 316 317 return APValue(); 318} 319 320 321APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 322 const Expr* SubExpr = E->getSubExpr(); 323 324 // Check for pointer->pointer cast 325 if (SubExpr->getType()->isPointerType()) { 326 APValue Result; 327 if (EvaluatePointer(SubExpr, Result, Info)) 328 return Result; 329 return APValue(); 330 } 331 332 if (SubExpr->getType()->isIntegralType()) { 333 llvm::APSInt Result(32); 334 if (EvaluateInteger(SubExpr, Result, Info)) { 335 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType())); 336 return APValue(0, Result.getZExtValue()); 337 } 338 } 339 340 if (SubExpr->getType()->isFunctionType() || 341 SubExpr->getType()->isArrayType()) { 342 APValue Result; 343 if (EvaluateLValue(SubExpr, Result, Info)) 344 return Result; 345 return APValue(); 346 } 347 348 //assert(0 && "Unhandled cast"); 349 return APValue(); 350} 351 352APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) { 353 if (E->isBuiltinCall() == Builtin::BI__builtin___CFStringMakeConstantString) 354 return APValue(E, 0); 355 return APValue(); 356} 357 358APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) { 359 bool BoolResult; 360 if (!HandleConversionToBool(E->getCond(), BoolResult, Info)) 361 return APValue(); 362 363 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 364 365 APValue Result; 366 if (EvaluatePointer(EvalExpr, Result, Info)) 367 return Result; 368 return APValue(); 369} 370 371//===----------------------------------------------------------------------===// 372// Vector Evaluation 373//===----------------------------------------------------------------------===// 374 375namespace { 376 class VISIBILITY_HIDDEN VectorExprEvaluator 377 : public StmtVisitor<VectorExprEvaluator, APValue> { 378 EvalInfo &Info; 379 public: 380 381 VectorExprEvaluator(EvalInfo &info) : Info(info) {} 382 383 APValue VisitStmt(Stmt *S) { 384 return APValue(); 385 } 386 387 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 388 APValue VisitCastExpr(const CastExpr* E); 389 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 390 APValue VisitInitListExpr(const InitListExpr *E); 391 }; 392} // end anonymous namespace 393 394static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 395 if (!E->getType()->isVectorType()) 396 return false; 397 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E)); 398 return !Result.isUninit(); 399} 400 401APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { 402 const Expr* SE = E->getSubExpr(); 403 404 // Check for vector->vector bitcast. 405 if (SE->getType()->isVectorType()) 406 return this->Visit(const_cast<Expr*>(SE)); 407 408 return APValue(); 409} 410 411APValue 412VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 413 return this->Visit(const_cast<Expr*>(E->getInitializer())); 414} 415 416APValue 417VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 418 const VectorType *VT = E->getType()->getAsVectorType(); 419 unsigned NumInits = E->getNumInits(); 420 421 if (!VT || VT->getNumElements() != NumInits) 422 return APValue(); 423 424 QualType EltTy = VT->getElementType(); 425 llvm::SmallVector<APValue, 4> Elements; 426 427 for (unsigned i = 0; i < NumInits; i++) { 428 if (EltTy->isIntegerType()) { 429 llvm::APSInt sInt(32); 430 if (!EvaluateInteger(E->getInit(i), sInt, Info)) 431 return APValue(); 432 Elements.push_back(APValue(sInt)); 433 } else { 434 llvm::APFloat f(0.0); 435 if (!EvaluateFloat(E->getInit(i), f, Info)) 436 return APValue(); 437 Elements.push_back(APValue(f)); 438 } 439 } 440 return APValue(&Elements[0], Elements.size()); 441} 442 443//===----------------------------------------------------------------------===// 444// Integer Evaluation 445//===----------------------------------------------------------------------===// 446 447namespace { 448class VISIBILITY_HIDDEN IntExprEvaluator 449 : public StmtVisitor<IntExprEvaluator, bool> { 450 EvalInfo &Info; 451 APSInt &Result; 452public: 453 IntExprEvaluator(EvalInfo &info, APSInt &result) 454 : Info(info), Result(result) {} 455 456 unsigned getIntTypeSizeInBits(QualType T) const { 457 return (unsigned)Info.Ctx.getIntWidth(T); 458 } 459 460 bool Extension(SourceLocation L, diag::kind D, const Expr *E) { 461 Info.EvalResult.DiagLoc = L; 462 Info.EvalResult.Diag = D; 463 Info.EvalResult.DiagExpr = E; 464 return true; // still a constant. 465 } 466 467 bool Error(SourceLocation L, diag::kind D, const Expr *E) { 468 // If this is in an unevaluated portion of the subexpression, ignore the 469 // error. 470 if (Info.ShortCircuit) { 471 // If error is ignored because the value isn't evaluated, get the real 472 // type at least to prevent errors downstream. 473 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 474 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 475 return true; 476 } 477 478 // Take the first error. 479 if (Info.EvalResult.Diag == 0) { 480 Info.EvalResult.DiagLoc = L; 481 Info.EvalResult.Diag = D; 482 Info.EvalResult.DiagExpr = E; 483 } 484 return false; 485 } 486 487 //===--------------------------------------------------------------------===// 488 // Visitor Methods 489 //===--------------------------------------------------------------------===// 490 491 bool VisitStmt(Stmt *) { 492 assert(0 && "This should be called on integers, stmts are not integers"); 493 return false; 494 } 495 496 bool VisitExpr(Expr *E) { 497 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 498 } 499 500 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 501 502 bool VisitIntegerLiteral(const IntegerLiteral *E) { 503 Result = E->getValue(); 504 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 505 return true; 506 } 507 bool VisitCharacterLiteral(const CharacterLiteral *E) { 508 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 509 Result = E->getValue(); 510 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 511 return true; 512 } 513 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 514 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 515 // Per gcc docs "this built-in function ignores top level 516 // qualifiers". We need to use the canonical version to properly 517 // be able to strip CRV qualifiers from the type. 518 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1()); 519 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2()); 520 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(), 521 T1.getUnqualifiedType()); 522 return true; 523 } 524 bool VisitDeclRefExpr(const DeclRefExpr *E); 525 bool VisitCallExpr(const CallExpr *E); 526 bool VisitBinaryOperator(const BinaryOperator *E); 527 bool VisitUnaryOperator(const UnaryOperator *E); 528 bool VisitConditionalOperator(const ConditionalOperator *E); 529 530 bool VisitCastExpr(CastExpr* E); 531 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 532 533 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 534 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 535 Result = E->getValue(); 536 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 537 return true; 538 } 539 540 bool VisitGNUNullExpr(const GNUNullExpr *E) { 541 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType())); 542 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 543 return true; 544 } 545 546 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 547 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType())); 548 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 549 return true; 550 } 551 552 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 553 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 554 Result = E->Evaluate(); 555 return true; 556 } 557 558private: 559 unsigned GetAlignOfExpr(const Expr *E); 560 unsigned GetAlignOfType(QualType T); 561}; 562} // end anonymous namespace 563 564static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) { 565 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E)); 566} 567 568bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 569 // Enums are integer constant exprs. 570 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) { 571 Result = D->getInitVal(); 572 // FIXME: This is an ugly hack around the fact that enums don't set their 573 // signedness consistently; see PR3173 574 Result.setIsUnsigned(!E->getType()->isSignedIntegerType()); 575 return true; 576 } 577 578 // Otherwise, random variable references are not constants. 579 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 580} 581 582/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 583/// as GCC. 584static int EvaluateBuiltinClassifyType(const CallExpr *E) { 585 // The following enum mimics the values returned by GCC. 586 enum gcc_type_class { 587 no_type_class = -1, 588 void_type_class, integer_type_class, char_type_class, 589 enumeral_type_class, boolean_type_class, 590 pointer_type_class, reference_type_class, offset_type_class, 591 real_type_class, complex_type_class, 592 function_type_class, method_type_class, 593 record_type_class, union_type_class, 594 array_type_class, string_type_class, 595 lang_type_class 596 }; 597 598 // If no argument was supplied, default to "no_type_class". This isn't 599 // ideal, however it is what gcc does. 600 if (E->getNumArgs() == 0) 601 return no_type_class; 602 603 QualType ArgTy = E->getArg(0)->getType(); 604 if (ArgTy->isVoidType()) 605 return void_type_class; 606 else if (ArgTy->isEnumeralType()) 607 return enumeral_type_class; 608 else if (ArgTy->isBooleanType()) 609 return boolean_type_class; 610 else if (ArgTy->isCharType()) 611 return string_type_class; // gcc doesn't appear to use char_type_class 612 else if (ArgTy->isIntegerType()) 613 return integer_type_class; 614 else if (ArgTy->isPointerType()) 615 return pointer_type_class; 616 else if (ArgTy->isReferenceType()) 617 return reference_type_class; 618 else if (ArgTy->isRealType()) 619 return real_type_class; 620 else if (ArgTy->isComplexType()) 621 return complex_type_class; 622 else if (ArgTy->isFunctionType()) 623 return function_type_class; 624 else if (ArgTy->isStructureType()) 625 return record_type_class; 626 else if (ArgTy->isUnionType()) 627 return union_type_class; 628 else if (ArgTy->isArrayType()) 629 return array_type_class; 630 else if (ArgTy->isUnionType()) 631 return union_type_class; 632 else // FIXME: offset_type_class, method_type_class, & lang_type_class? 633 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type"); 634 return -1; 635} 636 637bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 638 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 639 640 switch (E->isBuiltinCall()) { 641 default: 642 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 643 case Builtin::BI__builtin_classify_type: 644 Result.setIsSigned(true); 645 Result = EvaluateBuiltinClassifyType(E); 646 return true; 647 648 case Builtin::BI__builtin_constant_p: 649 // __builtin_constant_p always has one operand: it returns true if that 650 // operand can be folded, false otherwise. 651 Result = E->getArg(0)->isEvaluatable(Info.Ctx); 652 return true; 653 } 654} 655 656bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 657 if (E->getOpcode() == BinaryOperator::Comma) { 658 if (!Visit(E->getRHS())) 659 return false; 660 661 if (!Info.ShortCircuit) { 662 // If we can't evaluate the LHS, it must be because it has 663 // side effects. 664 if (!E->getLHS()->isEvaluatable(Info.Ctx)) 665 Info.EvalResult.HasSideEffects = true; 666 667 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E); 668 } 669 670 return true; 671 } 672 673 if (E->isLogicalOp()) { 674 // These need to be handled specially because the operands aren't 675 // necessarily integral 676 bool lhsResult, rhsResult; 677 678 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) { 679 // We were able to evaluate the LHS, see if we can get away with not 680 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 681 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) || 682 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) { 683 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 684 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 685 Result = lhsResult; 686 687 Info.ShortCircuit++; 688 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info); 689 Info.ShortCircuit--; 690 691 if (rhsEvaluated) 692 return true; 693 694 // FIXME: Return an extension warning saying that the RHS could not be 695 // evaluated. 696 return true; 697 } 698 699 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) { 700 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 701 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 702 if (E->getOpcode() == BinaryOperator::LOr) 703 Result = lhsResult || rhsResult; 704 else 705 Result = lhsResult && rhsResult; 706 return true; 707 } 708 } else { 709 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) { 710 // We can't evaluate the LHS; however, sometimes the result 711 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 712 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) || 713 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) { 714 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 715 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 716 Result = rhsResult; 717 718 // Since we werent able to evaluate the left hand side, it 719 // must have had side effects. 720 Info.EvalResult.HasSideEffects = true; 721 722 return true; 723 } 724 } 725 } 726 727 return false; 728 } 729 730 QualType LHSTy = E->getLHS()->getType(); 731 QualType RHSTy = E->getRHS()->getType(); 732 733 if (LHSTy->isAnyComplexType()) { 734 assert(RHSTy->isAnyComplexType() && "Invalid comparison"); 735 APValue LHS, RHS; 736 737 if (!EvaluateComplex(E->getLHS(), LHS, Info)) 738 return false; 739 740 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 741 return false; 742 743 if (LHS.isComplexFloat()) { 744 APFloat::cmpResult CR_r = 745 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 746 APFloat::cmpResult CR_i = 747 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 748 749 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 750 if (E->getOpcode() == BinaryOperator::EQ) 751 Result = (CR_r == APFloat::cmpEqual && 752 CR_i == APFloat::cmpEqual); 753 else if (E->getOpcode() == BinaryOperator::NE) 754 Result = ((CR_r == APFloat::cmpGreaterThan || 755 CR_r == APFloat::cmpLessThan) && 756 (CR_i == APFloat::cmpGreaterThan || 757 CR_i == APFloat::cmpLessThan)); 758 else 759 assert(0 && "Invalid complex compartison."); 760 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 761 return true; 762 } else { 763 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 764 if (E->getOpcode() == BinaryOperator::EQ) 765 Result = (LHS.getComplexIntReal() == RHS.getComplexIntReal() && 766 LHS.getComplexIntImag() == RHS.getComplexIntImag()); 767 else if (E->getOpcode() == BinaryOperator::NE) 768 Result = (LHS.getComplexIntReal() != RHS.getComplexIntReal() || 769 LHS.getComplexIntImag() != RHS.getComplexIntImag()); 770 else 771 assert(0 && "Invalid complex compartison."); 772 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 773 return true; 774 } 775 } 776 777 if (LHSTy->isRealFloatingType() && 778 RHSTy->isRealFloatingType()) { 779 APFloat RHS(0.0), LHS(0.0); 780 781 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 782 return false; 783 784 if (!EvaluateFloat(E->getLHS(), LHS, Info)) 785 return false; 786 787 APFloat::cmpResult CR = LHS.compare(RHS); 788 789 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 790 791 switch (E->getOpcode()) { 792 default: 793 assert(0 && "Invalid binary operator!"); 794 case BinaryOperator::LT: 795 Result = CR == APFloat::cmpLessThan; 796 break; 797 case BinaryOperator::GT: 798 Result = CR == APFloat::cmpGreaterThan; 799 break; 800 case BinaryOperator::LE: 801 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual; 802 break; 803 case BinaryOperator::GE: 804 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual; 805 break; 806 case BinaryOperator::EQ: 807 Result = CR == APFloat::cmpEqual; 808 break; 809 case BinaryOperator::NE: 810 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan; 811 break; 812 } 813 814 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 815 return true; 816 } 817 818 if (E->getOpcode() == BinaryOperator::Sub) { 819 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 820 APValue LHSValue; 821 if (!EvaluatePointer(E->getLHS(), LHSValue, Info)) 822 return false; 823 824 APValue RHSValue; 825 if (!EvaluatePointer(E->getRHS(), RHSValue, Info)) 826 return false; 827 828 // FIXME: Is this correct? What if only one of the operands has a base? 829 if (LHSValue.getLValueBase() || RHSValue.getLValueBase()) 830 return false; 831 832 const QualType Type = E->getLHS()->getType(); 833 const QualType ElementType = Type->getAsPointerType()->getPointeeType(); 834 835 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset(); 836 D /= Info.Ctx.getTypeSize(ElementType) / 8; 837 838 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 839 Result = D; 840 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 841 842 return true; 843 } 844 } 845 if (!LHSTy->isIntegralType() || 846 !RHSTy->isIntegralType()) { 847 // We can't continue from here for non-integral types, and they 848 // could potentially confuse the following operations. 849 // FIXME: Deal with EQ and friends. 850 return false; 851 } 852 853 // The LHS of a constant expr is always evaluated and needed. 854 llvm::APSInt RHS(32); 855 if (!Visit(E->getLHS())) { 856 return false; // error in subexpression. 857 } 858 859 860 // FIXME Maybe we want to succeed even where we can't evaluate the 861 // right side of LAnd/LOr? 862 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525 863 if (!EvaluateInteger(E->getRHS(), RHS, Info)) 864 return false; 865 866 switch (E->getOpcode()) { 867 default: 868 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 869 case BinaryOperator::Mul: Result *= RHS; return true; 870 case BinaryOperator::Add: Result += RHS; return true; 871 case BinaryOperator::Sub: Result -= RHS; return true; 872 case BinaryOperator::And: Result &= RHS; return true; 873 case BinaryOperator::Xor: Result ^= RHS; return true; 874 case BinaryOperator::Or: Result |= RHS; return true; 875 case BinaryOperator::Div: 876 if (RHS == 0) 877 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 878 Result /= RHS; 879 break; 880 case BinaryOperator::Rem: 881 if (RHS == 0) 882 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 883 Result %= RHS; 884 break; 885 case BinaryOperator::Shl: 886 // FIXME: Warn about out of range shift amounts! 887 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1); 888 break; 889 case BinaryOperator::Shr: 890 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1); 891 break; 892 893 case BinaryOperator::LT: 894 Result = Result < RHS; 895 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 896 break; 897 case BinaryOperator::GT: 898 Result = Result > RHS; 899 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 900 break; 901 case BinaryOperator::LE: 902 Result = Result <= RHS; 903 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 904 break; 905 case BinaryOperator::GE: 906 Result = Result >= RHS; 907 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 908 break; 909 case BinaryOperator::EQ: 910 Result = Result == RHS; 911 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 912 break; 913 case BinaryOperator::NE: 914 Result = Result != RHS; 915 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 916 break; 917 case BinaryOperator::LAnd: 918 Result = Result != 0 && RHS != 0; 919 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 920 break; 921 case BinaryOperator::LOr: 922 Result = Result != 0 || RHS != 0; 923 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 924 break; 925 } 926 927 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 928 return true; 929} 930 931bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) { 932 bool Cond; 933 if (!HandleConversionToBool(E->getCond(), Cond, Info)) 934 return false; 935 936 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr()); 937} 938 939unsigned IntExprEvaluator::GetAlignOfType(QualType T) { 940 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr(); 941 942 // __alignof__(void) = 1 as a gcc extension. 943 if (Ty->isVoidType()) 944 return 1; 945 946 // GCC extension: alignof(function) = 4. 947 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the 948 // attribute(align) directive. 949 if (Ty->isFunctionType()) 950 return 4; 951 952 if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty)) 953 return GetAlignOfType(QualType(ASQT->getBaseType(), 0)); 954 955 // alignof VLA/incomplete array. 956 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty)) 957 return GetAlignOfType(VAT->getElementType()); 958 959 // sizeof (objc class)? 960 if (isa<ObjCInterfaceType>(Ty)) 961 return 1; // FIXME: This probably isn't right. 962 963 // Get information about the alignment. 964 unsigned CharSize = Info.Ctx.Target.getCharWidth(); 965 return Info.Ctx.getTypeAlign(Ty) / CharSize; 966} 967 968unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) { 969 E = E->IgnoreParens(); 970 971 // alignof decl is always accepted, even if it doesn't make sense: we default 972 // to 1 in those cases. 973 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 974 return Info.Ctx.getDeclAlign(DRE->getDecl()); 975 976 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 977 return Info.Ctx.getDeclAlign(ME->getMemberDecl()); 978 979 return GetAlignOfType(E->getType()); 980} 981 982 983/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the 984/// expression's type. 985bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 986 QualType DstTy = E->getType(); 987 // Return the result in the right width. 988 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy)); 989 Result.setIsUnsigned(DstTy->isUnsignedIntegerType()); 990 991 // Handle alignof separately. 992 if (!E->isSizeOf()) { 993 if (E->isArgumentType()) 994 Result = GetAlignOfType(E->getArgumentType()); 995 else 996 Result = GetAlignOfExpr(E->getArgumentExpr()); 997 return true; 998 } 999 1000 QualType SrcTy = E->getTypeOfArgument(); 1001 1002 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. 1003 if (SrcTy->isVoidType()) { 1004 Result = 1; 1005 return true; 1006 } 1007 1008 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 1009 if (!SrcTy->isConstantSizeType()) 1010 return false; 1011 1012 // GCC extension: sizeof(function) = 1. 1013 if (SrcTy->isFunctionType()) { 1014 Result = 1; 1015 return true; 1016 } 1017 1018 if (SrcTy->isObjCInterfaceType()) { 1019 // Slightly unusual case: the size of an ObjC interface type is the 1020 // size of the class. This code intentionally falls through to the normal 1021 // case. 1022 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl(); 1023 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI)); 1024 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD)); 1025 } 1026 1027 // Get information about the size. 1028 unsigned CharSize = Info.Ctx.Target.getCharWidth(); 1029 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize; 1030 return true; 1031} 1032 1033bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 1034 // Special case unary operators that do not need their subexpression 1035 // evaluated. offsetof/sizeof/alignof are all special. 1036 if (E->isOffsetOfOp()) { 1037 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 1038 Result = E->evaluateOffsetOf(Info.Ctx); 1039 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 1040 return true; 1041 } 1042 1043 if (E->getOpcode() == UnaryOperator::LNot) { 1044 // LNot's operand isn't necessarily an integer, so we handle it specially. 1045 bool bres; 1046 if (!HandleConversionToBool(E->getSubExpr(), bres, Info)) 1047 return false; 1048 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType())); 1049 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 1050 Result = !bres; 1051 return true; 1052 } 1053 1054 // Get the operand value into 'Result'. 1055 if (!Visit(E->getSubExpr())) 1056 return false; 1057 1058 switch (E->getOpcode()) { 1059 default: 1060 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1061 // See C99 6.6p3. 1062 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 1063 case UnaryOperator::Extension: 1064 // FIXME: Should extension allow i-c-e extension expressions in its scope? 1065 // If so, we could clear the diagnostic ID. 1066 case UnaryOperator::Plus: 1067 // The result is always just the subexpr. 1068 break; 1069 case UnaryOperator::Minus: 1070 Result = -Result; 1071 break; 1072 case UnaryOperator::Not: 1073 Result = ~Result; 1074 break; 1075 } 1076 1077 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType()); 1078 return true; 1079} 1080 1081/// HandleCast - This is used to evaluate implicit or explicit casts where the 1082/// result type is integer. 1083bool IntExprEvaluator::VisitCastExpr(CastExpr *E) { 1084 Expr *SubExpr = E->getSubExpr(); 1085 QualType DestType = E->getType(); 1086 1087 unsigned DestWidth = getIntTypeSizeInBits(DestType); 1088 1089 if (DestType->isBooleanType()) { 1090 bool BoolResult; 1091 if (!HandleConversionToBool(SubExpr, BoolResult, Info)) 1092 return false; 1093 Result.zextOrTrunc(DestWidth); 1094 Result.setIsUnsigned(DestType->isUnsignedIntegerType()); 1095 Result = BoolResult; 1096 return true; 1097 } 1098 1099 // Handle simple integer->integer casts. 1100 if (SubExpr->getType()->isIntegralType()) { 1101 if (!Visit(SubExpr)) 1102 return false; 1103 1104 Result = HandleIntToIntCast(DestType, SubExpr->getType(), Result, Info.Ctx); 1105 return true; 1106 } 1107 1108 // FIXME: Clean this up! 1109 if (SubExpr->getType()->isPointerType()) { 1110 APValue LV; 1111 if (!EvaluatePointer(SubExpr, LV, Info)) 1112 return false; 1113 1114 if (LV.getLValueBase()) 1115 return false; 1116 1117 Result.extOrTrunc(DestWidth); 1118 Result = LV.getLValueOffset(); 1119 Result.setIsUnsigned(DestType->isUnsignedIntegerType()); 1120 return true; 1121 } 1122 1123 if (!SubExpr->getType()->isRealFloatingType()) 1124 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 1125 1126 APFloat F(0.0); 1127 if (!EvaluateFloat(SubExpr, F, Info)) 1128 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 1129 1130 Result = HandleFloatToIntCast(DestType, SubExpr->getType(), F, Info.Ctx); 1131 return true; 1132} 1133 1134//===----------------------------------------------------------------------===// 1135// Float Evaluation 1136//===----------------------------------------------------------------------===// 1137 1138namespace { 1139class VISIBILITY_HIDDEN FloatExprEvaluator 1140 : public StmtVisitor<FloatExprEvaluator, bool> { 1141 EvalInfo &Info; 1142 APFloat &Result; 1143public: 1144 FloatExprEvaluator(EvalInfo &info, APFloat &result) 1145 : Info(info), Result(result) {} 1146 1147 bool VisitStmt(Stmt *S) { 1148 return false; 1149 } 1150 1151 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 1152 bool VisitCallExpr(const CallExpr *E); 1153 1154 bool VisitUnaryOperator(const UnaryOperator *E); 1155 bool VisitBinaryOperator(const BinaryOperator *E); 1156 bool VisitFloatingLiteral(const FloatingLiteral *E); 1157 bool VisitCastExpr(CastExpr *E); 1158 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E); 1159}; 1160} // end anonymous namespace 1161 1162static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 1163 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E)); 1164} 1165 1166bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 1167 switch (E->isBuiltinCall()) { 1168 default: return false; 1169 case Builtin::BI__builtin_huge_val: 1170 case Builtin::BI__builtin_huge_valf: 1171 case Builtin::BI__builtin_huge_vall: 1172 case Builtin::BI__builtin_inf: 1173 case Builtin::BI__builtin_inff: 1174 case Builtin::BI__builtin_infl: { 1175 const llvm::fltSemantics &Sem = 1176 Info.Ctx.getFloatTypeSemantics(E->getType()); 1177 Result = llvm::APFloat::getInf(Sem); 1178 return true; 1179 } 1180 1181 case Builtin::BI__builtin_nan: 1182 case Builtin::BI__builtin_nanf: 1183 case Builtin::BI__builtin_nanl: 1184 // If this is __builtin_nan("") turn this into a simple nan, otherwise we 1185 // can't constant fold it. 1186 if (const StringLiteral *S = 1187 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) { 1188 if (!S->isWide() && S->getByteLength() == 0) { // empty string. 1189 const llvm::fltSemantics &Sem = 1190 Info.Ctx.getFloatTypeSemantics(E->getType()); 1191 Result = llvm::APFloat::getNaN(Sem); 1192 return true; 1193 } 1194 } 1195 return false; 1196 1197 case Builtin::BI__builtin_fabs: 1198 case Builtin::BI__builtin_fabsf: 1199 case Builtin::BI__builtin_fabsl: 1200 if (!EvaluateFloat(E->getArg(0), Result, Info)) 1201 return false; 1202 1203 if (Result.isNegative()) 1204 Result.changeSign(); 1205 return true; 1206 1207 case Builtin::BI__builtin_copysign: 1208 case Builtin::BI__builtin_copysignf: 1209 case Builtin::BI__builtin_copysignl: { 1210 APFloat RHS(0.); 1211 if (!EvaluateFloat(E->getArg(0), Result, Info) || 1212 !EvaluateFloat(E->getArg(1), RHS, Info)) 1213 return false; 1214 Result.copySign(RHS); 1215 return true; 1216 } 1217 } 1218} 1219 1220bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 1221 if (E->getOpcode() == UnaryOperator::Deref) 1222 return false; 1223 1224 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 1225 return false; 1226 1227 switch (E->getOpcode()) { 1228 default: return false; 1229 case UnaryOperator::Plus: 1230 return true; 1231 case UnaryOperator::Minus: 1232 Result.changeSign(); 1233 return true; 1234 } 1235} 1236 1237bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 1238 // FIXME: Diagnostics? I really don't understand how the warnings 1239 // and errors are supposed to work. 1240 APFloat RHS(0.0); 1241 if (!EvaluateFloat(E->getLHS(), Result, Info)) 1242 return false; 1243 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 1244 return false; 1245 1246 switch (E->getOpcode()) { 1247 default: return false; 1248 case BinaryOperator::Mul: 1249 Result.multiply(RHS, APFloat::rmNearestTiesToEven); 1250 return true; 1251 case BinaryOperator::Add: 1252 Result.add(RHS, APFloat::rmNearestTiesToEven); 1253 return true; 1254 case BinaryOperator::Sub: 1255 Result.subtract(RHS, APFloat::rmNearestTiesToEven); 1256 return true; 1257 case BinaryOperator::Div: 1258 Result.divide(RHS, APFloat::rmNearestTiesToEven); 1259 return true; 1260 case BinaryOperator::Rem: 1261 Result.mod(RHS, APFloat::rmNearestTiesToEven); 1262 return true; 1263 } 1264} 1265 1266bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 1267 Result = E->getValue(); 1268 return true; 1269} 1270 1271bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) { 1272 Expr* SubExpr = E->getSubExpr(); 1273 1274 if (SubExpr->getType()->isIntegralType()) { 1275 APSInt IntResult; 1276 if (!EvaluateInteger(E, IntResult, Info)) 1277 return false; 1278 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(), 1279 IntResult, Info.Ctx); 1280 return true; 1281 } 1282 if (SubExpr->getType()->isRealFloatingType()) { 1283 if (!Visit(SubExpr)) 1284 return false; 1285 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(), 1286 Result, Info.Ctx); 1287 return true; 1288 } 1289 1290 return false; 1291} 1292 1293bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) { 1294 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 1295 return true; 1296} 1297 1298//===----------------------------------------------------------------------===// 1299// Complex Evaluation (for float and integer) 1300//===----------------------------------------------------------------------===// 1301 1302namespace { 1303class VISIBILITY_HIDDEN ComplexExprEvaluator 1304 : public StmtVisitor<ComplexExprEvaluator, APValue> { 1305 EvalInfo &Info; 1306 1307public: 1308 ComplexExprEvaluator(EvalInfo &info) : Info(info) {} 1309 1310 //===--------------------------------------------------------------------===// 1311 // Visitor Methods 1312 //===--------------------------------------------------------------------===// 1313 1314 APValue VisitStmt(Stmt *S) { 1315 return APValue(); 1316 } 1317 1318 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 1319 1320 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) { 1321 Expr* SubExpr = E->getSubExpr(); 1322 1323 if (SubExpr->getType()->isRealFloatingType()) { 1324 APFloat Result(0.0); 1325 1326 if (!EvaluateFloat(SubExpr, Result, Info)) 1327 return APValue(); 1328 1329 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false), 1330 Result); 1331 } else { 1332 assert(SubExpr->getType()->isIntegerType() && 1333 "Unexpected imaginary literal."); 1334 1335 llvm::APSInt Result; 1336 if (!EvaluateInteger(SubExpr, Result, Info)) 1337 return APValue(); 1338 1339 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned()); 1340 Zero = 0; 1341 return APValue(Zero, Result); 1342 } 1343 } 1344 1345 APValue VisitCastExpr(CastExpr *E) { 1346 Expr* SubExpr = E->getSubExpr(); 1347 QualType EltType = E->getType()->getAsComplexType()->getElementType(); 1348 QualType SubType = SubExpr->getType(); 1349 1350 if (SubType->isRealFloatingType()) { 1351 APFloat Result(0.0); 1352 1353 if (!EvaluateFloat(SubExpr, Result, Info)) 1354 return APValue(); 1355 1356 // Apply float conversion if necessary. 1357 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx); 1358 return APValue(Result, 1359 APFloat(Result.getSemantics(), APFloat::fcZero, false)); 1360 } else if (SubType->isIntegerType()) { 1361 APSInt Result; 1362 1363 if (!EvaluateInteger(SubExpr, Result, Info)) 1364 return APValue(); 1365 1366 // Apply integer conversion if necessary. 1367 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx); 1368 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned()); 1369 Zero = 0; 1370 return APValue(Result, Zero); 1371 } else if (const ComplexType *CT = SubType->getAsComplexType()) { 1372 APValue Src; 1373 1374 if (!EvaluateComplex(SubExpr, Src, Info)) 1375 return APValue(); 1376 1377 QualType SrcType = CT->getElementType(); 1378 1379 if (Src.isComplexFloat()) { 1380 if (EltType->isRealFloatingType()) { 1381 return APValue(HandleFloatToFloatCast(EltType, SrcType, 1382 Src.getComplexFloatReal(), 1383 Info.Ctx), 1384 HandleFloatToFloatCast(EltType, SrcType, 1385 Src.getComplexFloatImag(), 1386 Info.Ctx)); 1387 } else { 1388 return APValue(HandleFloatToIntCast(EltType, SrcType, 1389 Src.getComplexFloatReal(), 1390 Info.Ctx), 1391 HandleFloatToIntCast(EltType, SrcType, 1392 Src.getComplexFloatImag(), 1393 Info.Ctx)); 1394 } 1395 } else { 1396 assert(Src.isComplexInt() && "Invalid evaluate result."); 1397 if (EltType->isRealFloatingType()) { 1398 return APValue(HandleIntToFloatCast(EltType, SrcType, 1399 Src.getComplexIntReal(), 1400 Info.Ctx), 1401 HandleIntToFloatCast(EltType, SrcType, 1402 Src.getComplexIntImag(), 1403 Info.Ctx)); 1404 } else { 1405 return APValue(HandleIntToIntCast(EltType, SrcType, 1406 Src.getComplexIntReal(), 1407 Info.Ctx), 1408 HandleIntToIntCast(EltType, SrcType, 1409 Src.getComplexIntImag(), 1410 Info.Ctx)); 1411 } 1412 } 1413 } 1414 1415 // FIXME: Handle more casts. 1416 return APValue(); 1417 } 1418 1419 APValue VisitBinaryOperator(const BinaryOperator *E); 1420 1421}; 1422} // end anonymous namespace 1423 1424static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) 1425{ 1426 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E)); 1427 assert((!Result.isComplexFloat() || 1428 (&Result.getComplexFloatReal().getSemantics() == 1429 &Result.getComplexFloatImag().getSemantics())) && 1430 "Invalid complex evaluation."); 1431 return Result.isComplexFloat() || Result.isComplexInt(); 1432} 1433 1434APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) 1435{ 1436 APValue Result, RHS; 1437 1438 if (!EvaluateComplex(E->getLHS(), Result, Info)) 1439 return APValue(); 1440 1441 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 1442 return APValue(); 1443 1444 assert(Result.isComplexFloat() == RHS.isComplexFloat() && 1445 "Invalid operands to binary operator."); 1446 switch (E->getOpcode()) { 1447 default: return APValue(); 1448 case BinaryOperator::Add: 1449 if (Result.isComplexFloat()) { 1450 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 1451 APFloat::rmNearestTiesToEven); 1452 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 1453 APFloat::rmNearestTiesToEven); 1454 } else { 1455 Result.getComplexIntReal() += RHS.getComplexIntReal(); 1456 Result.getComplexIntImag() += RHS.getComplexIntImag(); 1457 } 1458 break; 1459 case BinaryOperator::Sub: 1460 if (Result.isComplexFloat()) { 1461 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 1462 APFloat::rmNearestTiesToEven); 1463 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 1464 APFloat::rmNearestTiesToEven); 1465 } else { 1466 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 1467 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 1468 } 1469 break; 1470 case BinaryOperator::Mul: 1471 if (Result.isComplexFloat()) { 1472 APValue LHS = Result; 1473 APFloat &LHS_r = LHS.getComplexFloatReal(); 1474 APFloat &LHS_i = LHS.getComplexFloatImag(); 1475 APFloat &RHS_r = RHS.getComplexFloatReal(); 1476 APFloat &RHS_i = RHS.getComplexFloatImag(); 1477 1478 APFloat Tmp = LHS_r; 1479 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 1480 Result.getComplexFloatReal() = Tmp; 1481 Tmp = LHS_i; 1482 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 1483 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven); 1484 1485 Tmp = LHS_r; 1486 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 1487 Result.getComplexFloatImag() = Tmp; 1488 Tmp = LHS_i; 1489 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 1490 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven); 1491 } else { 1492 APValue LHS = Result; 1493 Result.getComplexIntReal() = 1494 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 1495 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 1496 Result.getComplexIntImag() = 1497 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 1498 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 1499 } 1500 break; 1501 } 1502 1503 return Result; 1504} 1505 1506//===----------------------------------------------------------------------===// 1507// Top level Expr::Evaluate method. 1508//===----------------------------------------------------------------------===// 1509 1510/// Evaluate - Return true if this is a constant which we can fold using 1511/// any crazy technique (that has nothing to do with language standards) that 1512/// we want to. If this function returns true, it returns the folded constant 1513/// in Result. 1514bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const { 1515 EvalInfo Info(Ctx, Result); 1516 1517 if (getType()->isVectorType()) { 1518 if (!EvaluateVector(this, Result.Val, Info)) 1519 return false; 1520 } else if (getType()->isIntegerType()) { 1521 llvm::APSInt sInt(32); 1522 if (!EvaluateInteger(this, sInt, Info)) 1523 return false; 1524 1525 Result.Val = APValue(sInt); 1526 } else if (getType()->isPointerType()) { 1527 if (!EvaluatePointer(this, Result.Val, Info)) 1528 return false; 1529 } else if (getType()->isRealFloatingType()) { 1530 llvm::APFloat f(0.0); 1531 if (!EvaluateFloat(this, f, Info)) 1532 return false; 1533 1534 Result.Val = APValue(f); 1535 } else if (getType()->isAnyComplexType()) { 1536 if (!EvaluateComplex(this, Result.Val, Info)) 1537 return false; 1538 } else 1539 return false; 1540 1541 return true; 1542} 1543 1544/// isEvaluatable - Call Evaluate to see if this expression can be constant 1545/// folded, but discard the result. 1546bool Expr::isEvaluatable(ASTContext &Ctx) const { 1547 EvalResult Result; 1548 return Evaluate(Result, Ctx) && !Result.HasSideEffects; 1549} 1550 1551APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const { 1552 EvalResult EvalResult; 1553 bool Result = Evaluate(EvalResult, Ctx); 1554 Result = Result; 1555 assert(Result && "Could not evaluate expression"); 1556 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 1557 1558 return EvalResult.Val.getInt(); 1559} 1560