ExprEngineC.cpp revision 0156439a3d718ea0ef5922c38d189a60829c8a86
1//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===// 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 defines ExprEngine's support for C expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/StaticAnalyzer/Core/CheckerManager.h" 15#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16 17using namespace clang; 18using namespace ento; 19using llvm::APSInt; 20 21void ExprEngine::VisitBinaryOperator(const BinaryOperator* B, 22 ExplodedNode *Pred, 23 ExplodedNodeSet &Dst) { 24 25 Expr *LHS = B->getLHS()->IgnoreParens(); 26 Expr *RHS = B->getRHS()->IgnoreParens(); 27 28 // FIXME: Prechecks eventually go in ::Visit(). 29 ExplodedNodeSet CheckedSet; 30 ExplodedNodeSet Tmp2; 31 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this); 32 33 // With both the LHS and RHS evaluated, process the operation itself. 34 for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end(); 35 it != ei; ++it) { 36 37 ProgramStateRef state = (*it)->getState(); 38 const LocationContext *LCtx = (*it)->getLocationContext(); 39 SVal LeftV = state->getSVal(LHS, LCtx); 40 SVal RightV = state->getSVal(RHS, LCtx); 41 42 BinaryOperator::Opcode Op = B->getOpcode(); 43 44 if (Op == BO_Assign) { 45 // EXPERIMENTAL: "Conjured" symbols. 46 // FIXME: Handle structs. 47 if (RightV.isUnknown()) { 48 unsigned Count = currBldrCtx->blockCount(); 49 RightV = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, Count); 50 } 51 // Simulate the effects of a "store": bind the value of the RHS 52 // to the L-Value represented by the LHS. 53 SVal ExprVal = B->isGLValue() ? LeftV : RightV; 54 evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal), 55 LeftV, RightV); 56 continue; 57 } 58 59 if (!B->isAssignmentOp()) { 60 StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx); 61 62 if (B->isAdditiveOp()) { 63 // If one of the operands is a location, conjure a symbol for the other 64 // one (offset) if it's unknown so that memory arithmetic always 65 // results in an ElementRegion. 66 // TODO: This can be removed after we enable history tracking with 67 // SymSymExpr. 68 unsigned Count = currBldrCtx->blockCount(); 69 if (isa<Loc>(LeftV) && 70 RHS->getType()->isIntegerType() && RightV.isUnknown()) { 71 RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(), 72 Count); 73 } 74 if (isa<Loc>(RightV) && 75 LHS->getType()->isIntegerType() && LeftV.isUnknown()) { 76 LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(), 77 Count); 78 } 79 } 80 81 // Process non-assignments except commas or short-circuited 82 // logical expressions (LAnd and LOr). 83 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType()); 84 if (Result.isUnknown()) { 85 Bldr.generateNode(B, *it, state); 86 continue; 87 } 88 89 state = state->BindExpr(B, LCtx, Result); 90 Bldr.generateNode(B, *it, state); 91 continue; 92 } 93 94 assert (B->isCompoundAssignmentOp()); 95 96 switch (Op) { 97 default: 98 llvm_unreachable("Invalid opcode for compound assignment."); 99 case BO_MulAssign: Op = BO_Mul; break; 100 case BO_DivAssign: Op = BO_Div; break; 101 case BO_RemAssign: Op = BO_Rem; break; 102 case BO_AddAssign: Op = BO_Add; break; 103 case BO_SubAssign: Op = BO_Sub; break; 104 case BO_ShlAssign: Op = BO_Shl; break; 105 case BO_ShrAssign: Op = BO_Shr; break; 106 case BO_AndAssign: Op = BO_And; break; 107 case BO_XorAssign: Op = BO_Xor; break; 108 case BO_OrAssign: Op = BO_Or; break; 109 } 110 111 // Perform a load (the LHS). This performs the checks for 112 // null dereferences, and so on. 113 ExplodedNodeSet Tmp; 114 SVal location = LeftV; 115 evalLoad(Tmp, B, LHS, *it, state, location); 116 117 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; 118 ++I) { 119 120 state = (*I)->getState(); 121 const LocationContext *LCtx = (*I)->getLocationContext(); 122 SVal V = state->getSVal(LHS, LCtx); 123 124 // Get the computation type. 125 QualType CTy = 126 cast<CompoundAssignOperator>(B)->getComputationResultType(); 127 CTy = getContext().getCanonicalType(CTy); 128 129 QualType CLHSTy = 130 cast<CompoundAssignOperator>(B)->getComputationLHSType(); 131 CLHSTy = getContext().getCanonicalType(CLHSTy); 132 133 QualType LTy = getContext().getCanonicalType(LHS->getType()); 134 135 // Promote LHS. 136 V = svalBuilder.evalCast(V, CLHSTy, LTy); 137 138 // Compute the result of the operation. 139 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy), 140 B->getType(), CTy); 141 142 // EXPERIMENTAL: "Conjured" symbols. 143 // FIXME: Handle structs. 144 145 SVal LHSVal; 146 147 if (Result.isUnknown()) { 148 // The symbolic value is actually for the type of the left-hand side 149 // expression, not the computation type, as this is the value the 150 // LValue on the LHS will bind to. 151 LHSVal = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, LTy, 152 currBldrCtx->blockCount()); 153 // However, we need to convert the symbol to the computation type. 154 Result = svalBuilder.evalCast(LHSVal, CTy, LTy); 155 } 156 else { 157 // The left-hand side may bind to a different value then the 158 // computation type. 159 LHSVal = svalBuilder.evalCast(Result, LTy, CTy); 160 } 161 162 // In C++, assignment and compound assignment operators return an 163 // lvalue. 164 if (B->isGLValue()) 165 state = state->BindExpr(B, LCtx, location); 166 else 167 state = state->BindExpr(B, LCtx, Result); 168 169 evalStore(Tmp2, B, LHS, *I, state, location, LHSVal); 170 } 171 } 172 173 // FIXME: postvisits eventually go in ::Visit() 174 getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this); 175} 176 177void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 178 ExplodedNodeSet &Dst) { 179 180 CanQualType T = getContext().getCanonicalType(BE->getType()); 181 182 // Get the value of the block itself. 183 SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T, 184 Pred->getLocationContext()); 185 186 ProgramStateRef State = Pred->getState(); 187 188 // If we created a new MemRegion for the block, we should explicitly bind 189 // the captured variables. 190 if (const BlockDataRegion *BDR = 191 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) { 192 193 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(), 194 E = BDR->referenced_vars_end(); 195 196 for (; I != E; ++I) { 197 const MemRegion *capturedR = I.getCapturedRegion(); 198 const MemRegion *originalR = I.getOriginalRegion(); 199 if (capturedR != originalR) { 200 SVal originalV = State->getSVal(loc::MemRegionVal(originalR)); 201 State = State->bindLoc(loc::MemRegionVal(capturedR), originalV); 202 } 203 } 204 } 205 206 ExplodedNodeSet Tmp; 207 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 208 Bldr.generateNode(BE, Pred, 209 State->BindExpr(BE, Pred->getLocationContext(), V), 210 0, ProgramPoint::PostLValueKind); 211 212 // FIXME: Move all post/pre visits to ::Visit(). 213 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this); 214} 215 216void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 217 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 218 219 ExplodedNodeSet dstPreStmt; 220 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this); 221 222 if (CastE->getCastKind() == CK_LValueToRValue) { 223 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 224 I!=E; ++I) { 225 ExplodedNode *subExprNode = *I; 226 ProgramStateRef state = subExprNode->getState(); 227 const LocationContext *LCtx = subExprNode->getLocationContext(); 228 evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx)); 229 } 230 return; 231 } 232 233 // All other casts. 234 QualType T = CastE->getType(); 235 QualType ExTy = Ex->getType(); 236 237 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) 238 T = ExCast->getTypeAsWritten(); 239 240 StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx); 241 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 242 I != E; ++I) { 243 244 Pred = *I; 245 ProgramStateRef state = Pred->getState(); 246 const LocationContext *LCtx = Pred->getLocationContext(); 247 248 switch (CastE->getCastKind()) { 249 case CK_LValueToRValue: 250 llvm_unreachable("LValueToRValue casts handled earlier."); 251 case CK_ToVoid: 252 continue; 253 // The analyzer doesn't do anything special with these casts, 254 // since it understands retain/release semantics already. 255 case CK_ARCProduceObject: 256 case CK_ARCConsumeObject: 257 case CK_ARCReclaimReturnedObject: 258 case CK_ARCExtendBlockObject: // Fall-through. 259 case CK_CopyAndAutoreleaseBlockObject: 260 // The analyser can ignore atomic casts for now, although some future 261 // checkers may want to make certain that you're not modifying the same 262 // value through atomic and nonatomic pointers. 263 case CK_AtomicToNonAtomic: 264 case CK_NonAtomicToAtomic: 265 // True no-ops. 266 case CK_NoOp: 267 case CK_UserDefinedConversion: 268 case CK_FunctionToPointerDecay: { 269 // Copy the SVal of Ex to CastE. 270 ProgramStateRef state = Pred->getState(); 271 const LocationContext *LCtx = Pred->getLocationContext(); 272 SVal V = state->getSVal(Ex, LCtx); 273 state = state->BindExpr(CastE, LCtx, V); 274 Bldr.generateNode(CastE, Pred, state); 275 continue; 276 } 277 case CK_MemberPointerToBoolean: 278 // FIXME: For now, member pointers are represented by void *. 279 // FALLTHROUGH 280 case CK_Dependent: 281 case CK_ArrayToPointerDecay: 282 case CK_BitCast: 283 case CK_IntegralCast: 284 case CK_NullToPointer: 285 case CK_IntegralToPointer: 286 case CK_PointerToIntegral: 287 case CK_PointerToBoolean: 288 case CK_IntegralToBoolean: 289 case CK_IntegralToFloating: 290 case CK_FloatingToIntegral: 291 case CK_FloatingToBoolean: 292 case CK_FloatingCast: 293 case CK_FloatingRealToComplex: 294 case CK_FloatingComplexToReal: 295 case CK_FloatingComplexToBoolean: 296 case CK_FloatingComplexCast: 297 case CK_FloatingComplexToIntegralComplex: 298 case CK_IntegralRealToComplex: 299 case CK_IntegralComplexToReal: 300 case CK_IntegralComplexToBoolean: 301 case CK_IntegralComplexCast: 302 case CK_IntegralComplexToFloatingComplex: 303 case CK_CPointerToObjCPointerCast: 304 case CK_BlockPointerToObjCPointerCast: 305 case CK_AnyPointerToBlockPointerCast: 306 case CK_ObjCObjectLValueCast: { 307 // Delegate to SValBuilder to process. 308 SVal V = state->getSVal(Ex, LCtx); 309 V = svalBuilder.evalCast(V, T, ExTy); 310 state = state->BindExpr(CastE, LCtx, V); 311 Bldr.generateNode(CastE, Pred, state); 312 continue; 313 } 314 case CK_DerivedToBase: 315 case CK_UncheckedDerivedToBase: { 316 // For DerivedToBase cast, delegate to the store manager. 317 SVal val = state->getSVal(Ex, LCtx); 318 val = getStoreManager().evalDerivedToBase(val, CastE); 319 state = state->BindExpr(CastE, LCtx, val); 320 Bldr.generateNode(CastE, Pred, state); 321 continue; 322 } 323 // Handle C++ dyn_cast. 324 case CK_Dynamic: { 325 SVal val = state->getSVal(Ex, LCtx); 326 327 // Compute the type of the result. 328 QualType resultType = CastE->getType(); 329 if (CastE->isGLValue()) 330 resultType = getContext().getPointerType(resultType); 331 332 bool Failed = false; 333 334 // Check if the value being cast evaluates to 0. 335 if (val.isZeroConstant()) 336 Failed = true; 337 // Else, evaluate the cast. 338 else 339 val = getStoreManager().evalDynamicCast(val, T, Failed); 340 341 if (Failed) { 342 if (T->isReferenceType()) { 343 // A bad_cast exception is thrown if input value is a reference. 344 // Currently, we model this, by generating a sink. 345 Bldr.generateSink(CastE, Pred, state); 346 continue; 347 } else { 348 // If the cast fails on a pointer, bind to 0. 349 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull()); 350 } 351 } else { 352 // If we don't know if the cast succeeded, conjure a new symbol. 353 if (val.isUnknown()) { 354 DefinedOrUnknownSVal NewSym = 355 svalBuilder.conjureSymbolVal(0, CastE, LCtx, resultType, 356 currBldrCtx->blockCount()); 357 state = state->BindExpr(CastE, LCtx, NewSym); 358 } else 359 // Else, bind to the derived region value. 360 state = state->BindExpr(CastE, LCtx, val); 361 } 362 Bldr.generateNode(CastE, Pred, state); 363 continue; 364 } 365 case CK_NullToMemberPointer: { 366 // FIXME: For now, member pointers are represented by void *. 367 SVal V = svalBuilder.makeIntValWithPtrWidth(0, true); 368 state = state->BindExpr(CastE, LCtx, V); 369 Bldr.generateNode(CastE, Pred, state); 370 continue; 371 } 372 // Various C++ casts that are not handled yet. 373 case CK_ToUnion: 374 case CK_BaseToDerived: 375 case CK_BaseToDerivedMemberPointer: 376 case CK_DerivedToBaseMemberPointer: 377 case CK_ReinterpretMemberPointer: 378 case CK_ConstructorConversion: 379 case CK_VectorSplat: 380 case CK_LValueBitCast: { 381 // Recover some path-sensitivty by conjuring a new value. 382 QualType resultType = CastE->getType(); 383 if (CastE->isGLValue()) 384 resultType = getContext().getPointerType(resultType); 385 SVal result = svalBuilder.conjureSymbolVal(0, CastE, LCtx, 386 resultType, 387 currBldrCtx->blockCount()); 388 state = state->BindExpr(CastE, LCtx, result); 389 Bldr.generateNode(CastE, Pred, state); 390 continue; 391 } 392 } 393 } 394} 395 396void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 397 ExplodedNode *Pred, 398 ExplodedNodeSet &Dst) { 399 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 400 401 const InitListExpr *ILE 402 = cast<InitListExpr>(CL->getInitializer()->IgnoreParens()); 403 404 ProgramStateRef state = Pred->getState(); 405 SVal ILV = state->getSVal(ILE, Pred->getLocationContext()); 406 const LocationContext *LC = Pred->getLocationContext(); 407 state = state->bindCompoundLiteral(CL, LC, ILV); 408 409 // Compound literal expressions are a GNU extension in C++. 410 // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues, 411 // and like temporary objects created by the functional notation T() 412 // CLs are destroyed at the end of the containing full-expression. 413 // HOWEVER, an rvalue of array type is not something the analyzer can 414 // reason about, since we expect all regions to be wrapped in Locs. 415 // So we treat array CLs as lvalues as well, knowing that they will decay 416 // to pointers as soon as they are used. 417 if (CL->isGLValue() || CL->getType()->isArrayType()) 418 B.generateNode(CL, Pred, state->BindExpr(CL, LC, state->getLValue(CL, LC))); 419 else 420 B.generateNode(CL, Pred, state->BindExpr(CL, LC, ILV)); 421} 422 423void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 424 ExplodedNodeSet &Dst) { 425 426 // FIXME: static variables may have an initializer, but the second 427 // time a function is called those values may not be current. 428 // This may need to be reflected in the CFG. 429 430 // Assumption: The CFG has one DeclStmt per Decl. 431 const Decl *D = *DS->decl_begin(); 432 433 if (!D || !isa<VarDecl>(D)) { 434 //TODO:AZ: remove explicit insertion after refactoring is done. 435 Dst.insert(Pred); 436 return; 437 } 438 439 // FIXME: all pre/post visits should eventually be handled by ::Visit(). 440 ExplodedNodeSet dstPreVisit; 441 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this); 442 443 StmtNodeBuilder B(dstPreVisit, Dst, *currBldrCtx); 444 const VarDecl *VD = dyn_cast<VarDecl>(D); 445 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 446 I!=E; ++I) { 447 ExplodedNode *N = *I; 448 ProgramStateRef state = N->getState(); 449 450 // Decls without InitExpr are not initialized explicitly. 451 const LocationContext *LC = N->getLocationContext(); 452 453 if (const Expr *InitEx = VD->getInit()) { 454 SVal InitVal = state->getSVal(InitEx, LC); 455 456 if (InitVal == state->getLValue(VD, LC) || 457 (VD->getType()->isArrayType() && 458 isa<CXXConstructExpr>(InitEx->IgnoreImplicit()))) { 459 // We constructed the object directly in the variable. 460 // No need to bind anything. 461 B.generateNode(DS, N, state); 462 } else { 463 // We bound the temp obj region to the CXXConstructExpr. Now recover 464 // the lazy compound value when the variable is not a reference. 465 if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() && 466 !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){ 467 InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion()); 468 assert(isa<nonloc::LazyCompoundVal>(InitVal)); 469 } 470 471 // Recover some path-sensitivity if a scalar value evaluated to 472 // UnknownVal. 473 if (InitVal.isUnknown()) { 474 QualType Ty = InitEx->getType(); 475 if (InitEx->isGLValue()) { 476 Ty = getContext().getPointerType(Ty); 477 } 478 479 InitVal = svalBuilder.conjureSymbolVal(0, InitEx, LC, Ty, 480 currBldrCtx->blockCount()); 481 } 482 B.takeNodes(N); 483 ExplodedNodeSet Dst2; 484 evalBind(Dst2, DS, N, state->getLValue(VD, LC), InitVal, true); 485 B.addNodes(Dst2); 486 } 487 } 488 else { 489 B.generateNode(DS, N, state); 490 } 491 } 492} 493 494void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 495 ExplodedNodeSet &Dst) { 496 assert(B->getOpcode() == BO_LAnd || 497 B->getOpcode() == BO_LOr); 498 499 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 500 ProgramStateRef state = Pred->getState(); 501 502 ExplodedNode *N = Pred; 503 while (!isa<BlockEntrance>(N->getLocation())) { 504 ProgramPoint P = N->getLocation(); 505 assert(isa<PreStmt>(P)|| isa<PreStmtPurgeDeadSymbols>(P)); 506 (void) P; 507 assert(N->pred_size() == 1); 508 N = *N->pred_begin(); 509 } 510 assert(N->pred_size() == 1); 511 N = *N->pred_begin(); 512 BlockEdge BE = cast<BlockEdge>(N->getLocation()); 513 SVal X; 514 515 // Determine the value of the expression by introspecting how we 516 // got this location in the CFG. This requires looking at the previous 517 // block we were in and what kind of control-flow transfer was involved. 518 const CFGBlock *SrcBlock = BE.getSrc(); 519 // The only terminator (if there is one) that makes sense is a logical op. 520 CFGTerminator T = SrcBlock->getTerminator(); 521 if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) { 522 (void) Term; 523 assert(Term->isLogicalOp()); 524 assert(SrcBlock->succ_size() == 2); 525 // Did we take the true or false branch? 526 unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0; 527 X = svalBuilder.makeIntVal(constant, B->getType()); 528 } 529 else { 530 // If there is no terminator, by construction the last statement 531 // in SrcBlock is the value of the enclosing expression. 532 // However, we still need to constrain that value to be 0 or 1. 533 assert(!SrcBlock->empty()); 534 CFGStmt Elem = cast<CFGStmt>(*SrcBlock->rbegin()); 535 const Expr *RHS = cast<Expr>(Elem.getStmt()); 536 SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext()); 537 538 DefinedOrUnknownSVal DefinedRHS = cast<DefinedOrUnknownSVal>(RHSVal); 539 ProgramStateRef StTrue, StFalse; 540 llvm::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS); 541 if (StTrue) { 542 if (StFalse) { 543 // We can't constrain the value to 0 or 1; the best we can do is a cast. 544 X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType()); 545 } else { 546 // The value is known to be true. 547 X = getSValBuilder().makeIntVal(1, B->getType()); 548 } 549 } else { 550 // The value is known to be false. 551 assert(StFalse && "Infeasible path!"); 552 X = getSValBuilder().makeIntVal(0, B->getType()); 553 } 554 } 555 556 Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X)); 557} 558 559void ExprEngine::VisitInitListExpr(const InitListExpr *IE, 560 ExplodedNode *Pred, 561 ExplodedNodeSet &Dst) { 562 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 563 564 ProgramStateRef state = Pred->getState(); 565 const LocationContext *LCtx = Pred->getLocationContext(); 566 QualType T = getContext().getCanonicalType(IE->getType()); 567 unsigned NumInitElements = IE->getNumInits(); 568 569 if (T->isArrayType() || T->isRecordType() || T->isVectorType()) { 570 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList(); 571 572 // Handle base case where the initializer has no elements. 573 // e.g: static int* myArray[] = {}; 574 if (NumInitElements == 0) { 575 SVal V = svalBuilder.makeCompoundVal(T, vals); 576 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 577 return; 578 } 579 580 for (InitListExpr::const_reverse_iterator it = IE->rbegin(), 581 ei = IE->rend(); it != ei; ++it) { 582 vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it), LCtx), 583 vals); 584 } 585 586 B.generateNode(IE, Pred, 587 state->BindExpr(IE, LCtx, 588 svalBuilder.makeCompoundVal(T, vals))); 589 return; 590 } 591 592 // Handle scalars: int{5} and int{}. 593 assert(NumInitElements <= 1); 594 595 SVal V; 596 if (NumInitElements == 0) 597 V = getSValBuilder().makeZeroVal(T); 598 else 599 V = state->getSVal(IE->getInit(0), LCtx); 600 601 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 602} 603 604void ExprEngine::VisitGuardedExpr(const Expr *Ex, 605 const Expr *L, 606 const Expr *R, 607 ExplodedNode *Pred, 608 ExplodedNodeSet &Dst) { 609 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 610 ProgramStateRef state = Pred->getState(); 611 const LocationContext *LCtx = Pred->getLocationContext(); 612 const CFGBlock *SrcBlock = 0; 613 614 for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) { 615 ProgramPoint PP = N->getLocation(); 616 if (isa<PreStmtPurgeDeadSymbols>(PP) || isa<BlockEntrance>(PP)) { 617 assert(N->pred_size() == 1); 618 continue; 619 } 620 SrcBlock = cast<BlockEdge>(&PP)->getSrc(); 621 break; 622 } 623 624 // Find the last expression in the predecessor block. That is the 625 // expression that is used for the value of the ternary expression. 626 bool hasValue = false; 627 SVal V; 628 629 for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(), 630 E = SrcBlock->rend(); I != E; ++I) { 631 CFGElement CE = *I; 632 if (CFGStmt *CS = dyn_cast<CFGStmt>(&CE)) { 633 const Expr *ValEx = cast<Expr>(CS->getStmt()); 634 hasValue = true; 635 V = state->getSVal(ValEx, LCtx); 636 break; 637 } 638 } 639 640 assert(hasValue); 641 (void) hasValue; 642 643 // Generate a new node with the binding from the appropriate path. 644 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true)); 645} 646 647void ExprEngine:: 648VisitOffsetOfExpr(const OffsetOfExpr *OOE, 649 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 650 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 651 APSInt IV; 652 if (OOE->EvaluateAsInt(IV, getContext())) { 653 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 654 assert(OOE->getType()->isIntegerType()); 655 assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType()); 656 SVal X = svalBuilder.makeIntVal(IV); 657 B.generateNode(OOE, Pred, 658 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(), 659 X)); 660 } 661 // FIXME: Handle the case where __builtin_offsetof is not a constant. 662} 663 664 665void ExprEngine:: 666VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 667 ExplodedNode *Pred, 668 ExplodedNodeSet &Dst) { 669 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 670 671 QualType T = Ex->getTypeOfArgument(); 672 673 if (Ex->getKind() == UETT_SizeOf) { 674 if (!T->isIncompleteType() && !T->isConstantSizeType()) { 675 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 676 677 // FIXME: Add support for VLA type arguments and VLA expressions. 678 // When that happens, we should probably refactor VLASizeChecker's code. 679 return; 680 } 681 else if (T->getAs<ObjCObjectType>()) { 682 // Some code tries to take the sizeof an ObjCObjectType, relying that 683 // the compiler has laid out its representation. Just report Unknown 684 // for these. 685 return; 686 } 687 } 688 689 APSInt Value = Ex->EvaluateKnownConstInt(getContext()); 690 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue()); 691 692 ProgramStateRef state = Pred->getState(); 693 state = state->BindExpr(Ex, Pred->getLocationContext(), 694 svalBuilder.makeIntVal(amt.getQuantity(), 695 Ex->getType())); 696 Bldr.generateNode(Ex, Pred, state); 697} 698 699void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, 700 ExplodedNode *Pred, 701 ExplodedNodeSet &Dst) { 702 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 703 switch (U->getOpcode()) { 704 default: { 705 Bldr.takeNodes(Pred); 706 ExplodedNodeSet Tmp; 707 VisitIncrementDecrementOperator(U, Pred, Tmp); 708 Bldr.addNodes(Tmp); 709 } 710 break; 711 case UO_Real: { 712 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 713 714 // FIXME: We don't have complex SValues yet. 715 if (Ex->getType()->isAnyComplexType()) { 716 // Just report "Unknown." 717 break; 718 } 719 720 // For all other types, UO_Real is an identity operation. 721 assert (U->getType() == Ex->getType()); 722 ProgramStateRef state = Pred->getState(); 723 const LocationContext *LCtx = Pred->getLocationContext(); 724 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 725 state->getSVal(Ex, LCtx))); 726 break; 727 } 728 729 case UO_Imag: { 730 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 731 // FIXME: We don't have complex SValues yet. 732 if (Ex->getType()->isAnyComplexType()) { 733 // Just report "Unknown." 734 break; 735 } 736 // For all other types, UO_Imag returns 0. 737 ProgramStateRef state = Pred->getState(); 738 const LocationContext *LCtx = Pred->getLocationContext(); 739 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 740 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X)); 741 break; 742 } 743 744 case UO_Plus: 745 assert(!U->isGLValue()); 746 // FALL-THROUGH. 747 case UO_Deref: 748 case UO_AddrOf: 749 case UO_Extension: { 750 // FIXME: We can probably just have some magic in Environment::getSVal() 751 // that propagates values, instead of creating a new node here. 752 // 753 // Unary "+" is a no-op, similar to a parentheses. We still have places 754 // where it may be a block-level expression, so we need to 755 // generate an extra node that just propagates the value of the 756 // subexpression. 757 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 758 ProgramStateRef state = Pred->getState(); 759 const LocationContext *LCtx = Pred->getLocationContext(); 760 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 761 state->getSVal(Ex, LCtx))); 762 break; 763 } 764 765 case UO_LNot: 766 case UO_Minus: 767 case UO_Not: { 768 assert (!U->isGLValue()); 769 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 770 ProgramStateRef state = Pred->getState(); 771 const LocationContext *LCtx = Pred->getLocationContext(); 772 773 // Get the value of the subexpression. 774 SVal V = state->getSVal(Ex, LCtx); 775 776 if (V.isUnknownOrUndef()) { 777 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V)); 778 break; 779 } 780 781 switch (U->getOpcode()) { 782 default: 783 llvm_unreachable("Invalid Opcode."); 784 case UO_Not: 785 // FIXME: Do we need to handle promotions? 786 state = state->BindExpr(U, LCtx, evalComplement(cast<NonLoc>(V))); 787 break; 788 case UO_Minus: 789 // FIXME: Do we need to handle promotions? 790 state = state->BindExpr(U, LCtx, evalMinus(cast<NonLoc>(V))); 791 break; 792 case UO_LNot: 793 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 794 // 795 // Note: technically we do "E == 0", but this is the same in the 796 // transfer functions as "0 == E". 797 SVal Result; 798 if (isa<Loc>(V)) { 799 Loc X = svalBuilder.makeNull(); 800 Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X, 801 U->getType()); 802 } 803 else { 804 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 805 Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X, 806 U->getType()); 807 } 808 809 state = state->BindExpr(U, LCtx, Result); 810 break; 811 } 812 Bldr.generateNode(U, Pred, state); 813 break; 814 } 815 } 816 817} 818 819void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U, 820 ExplodedNode *Pred, 821 ExplodedNodeSet &Dst) { 822 // Handle ++ and -- (both pre- and post-increment). 823 assert (U->isIncrementDecrementOp()); 824 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 825 826 const LocationContext *LCtx = Pred->getLocationContext(); 827 ProgramStateRef state = Pred->getState(); 828 SVal loc = state->getSVal(Ex, LCtx); 829 830 // Perform a load. 831 ExplodedNodeSet Tmp; 832 evalLoad(Tmp, U, Ex, Pred, state, loc); 833 834 ExplodedNodeSet Dst2; 835 StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx); 836 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) { 837 838 state = (*I)->getState(); 839 assert(LCtx == (*I)->getLocationContext()); 840 SVal V2_untested = state->getSVal(Ex, LCtx); 841 842 // Propagate unknown and undefined values. 843 if (V2_untested.isUnknownOrUndef()) { 844 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested)); 845 continue; 846 } 847 DefinedSVal V2 = cast<DefinedSVal>(V2_untested); 848 849 // Handle all other values. 850 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub; 851 852 // If the UnaryOperator has non-location type, use its type to create the 853 // constant value. If the UnaryOperator has location type, create the 854 // constant with int type and pointer width. 855 SVal RHS; 856 857 if (U->getType()->isAnyPointerType()) 858 RHS = svalBuilder.makeArrayIndex(1); 859 else 860 RHS = svalBuilder.makeIntVal(1, U->getType()); 861 862 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 863 864 // Conjure a new symbol if necessary to recover precision. 865 if (Result.isUnknown()){ 866 DefinedOrUnknownSVal SymVal = 867 svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount()); 868 Result = SymVal; 869 870 // If the value is a location, ++/-- should always preserve 871 // non-nullness. Check if the original value was non-null, and if so 872 // propagate that constraint. 873 if (Loc::isLocType(U->getType())) { 874 DefinedOrUnknownSVal Constraint = 875 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 876 877 if (!state->assume(Constraint, true)) { 878 // It isn't feasible for the original value to be null. 879 // Propagate this constraint. 880 Constraint = svalBuilder.evalEQ(state, SymVal, 881 svalBuilder.makeZeroVal(U->getType())); 882 883 884 state = state->assume(Constraint, false); 885 assert(state); 886 } 887 } 888 } 889 890 // Since the lvalue-to-rvalue conversion is explicit in the AST, 891 // we bind an l-value if the operator is prefix and an lvalue (in C++). 892 if (U->isGLValue()) 893 state = state->BindExpr(U, LCtx, loc); 894 else 895 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result); 896 897 // Perform the store. 898 Bldr.takeNodes(*I); 899 ExplodedNodeSet Dst3; 900 evalStore(Dst3, U, U, *I, state, loc, Result); 901 Bldr.addNodes(Dst3); 902 } 903 Dst.insert(Dst2); 904} 905