ExprEngineC.cpp revision 1994e3993e5e2c606f4ab22563768af6f03dad30
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_ConstructorConversion: 268 case CK_UserDefinedConversion: 269 case CK_FunctionToPointerDecay: 270 case CK_BuiltinFnToFnPtr: { 271 // Copy the SVal of Ex to CastE. 272 ProgramStateRef state = Pred->getState(); 273 const LocationContext *LCtx = Pred->getLocationContext(); 274 SVal V = state->getSVal(Ex, LCtx); 275 state = state->BindExpr(CastE, LCtx, V); 276 Bldr.generateNode(CastE, Pred, state); 277 continue; 278 } 279 case CK_MemberPointerToBoolean: 280 // FIXME: For now, member pointers are represented by void *. 281 // FALLTHROUGH 282 case CK_Dependent: 283 case CK_ArrayToPointerDecay: 284 case CK_BitCast: 285 case CK_IntegralCast: 286 case CK_NullToPointer: 287 case CK_IntegralToPointer: 288 case CK_PointerToIntegral: 289 case CK_PointerToBoolean: 290 case CK_IntegralToBoolean: 291 case CK_IntegralToFloating: 292 case CK_FloatingToIntegral: 293 case CK_FloatingToBoolean: 294 case CK_FloatingCast: 295 case CK_FloatingRealToComplex: 296 case CK_FloatingComplexToReal: 297 case CK_FloatingComplexToBoolean: 298 case CK_FloatingComplexCast: 299 case CK_FloatingComplexToIntegralComplex: 300 case CK_IntegralRealToComplex: 301 case CK_IntegralComplexToReal: 302 case CK_IntegralComplexToBoolean: 303 case CK_IntegralComplexCast: 304 case CK_IntegralComplexToFloatingComplex: 305 case CK_CPointerToObjCPointerCast: 306 case CK_BlockPointerToObjCPointerCast: 307 case CK_AnyPointerToBlockPointerCast: 308 case CK_ObjCObjectLValueCast: { 309 // Delegate to SValBuilder to process. 310 SVal V = state->getSVal(Ex, LCtx); 311 V = svalBuilder.evalCast(V, T, ExTy); 312 state = state->BindExpr(CastE, LCtx, V); 313 Bldr.generateNode(CastE, Pred, state); 314 continue; 315 } 316 case CK_DerivedToBase: 317 case CK_UncheckedDerivedToBase: { 318 // For DerivedToBase cast, delegate to the store manager. 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 SVal val = state->getSVal(Ex, LCtx); 328 329 // Compute the type of the result. 330 QualType resultType = CastE->getType(); 331 if (CastE->isGLValue()) 332 resultType = getContext().getPointerType(resultType); 333 334 bool Failed = false; 335 336 // Check if the value being cast evaluates to 0. 337 if (val.isZeroConstant()) 338 Failed = true; 339 // Else, evaluate the cast. 340 else 341 val = getStoreManager().evalDynamicCast(val, T, Failed); 342 343 if (Failed) { 344 if (T->isReferenceType()) { 345 // A bad_cast exception is thrown if input value is a reference. 346 // Currently, we model this, by generating a sink. 347 Bldr.generateSink(CastE, Pred, state); 348 continue; 349 } else { 350 // If the cast fails on a pointer, bind to 0. 351 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull()); 352 } 353 } else { 354 // If we don't know if the cast succeeded, conjure a new symbol. 355 if (val.isUnknown()) { 356 DefinedOrUnknownSVal NewSym = 357 svalBuilder.conjureSymbolVal(0, CastE, LCtx, resultType, 358 currBldrCtx->blockCount()); 359 state = state->BindExpr(CastE, LCtx, NewSym); 360 } else 361 // Else, bind to the derived region value. 362 state = state->BindExpr(CastE, LCtx, val); 363 } 364 Bldr.generateNode(CastE, Pred, state); 365 continue; 366 } 367 case CK_NullToMemberPointer: { 368 // FIXME: For now, member pointers are represented by void *. 369 SVal V = svalBuilder.makeIntValWithPtrWidth(0, true); 370 state = state->BindExpr(CastE, LCtx, V); 371 Bldr.generateNode(CastE, Pred, state); 372 continue; 373 } 374 // Various C++ casts that are not handled yet. 375 case CK_ToUnion: 376 case CK_BaseToDerived: 377 case CK_BaseToDerivedMemberPointer: 378 case CK_DerivedToBaseMemberPointer: 379 case CK_ReinterpretMemberPointer: 380 case CK_VectorSplat: 381 case CK_LValueBitCast: { 382 // Recover some path-sensitivty by conjuring a new value. 383 QualType resultType = CastE->getType(); 384 if (CastE->isGLValue()) 385 resultType = getContext().getPointerType(resultType); 386 SVal result = svalBuilder.conjureSymbolVal(0, CastE, LCtx, 387 resultType, 388 currBldrCtx->blockCount()); 389 state = state->BindExpr(CastE, LCtx, 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, *currBldrCtx); 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, *currBldrCtx); 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.conjureSymbolVal(0, InitEx, LC, Ty, 481 currBldrCtx->blockCount()); 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, *currBldrCtx); 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, *currBldrCtx); 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 T->isAnyComplexType()) { 572 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList(); 573 574 // Handle base case where the initializer has no elements. 575 // e.g: static int* myArray[] = {}; 576 if (NumInitElements == 0) { 577 SVal V = svalBuilder.makeCompoundVal(T, vals); 578 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 579 return; 580 } 581 582 for (InitListExpr::const_reverse_iterator it = IE->rbegin(), 583 ei = IE->rend(); it != ei; ++it) { 584 SVal V = state->getSVal(cast<Expr>(*it), LCtx); 585 if (dyn_cast_or_null<CXXTempObjectRegion>(V.getAsRegion())) 586 V = UnknownVal(); 587 vals = getBasicVals().consVals(V, vals); 588 } 589 590 B.generateNode(IE, Pred, 591 state->BindExpr(IE, LCtx, 592 svalBuilder.makeCompoundVal(T, vals))); 593 return; 594 } 595 596 // Handle scalars: int{5} and int{}. 597 assert(NumInitElements <= 1); 598 599 SVal V; 600 if (NumInitElements == 0) 601 V = getSValBuilder().makeZeroVal(T); 602 else 603 V = state->getSVal(IE->getInit(0), LCtx); 604 605 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 606} 607 608void ExprEngine::VisitGuardedExpr(const Expr *Ex, 609 const Expr *L, 610 const Expr *R, 611 ExplodedNode *Pred, 612 ExplodedNodeSet &Dst) { 613 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 614 ProgramStateRef state = Pred->getState(); 615 const LocationContext *LCtx = Pred->getLocationContext(); 616 const CFGBlock *SrcBlock = 0; 617 618 for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) { 619 ProgramPoint PP = N->getLocation(); 620 if (isa<PreStmtPurgeDeadSymbols>(PP) || isa<BlockEntrance>(PP)) { 621 assert(N->pred_size() == 1); 622 continue; 623 } 624 SrcBlock = cast<BlockEdge>(&PP)->getSrc(); 625 break; 626 } 627 628 // Find the last expression in the predecessor block. That is the 629 // expression that is used for the value of the ternary expression. 630 bool hasValue = false; 631 SVal V; 632 633 for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(), 634 E = SrcBlock->rend(); I != E; ++I) { 635 CFGElement CE = *I; 636 if (CFGStmt *CS = dyn_cast<CFGStmt>(&CE)) { 637 const Expr *ValEx = cast<Expr>(CS->getStmt()); 638 hasValue = true; 639 V = state->getSVal(ValEx, LCtx); 640 break; 641 } 642 } 643 644 assert(hasValue); 645 (void) hasValue; 646 647 // Generate a new node with the binding from the appropriate path. 648 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true)); 649} 650 651void ExprEngine:: 652VisitOffsetOfExpr(const OffsetOfExpr *OOE, 653 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 654 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 655 APSInt IV; 656 if (OOE->EvaluateAsInt(IV, getContext())) { 657 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 658 assert(OOE->getType()->isIntegerType()); 659 assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType()); 660 SVal X = svalBuilder.makeIntVal(IV); 661 B.generateNode(OOE, Pred, 662 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(), 663 X)); 664 } 665 // FIXME: Handle the case where __builtin_offsetof is not a constant. 666} 667 668 669void ExprEngine:: 670VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 671 ExplodedNode *Pred, 672 ExplodedNodeSet &Dst) { 673 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 674 675 QualType T = Ex->getTypeOfArgument(); 676 677 if (Ex->getKind() == UETT_SizeOf) { 678 if (!T->isIncompleteType() && !T->isConstantSizeType()) { 679 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 680 681 // FIXME: Add support for VLA type arguments and VLA expressions. 682 // When that happens, we should probably refactor VLASizeChecker's code. 683 return; 684 } 685 else if (T->getAs<ObjCObjectType>()) { 686 // Some code tries to take the sizeof an ObjCObjectType, relying that 687 // the compiler has laid out its representation. Just report Unknown 688 // for these. 689 return; 690 } 691 } 692 693 APSInt Value = Ex->EvaluateKnownConstInt(getContext()); 694 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue()); 695 696 ProgramStateRef state = Pred->getState(); 697 state = state->BindExpr(Ex, Pred->getLocationContext(), 698 svalBuilder.makeIntVal(amt.getQuantity(), 699 Ex->getType())); 700 Bldr.generateNode(Ex, Pred, state); 701} 702 703void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, 704 ExplodedNode *Pred, 705 ExplodedNodeSet &Dst) { 706 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 707 switch (U->getOpcode()) { 708 default: { 709 Bldr.takeNodes(Pred); 710 ExplodedNodeSet Tmp; 711 VisitIncrementDecrementOperator(U, Pred, Tmp); 712 Bldr.addNodes(Tmp); 713 } 714 break; 715 case UO_Real: { 716 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 717 718 // FIXME: We don't have complex SValues yet. 719 if (Ex->getType()->isAnyComplexType()) { 720 // Just report "Unknown." 721 break; 722 } 723 724 // For all other types, UO_Real is an identity operation. 725 assert (U->getType() == Ex->getType()); 726 ProgramStateRef state = Pred->getState(); 727 const LocationContext *LCtx = Pred->getLocationContext(); 728 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 729 state->getSVal(Ex, LCtx))); 730 break; 731 } 732 733 case UO_Imag: { 734 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 735 // FIXME: We don't have complex SValues yet. 736 if (Ex->getType()->isAnyComplexType()) { 737 // Just report "Unknown." 738 break; 739 } 740 // For all other types, UO_Imag returns 0. 741 ProgramStateRef state = Pred->getState(); 742 const LocationContext *LCtx = Pred->getLocationContext(); 743 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 744 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X)); 745 break; 746 } 747 748 case UO_Plus: 749 assert(!U->isGLValue()); 750 // FALL-THROUGH. 751 case UO_Deref: 752 case UO_AddrOf: 753 case UO_Extension: { 754 // FIXME: We can probably just have some magic in Environment::getSVal() 755 // that propagates values, instead of creating a new node here. 756 // 757 // Unary "+" is a no-op, similar to a parentheses. We still have places 758 // where it may be a block-level expression, so we need to 759 // generate an extra node that just propagates the value of the 760 // subexpression. 761 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 762 ProgramStateRef state = Pred->getState(); 763 const LocationContext *LCtx = Pred->getLocationContext(); 764 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 765 state->getSVal(Ex, LCtx))); 766 break; 767 } 768 769 case UO_LNot: 770 case UO_Minus: 771 case UO_Not: { 772 assert (!U->isGLValue()); 773 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 774 ProgramStateRef state = Pred->getState(); 775 const LocationContext *LCtx = Pred->getLocationContext(); 776 777 // Get the value of the subexpression. 778 SVal V = state->getSVal(Ex, LCtx); 779 780 if (V.isUnknownOrUndef()) { 781 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V)); 782 break; 783 } 784 785 switch (U->getOpcode()) { 786 default: 787 llvm_unreachable("Invalid Opcode."); 788 case UO_Not: 789 // FIXME: Do we need to handle promotions? 790 state = state->BindExpr(U, LCtx, evalComplement(cast<NonLoc>(V))); 791 break; 792 case UO_Minus: 793 // FIXME: Do we need to handle promotions? 794 state = state->BindExpr(U, LCtx, evalMinus(cast<NonLoc>(V))); 795 break; 796 case UO_LNot: 797 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 798 // 799 // Note: technically we do "E == 0", but this is the same in the 800 // transfer functions as "0 == E". 801 SVal Result; 802 if (isa<Loc>(V)) { 803 Loc X = svalBuilder.makeNull(); 804 Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X, 805 U->getType()); 806 } 807 else { 808 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 809 Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X, 810 U->getType()); 811 } 812 813 state = state->BindExpr(U, LCtx, Result); 814 break; 815 } 816 Bldr.generateNode(U, Pred, state); 817 break; 818 } 819 } 820 821} 822 823void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U, 824 ExplodedNode *Pred, 825 ExplodedNodeSet &Dst) { 826 // Handle ++ and -- (both pre- and post-increment). 827 assert (U->isIncrementDecrementOp()); 828 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 829 830 const LocationContext *LCtx = Pred->getLocationContext(); 831 ProgramStateRef state = Pred->getState(); 832 SVal loc = state->getSVal(Ex, LCtx); 833 834 // Perform a load. 835 ExplodedNodeSet Tmp; 836 evalLoad(Tmp, U, Ex, Pred, state, loc); 837 838 ExplodedNodeSet Dst2; 839 StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx); 840 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) { 841 842 state = (*I)->getState(); 843 assert(LCtx == (*I)->getLocationContext()); 844 SVal V2_untested = state->getSVal(Ex, LCtx); 845 846 // Propagate unknown and undefined values. 847 if (V2_untested.isUnknownOrUndef()) { 848 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested)); 849 continue; 850 } 851 DefinedSVal V2 = cast<DefinedSVal>(V2_untested); 852 853 // Handle all other values. 854 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub; 855 856 // If the UnaryOperator has non-location type, use its type to create the 857 // constant value. If the UnaryOperator has location type, create the 858 // constant with int type and pointer width. 859 SVal RHS; 860 861 if (U->getType()->isAnyPointerType()) 862 RHS = svalBuilder.makeArrayIndex(1); 863 else if (U->getType()->isIntegralOrEnumerationType()) 864 RHS = svalBuilder.makeIntVal(1, U->getType()); 865 else 866 RHS = UnknownVal(); 867 868 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 869 870 // Conjure a new symbol if necessary to recover precision. 871 if (Result.isUnknown()){ 872 DefinedOrUnknownSVal SymVal = 873 svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount()); 874 Result = SymVal; 875 876 // If the value is a location, ++/-- should always preserve 877 // non-nullness. Check if the original value was non-null, and if so 878 // propagate that constraint. 879 if (Loc::isLocType(U->getType())) { 880 DefinedOrUnknownSVal Constraint = 881 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 882 883 if (!state->assume(Constraint, true)) { 884 // It isn't feasible for the original value to be null. 885 // Propagate this constraint. 886 Constraint = svalBuilder.evalEQ(state, SymVal, 887 svalBuilder.makeZeroVal(U->getType())); 888 889 890 state = state->assume(Constraint, false); 891 assert(state); 892 } 893 } 894 } 895 896 // Since the lvalue-to-rvalue conversion is explicit in the AST, 897 // we bind an l-value if the operator is prefix and an lvalue (in C++). 898 if (U->isGLValue()) 899 state = state->BindExpr(U, LCtx, loc); 900 else 901 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result); 902 903 // Perform the store. 904 Bldr.takeNodes(*I); 905 ExplodedNodeSet Dst3; 906 evalStore(Dst3, U, U, *I, state, loc, Result); 907 Bldr.addNodes(Dst3); 908 } 909 Dst.insert(Dst2); 910} 911