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