clang API Documentation

ExprEngineC.cpp
Go to the documentation of this file.
00001 //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines ExprEngine's support for C expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/ExprCXX.h"
00015 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
00016 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
00017 
00018 using namespace clang;
00019 using namespace ento;
00020 using llvm::APSInt;
00021 
00022 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
00023                                      ExplodedNode *Pred,
00024                                      ExplodedNodeSet &Dst) {
00025 
00026   Expr *LHS = B->getLHS()->IgnoreParens();
00027   Expr *RHS = B->getRHS()->IgnoreParens();
00028   
00029   // FIXME: Prechecks eventually go in ::Visit().
00030   ExplodedNodeSet CheckedSet;
00031   ExplodedNodeSet Tmp2;
00032   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
00033     
00034   // With both the LHS and RHS evaluated, process the operation itself.    
00035   for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
00036          it != ei; ++it) {
00037       
00038     ProgramStateRef state = (*it)->getState();
00039     const LocationContext *LCtx = (*it)->getLocationContext();
00040     SVal LeftV = state->getSVal(LHS, LCtx);
00041     SVal RightV = state->getSVal(RHS, LCtx);
00042       
00043     BinaryOperator::Opcode Op = B->getOpcode();
00044       
00045     if (Op == BO_Assign) {
00046       // EXPERIMENTAL: "Conjured" symbols.
00047       // FIXME: Handle structs.
00048       if (RightV.isUnknown()) {
00049         unsigned Count = currBldrCtx->blockCount();
00050         RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
00051                                               Count);
00052       }
00053       // Simulate the effects of a "store":  bind the value of the RHS
00054       // to the L-Value represented by the LHS.
00055       SVal ExprVal = B->isGLValue() ? LeftV : RightV;
00056       evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
00057                 LeftV, RightV);
00058       continue;
00059     }
00060       
00061     if (!B->isAssignmentOp()) {
00062       StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
00063 
00064       if (B->isAdditiveOp()) {
00065         // If one of the operands is a location, conjure a symbol for the other
00066         // one (offset) if it's unknown so that memory arithmetic always
00067         // results in an ElementRegion.
00068         // TODO: This can be removed after we enable history tracking with
00069         // SymSymExpr.
00070         unsigned Count = currBldrCtx->blockCount();
00071         if (LeftV.getAs<Loc>() &&
00072             RHS->getType()->isIntegralOrEnumerationType() &&
00073             RightV.isUnknown()) {
00074           RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
00075                                                 Count);
00076         }
00077         if (RightV.getAs<Loc>() &&
00078             LHS->getType()->isIntegralOrEnumerationType() &&
00079             LeftV.isUnknown()) {
00080           LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
00081                                                Count);
00082         }
00083       }
00084 
00085       // Although we don't yet model pointers-to-members, we do need to make
00086       // sure that the members of temporaries have a valid 'this' pointer for
00087       // other checks.
00088       if (B->getOpcode() == BO_PtrMemD)
00089         state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
00090 
00091       // Process non-assignments except commas or short-circuited
00092       // logical expressions (LAnd and LOr).
00093       SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());      
00094       if (Result.isUnknown()) {
00095         Bldr.generateNode(B, *it, state);
00096         continue;
00097       }        
00098 
00099       state = state->BindExpr(B, LCtx, Result);      
00100       Bldr.generateNode(B, *it, state);
00101       continue;
00102     }
00103       
00104     assert (B->isCompoundAssignmentOp());
00105     
00106     switch (Op) {
00107       default:
00108         llvm_unreachable("Invalid opcode for compound assignment.");
00109       case BO_MulAssign: Op = BO_Mul; break;
00110       case BO_DivAssign: Op = BO_Div; break;
00111       case BO_RemAssign: Op = BO_Rem; break;
00112       case BO_AddAssign: Op = BO_Add; break;
00113       case BO_SubAssign: Op = BO_Sub; break;
00114       case BO_ShlAssign: Op = BO_Shl; break;
00115       case BO_ShrAssign: Op = BO_Shr; break;
00116       case BO_AndAssign: Op = BO_And; break;
00117       case BO_XorAssign: Op = BO_Xor; break;
00118       case BO_OrAssign:  Op = BO_Or;  break;
00119     }
00120       
00121     // Perform a load (the LHS).  This performs the checks for
00122     // null dereferences, and so on.
00123     ExplodedNodeSet Tmp;
00124     SVal location = LeftV;
00125     evalLoad(Tmp, B, LHS, *it, state, location);
00126     
00127     for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
00128          ++I) {
00129 
00130       state = (*I)->getState();
00131       const LocationContext *LCtx = (*I)->getLocationContext();
00132       SVal V = state->getSVal(LHS, LCtx);
00133       
00134       // Get the computation type.
00135       QualType CTy =
00136         cast<CompoundAssignOperator>(B)->getComputationResultType();
00137       CTy = getContext().getCanonicalType(CTy);
00138       
00139       QualType CLHSTy =
00140         cast<CompoundAssignOperator>(B)->getComputationLHSType();
00141       CLHSTy = getContext().getCanonicalType(CLHSTy);
00142       
00143       QualType LTy = getContext().getCanonicalType(LHS->getType());
00144       
00145       // Promote LHS.
00146       V = svalBuilder.evalCast(V, CLHSTy, LTy);
00147       
00148       // Compute the result of the operation.
00149       SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
00150                                          B->getType(), CTy);
00151       
00152       // EXPERIMENTAL: "Conjured" symbols.
00153       // FIXME: Handle structs.
00154       
00155       SVal LHSVal;
00156       
00157       if (Result.isUnknown()) {
00158         // The symbolic value is actually for the type of the left-hand side
00159         // expression, not the computation type, as this is the value the
00160         // LValue on the LHS will bind to.
00161         LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
00162                                               currBldrCtx->blockCount());
00163         // However, we need to convert the symbol to the computation type.
00164         Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
00165       }
00166       else {
00167         // The left-hand side may bind to a different value then the
00168         // computation type.
00169         LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
00170       }
00171       
00172       // In C++, assignment and compound assignment operators return an 
00173       // lvalue.
00174       if (B->isGLValue())
00175         state = state->BindExpr(B, LCtx, location);
00176       else
00177         state = state->BindExpr(B, LCtx, Result);
00178       
00179       evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
00180     }
00181   }
00182   
00183   // FIXME: postvisits eventually go in ::Visit()
00184   getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
00185 }
00186 
00187 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
00188                                 ExplodedNodeSet &Dst) {
00189   
00190   CanQualType T = getContext().getCanonicalType(BE->getType());
00191 
00192   // Get the value of the block itself.
00193   SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
00194                                        Pred->getLocationContext(),
00195                                        currBldrCtx->blockCount());
00196   
00197   ProgramStateRef State = Pred->getState();
00198   
00199   // If we created a new MemRegion for the block, we should explicitly bind
00200   // the captured variables.
00201   if (const BlockDataRegion *BDR =
00202       dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
00203     
00204     BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
00205                                               E = BDR->referenced_vars_end();
00206     
00207     for (; I != E; ++I) {
00208       const MemRegion *capturedR = I.getCapturedRegion();
00209       const MemRegion *originalR = I.getOriginalRegion();
00210       if (capturedR != originalR) {
00211         SVal originalV = State->getSVal(loc::MemRegionVal(originalR));
00212         State = State->bindLoc(loc::MemRegionVal(capturedR), originalV);
00213       }
00214     }
00215   }
00216   
00217   ExplodedNodeSet Tmp;
00218   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
00219   Bldr.generateNode(BE, Pred,
00220                     State->BindExpr(BE, Pred->getLocationContext(), V),
00221                     nullptr, ProgramPoint::PostLValueKind);
00222 
00223   // FIXME: Move all post/pre visits to ::Visit().
00224   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
00225 }
00226 
00227 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 
00228                            ExplodedNode *Pred, ExplodedNodeSet &Dst) {
00229   
00230   ExplodedNodeSet dstPreStmt;
00231   getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
00232   
00233   if (CastE->getCastKind() == CK_LValueToRValue) {
00234     for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
00235          I!=E; ++I) {
00236       ExplodedNode *subExprNode = *I;
00237       ProgramStateRef state = subExprNode->getState();
00238       const LocationContext *LCtx = subExprNode->getLocationContext();
00239       evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
00240     }
00241     return;
00242   }
00243   
00244   // All other casts.  
00245   QualType T = CastE->getType();
00246   QualType ExTy = Ex->getType();
00247   
00248   if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
00249     T = ExCast->getTypeAsWritten();
00250   
00251   StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
00252   for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
00253        I != E; ++I) {
00254     
00255     Pred = *I;
00256     ProgramStateRef state = Pred->getState();
00257     const LocationContext *LCtx = Pred->getLocationContext();
00258 
00259     switch (CastE->getCastKind()) {
00260       case CK_LValueToRValue:
00261         llvm_unreachable("LValueToRValue casts handled earlier.");
00262       case CK_ToVoid:
00263         continue;
00264         // The analyzer doesn't do anything special with these casts,
00265         // since it understands retain/release semantics already.
00266       case CK_ARCProduceObject:
00267       case CK_ARCConsumeObject:
00268       case CK_ARCReclaimReturnedObject:
00269       case CK_ARCExtendBlockObject: // Fall-through.
00270       case CK_CopyAndAutoreleaseBlockObject:
00271         // The analyser can ignore atomic casts for now, although some future
00272         // checkers may want to make certain that you're not modifying the same
00273         // value through atomic and nonatomic pointers.
00274       case CK_AtomicToNonAtomic:
00275       case CK_NonAtomicToAtomic:
00276         // True no-ops.
00277       case CK_NoOp:
00278       case CK_ConstructorConversion:
00279       case CK_UserDefinedConversion:
00280       case CK_FunctionToPointerDecay:
00281       case CK_BuiltinFnToFnPtr: {
00282         // Copy the SVal of Ex to CastE.
00283         ProgramStateRef state = Pred->getState();
00284         const LocationContext *LCtx = Pred->getLocationContext();
00285         SVal V = state->getSVal(Ex, LCtx);
00286         state = state->BindExpr(CastE, LCtx, V);
00287         Bldr.generateNode(CastE, Pred, state);
00288         continue;
00289       }
00290       case CK_MemberPointerToBoolean:
00291         // FIXME: For now, member pointers are represented by void *.
00292         // FALLTHROUGH
00293       case CK_Dependent:
00294       case CK_ArrayToPointerDecay:
00295       case CK_BitCast:
00296       case CK_AddressSpaceConversion:
00297       case CK_IntegralCast:
00298       case CK_NullToPointer:
00299       case CK_IntegralToPointer:
00300       case CK_PointerToIntegral:
00301       case CK_PointerToBoolean:
00302       case CK_IntegralToBoolean:
00303       case CK_IntegralToFloating:
00304       case CK_FloatingToIntegral:
00305       case CK_FloatingToBoolean:
00306       case CK_FloatingCast:
00307       case CK_FloatingRealToComplex:
00308       case CK_FloatingComplexToReal:
00309       case CK_FloatingComplexToBoolean:
00310       case CK_FloatingComplexCast:
00311       case CK_FloatingComplexToIntegralComplex:
00312       case CK_IntegralRealToComplex:
00313       case CK_IntegralComplexToReal:
00314       case CK_IntegralComplexToBoolean:
00315       case CK_IntegralComplexCast:
00316       case CK_IntegralComplexToFloatingComplex:
00317       case CK_CPointerToObjCPointerCast:
00318       case CK_BlockPointerToObjCPointerCast:
00319       case CK_AnyPointerToBlockPointerCast:  
00320       case CK_ObjCObjectLValueCast: 
00321       case CK_ZeroToOCLEvent:
00322       case CK_LValueBitCast: {
00323         // Delegate to SValBuilder to process.
00324         SVal V = state->getSVal(Ex, LCtx);
00325         V = svalBuilder.evalCast(V, T, ExTy);
00326         state = state->BindExpr(CastE, LCtx, V);
00327         Bldr.generateNode(CastE, Pred, state);
00328         continue;
00329       }
00330       case CK_DerivedToBase:
00331       case CK_UncheckedDerivedToBase: {
00332         // For DerivedToBase cast, delegate to the store manager.
00333         SVal val = state->getSVal(Ex, LCtx);
00334         val = getStoreManager().evalDerivedToBase(val, CastE);
00335         state = state->BindExpr(CastE, LCtx, val);
00336         Bldr.generateNode(CastE, Pred, state);
00337         continue;
00338       }
00339       // Handle C++ dyn_cast.
00340       case CK_Dynamic: {
00341         SVal val = state->getSVal(Ex, LCtx);
00342 
00343         // Compute the type of the result.
00344         QualType resultType = CastE->getType();
00345         if (CastE->isGLValue())
00346           resultType = getContext().getPointerType(resultType);
00347 
00348         bool Failed = false;
00349 
00350         // Check if the value being cast evaluates to 0.
00351         if (val.isZeroConstant())
00352           Failed = true;
00353         // Else, evaluate the cast.
00354         else
00355           val = getStoreManager().evalDynamicCast(val, T, Failed);
00356 
00357         if (Failed) {
00358           if (T->isReferenceType()) {
00359             // A bad_cast exception is thrown if input value is a reference.
00360             // Currently, we model this, by generating a sink.
00361             Bldr.generateSink(CastE, Pred, state);
00362             continue;
00363           } else {
00364             // If the cast fails on a pointer, bind to 0.
00365             state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
00366           }
00367         } else {
00368           // If we don't know if the cast succeeded, conjure a new symbol.
00369           if (val.isUnknown()) {
00370             DefinedOrUnknownSVal NewSym =
00371               svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
00372                                            currBldrCtx->blockCount());
00373             state = state->BindExpr(CastE, LCtx, NewSym);
00374           } else 
00375             // Else, bind to the derived region value.
00376             state = state->BindExpr(CastE, LCtx, val);
00377         }
00378         Bldr.generateNode(CastE, Pred, state);
00379         continue;
00380       }
00381       case CK_NullToMemberPointer: {
00382         // FIXME: For now, member pointers are represented by void *.
00383         SVal V = svalBuilder.makeNull();
00384         state = state->BindExpr(CastE, LCtx, V);
00385         Bldr.generateNode(CastE, Pred, state);
00386         continue;
00387       }
00388       // Various C++ casts that are not handled yet.
00389       case CK_ToUnion:
00390       case CK_BaseToDerived:
00391       case CK_BaseToDerivedMemberPointer:
00392       case CK_DerivedToBaseMemberPointer:
00393       case CK_ReinterpretMemberPointer:
00394       case CK_VectorSplat: {
00395         // Recover some path-sensitivty by conjuring a new value.
00396         QualType resultType = CastE->getType();
00397         if (CastE->isGLValue())
00398           resultType = getContext().getPointerType(resultType);
00399         SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
00400                                                    resultType,
00401                                                    currBldrCtx->blockCount());
00402         state = state->BindExpr(CastE, LCtx, result);
00403         Bldr.generateNode(CastE, Pred, state);
00404         continue;
00405       }
00406     }
00407   }
00408 }
00409 
00410 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
00411                                           ExplodedNode *Pred,
00412                                           ExplodedNodeSet &Dst) {
00413   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
00414 
00415   ProgramStateRef State = Pred->getState();
00416   const LocationContext *LCtx = Pred->getLocationContext();
00417 
00418   const Expr *Init = CL->getInitializer();
00419   SVal V = State->getSVal(CL->getInitializer(), LCtx);
00420   
00421   if (isa<CXXConstructExpr>(Init)) {
00422     // No work needed. Just pass the value up to this expression.
00423   } else {
00424     assert(isa<InitListExpr>(Init));
00425     Loc CLLoc = State->getLValue(CL, LCtx);
00426     State = State->bindLoc(CLLoc, V);
00427 
00428     // Compound literal expressions are a GNU extension in C++.
00429     // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
00430     // and like temporary objects created by the functional notation T()
00431     // CLs are destroyed at the end of the containing full-expression.
00432     // HOWEVER, an rvalue of array type is not something the analyzer can
00433     // reason about, since we expect all regions to be wrapped in Locs.
00434     // So we treat array CLs as lvalues as well, knowing that they will decay
00435     // to pointers as soon as they are used.
00436     if (CL->isGLValue() || CL->getType()->isArrayType())
00437       V = CLLoc;
00438   }
00439 
00440   B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
00441 }
00442 
00443 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
00444                                ExplodedNodeSet &Dst) {
00445   // Assumption: The CFG has one DeclStmt per Decl.
00446   const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
00447 
00448   if (!VD) {
00449     //TODO:AZ: remove explicit insertion after refactoring is done.
00450     Dst.insert(Pred);
00451     return;
00452   }
00453   
00454   // FIXME: all pre/post visits should eventually be handled by ::Visit().
00455   ExplodedNodeSet dstPreVisit;
00456   getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
00457   
00458   ExplodedNodeSet dstEvaluated;
00459   StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
00460   for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
00461        I!=E; ++I) {
00462     ExplodedNode *N = *I;
00463     ProgramStateRef state = N->getState();
00464     const LocationContext *LC = N->getLocationContext();
00465 
00466     // Decls without InitExpr are not initialized explicitly.
00467     if (const Expr *InitEx = VD->getInit()) {
00468 
00469       // Note in the state that the initialization has occurred.
00470       ExplodedNode *UpdatedN = N;
00471       SVal InitVal = state->getSVal(InitEx, LC);
00472 
00473       if (isa<CXXConstructExpr>(InitEx->IgnoreImplicit())) {
00474         // We constructed the object directly in the variable.
00475         // No need to bind anything.
00476         B.generateNode(DS, UpdatedN, state);
00477       } else {
00478         // We bound the temp obj region to the CXXConstructExpr. Now recover
00479         // the lazy compound value when the variable is not a reference.
00480         if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
00481             !VD->getType()->isReferenceType()) {
00482           if (Optional<loc::MemRegionVal> M =
00483                   InitVal.getAs<loc::MemRegionVal>()) {
00484             InitVal = state->getSVal(M->getRegion());
00485             assert(InitVal.getAs<nonloc::LazyCompoundVal>());
00486           }
00487         }
00488         
00489         // Recover some path-sensitivity if a scalar value evaluated to
00490         // UnknownVal.
00491         if (InitVal.isUnknown()) {
00492           QualType Ty = InitEx->getType();
00493           if (InitEx->isGLValue()) {
00494             Ty = getContext().getPointerType(Ty);
00495           }
00496 
00497           InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
00498                                                  currBldrCtx->blockCount());
00499         }
00500 
00501 
00502         B.takeNodes(UpdatedN);
00503         ExplodedNodeSet Dst2;
00504         evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
00505         B.addNodes(Dst2);
00506       }
00507     }
00508     else {
00509       B.generateNode(DS, N, state);
00510     }
00511   }
00512 
00513   getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
00514 }
00515 
00516 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
00517                                   ExplodedNodeSet &Dst) {
00518   assert(B->getOpcode() == BO_LAnd ||
00519          B->getOpcode() == BO_LOr);
00520 
00521   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
00522   ProgramStateRef state = Pred->getState();
00523 
00524   ExplodedNode *N = Pred;
00525   while (!N->getLocation().getAs<BlockEntrance>()) {
00526     ProgramPoint P = N->getLocation();
00527     assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
00528     (void) P;
00529     assert(N->pred_size() == 1);
00530     N = *N->pred_begin();
00531   }
00532   assert(N->pred_size() == 1);
00533   N = *N->pred_begin();
00534   BlockEdge BE = N->getLocation().castAs<BlockEdge>();
00535   SVal X;
00536 
00537   // Determine the value of the expression by introspecting how we
00538   // got this location in the CFG.  This requires looking at the previous
00539   // block we were in and what kind of control-flow transfer was involved.
00540   const CFGBlock *SrcBlock = BE.getSrc();
00541   // The only terminator (if there is one) that makes sense is a logical op.
00542   CFGTerminator T = SrcBlock->getTerminator();
00543   if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
00544     (void) Term;
00545     assert(Term->isLogicalOp());
00546     assert(SrcBlock->succ_size() == 2);
00547     // Did we take the true or false branch?
00548     unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
00549     X = svalBuilder.makeIntVal(constant, B->getType());
00550   }
00551   else {
00552     // If there is no terminator, by construction the last statement
00553     // in SrcBlock is the value of the enclosing expression.
00554     // However, we still need to constrain that value to be 0 or 1.
00555     assert(!SrcBlock->empty());
00556     CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
00557     const Expr *RHS = cast<Expr>(Elem.getStmt());
00558     SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
00559 
00560     if (RHSVal.isUndef()) {
00561       X = RHSVal;
00562     } else {
00563       DefinedOrUnknownSVal DefinedRHS = RHSVal.castAs<DefinedOrUnknownSVal>();
00564       ProgramStateRef StTrue, StFalse;
00565       std::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS);
00566       if (StTrue) {
00567         if (StFalse) {
00568           // We can't constrain the value to 0 or 1.
00569           // The best we can do is a cast.
00570           X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType());
00571         } else {
00572           // The value is known to be true.
00573           X = getSValBuilder().makeIntVal(1, B->getType());
00574         }
00575       } else {
00576         // The value is known to be false.
00577         assert(StFalse && "Infeasible path!");
00578         X = getSValBuilder().makeIntVal(0, B->getType());
00579       }
00580     }
00581   }
00582   Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
00583 }
00584 
00585 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
00586                                    ExplodedNode *Pred,
00587                                    ExplodedNodeSet &Dst) {
00588   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
00589 
00590   ProgramStateRef state = Pred->getState();
00591   const LocationContext *LCtx = Pred->getLocationContext();
00592   QualType T = getContext().getCanonicalType(IE->getType());
00593   unsigned NumInitElements = IE->getNumInits();
00594 
00595   if (!IE->isGLValue() &&
00596       (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
00597        T->isAnyComplexType())) {
00598     llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
00599     
00600     // Handle base case where the initializer has no elements.
00601     // e.g: static int* myArray[] = {};
00602     if (NumInitElements == 0) {
00603       SVal V = svalBuilder.makeCompoundVal(T, vals);
00604       B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
00605       return;
00606     }
00607     
00608     for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
00609          ei = IE->rend(); it != ei; ++it) {
00610       SVal V = state->getSVal(cast<Expr>(*it), LCtx);
00611       vals = getBasicVals().consVals(V, vals);
00612     }
00613     
00614     B.generateNode(IE, Pred,
00615                    state->BindExpr(IE, LCtx,
00616                                    svalBuilder.makeCompoundVal(T, vals)));
00617     return;
00618   }
00619 
00620   // Handle scalars: int{5} and int{} and GLvalues.
00621   // Note, if the InitListExpr is a GLvalue, it means that there is an address
00622   // representing it, so it must have a single init element.
00623   assert(NumInitElements <= 1);
00624 
00625   SVal V;
00626   if (NumInitElements == 0)
00627     V = getSValBuilder().makeZeroVal(T);
00628   else
00629     V = state->getSVal(IE->getInit(0), LCtx);
00630 
00631   B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
00632 }
00633 
00634 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
00635                                   const Expr *L, 
00636                                   const Expr *R,
00637                                   ExplodedNode *Pred,
00638                                   ExplodedNodeSet &Dst) {
00639   assert(L && R);
00640 
00641   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
00642   ProgramStateRef state = Pred->getState();
00643   const LocationContext *LCtx = Pred->getLocationContext();
00644   const CFGBlock *SrcBlock = nullptr;
00645 
00646   // Find the predecessor block.
00647   ProgramStateRef SrcState = state;
00648   for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
00649     ProgramPoint PP = N->getLocation();
00650     if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
00651       assert(N->pred_size() == 1);
00652       continue;
00653     }
00654     SrcBlock = PP.castAs<BlockEdge>().getSrc();
00655     SrcState = N->getState();
00656     break;
00657   }
00658 
00659   assert(SrcBlock && "missing function entry");
00660 
00661   // Find the last expression in the predecessor block.  That is the
00662   // expression that is used for the value of the ternary expression.
00663   bool hasValue = false;
00664   SVal V;
00665 
00666   for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(),
00667                                         E = SrcBlock->rend(); I != E; ++I) {
00668     CFGElement CE = *I;
00669     if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
00670       const Expr *ValEx = cast<Expr>(CS->getStmt());
00671       ValEx = ValEx->IgnoreParens();
00672 
00673       // For GNU extension '?:' operator, the left hand side will be an
00674       // OpaqueValueExpr, so get the underlying expression.
00675       if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
00676         L = OpaqueEx->getSourceExpr();
00677 
00678       // If the last expression in the predecessor block matches true or false
00679       // subexpression, get its the value.
00680       if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
00681         hasValue = true;
00682         V = SrcState->getSVal(ValEx, LCtx);
00683       }
00684       break;
00685     }
00686   }
00687 
00688   if (!hasValue)
00689     V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
00690                                      currBldrCtx->blockCount());
00691 
00692   // Generate a new node with the binding from the appropriate path.
00693   B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
00694 }
00695 
00696 void ExprEngine::
00697 VisitOffsetOfExpr(const OffsetOfExpr *OOE, 
00698                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
00699   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
00700   APSInt IV;
00701   if (OOE->EvaluateAsInt(IV, getContext())) {
00702     assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
00703     assert(OOE->getType()->isBuiltinType());
00704     assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
00705     assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
00706     SVal X = svalBuilder.makeIntVal(IV);
00707     B.generateNode(OOE, Pred,
00708                    Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
00709                                               X));
00710   }
00711   // FIXME: Handle the case where __builtin_offsetof is not a constant.
00712 }
00713 
00714 
00715 void ExprEngine::
00716 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
00717                               ExplodedNode *Pred,
00718                               ExplodedNodeSet &Dst) {
00719   // FIXME: Prechecks eventually go in ::Visit().
00720   ExplodedNodeSet CheckedSet;
00721   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
00722 
00723   ExplodedNodeSet EvalSet;
00724   StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
00725 
00726   QualType T = Ex->getTypeOfArgument();
00727 
00728   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
00729        I != E; ++I) {
00730     if (Ex->getKind() == UETT_SizeOf) {
00731       if (!T->isIncompleteType() && !T->isConstantSizeType()) {
00732         assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
00733         
00734         // FIXME: Add support for VLA type arguments and VLA expressions.
00735         // When that happens, we should probably refactor VLASizeChecker's code.
00736         continue;
00737       } else if (T->getAs<ObjCObjectType>()) {
00738         // Some code tries to take the sizeof an ObjCObjectType, relying that
00739         // the compiler has laid out its representation.  Just report Unknown
00740         // for these.
00741         continue;
00742       }
00743     }
00744     
00745     APSInt Value = Ex->EvaluateKnownConstInt(getContext());
00746     CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
00747     
00748     ProgramStateRef state = (*I)->getState();
00749     state = state->BindExpr(Ex, (*I)->getLocationContext(),
00750                             svalBuilder.makeIntVal(amt.getQuantity(),
00751                                                    Ex->getType()));
00752     Bldr.generateNode(Ex, *I, state);
00753   }
00754 
00755   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
00756 }
00757 
00758 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, 
00759                                     ExplodedNode *Pred,
00760                                     ExplodedNodeSet &Dst) {
00761   // FIXME: Prechecks eventually go in ::Visit().
00762   ExplodedNodeSet CheckedSet;
00763   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
00764 
00765   ExplodedNodeSet EvalSet;
00766   StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
00767 
00768   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
00769        I != E; ++I) {
00770     switch (U->getOpcode()) {
00771     default: {
00772       Bldr.takeNodes(*I);
00773       ExplodedNodeSet Tmp;
00774       VisitIncrementDecrementOperator(U, *I, Tmp);
00775       Bldr.addNodes(Tmp);
00776       break;
00777     }
00778     case UO_Real: {
00779       const Expr *Ex = U->getSubExpr()->IgnoreParens();
00780         
00781       // FIXME: We don't have complex SValues yet.
00782       if (Ex->getType()->isAnyComplexType()) {
00783         // Just report "Unknown."
00784         break;
00785       }
00786         
00787       // For all other types, UO_Real is an identity operation.
00788       assert (U->getType() == Ex->getType());
00789       ProgramStateRef state = (*I)->getState();
00790       const LocationContext *LCtx = (*I)->getLocationContext();
00791       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
00792                                                state->getSVal(Ex, LCtx)));
00793       break;
00794     }
00795       
00796     case UO_Imag: {      
00797       const Expr *Ex = U->getSubExpr()->IgnoreParens();
00798       // FIXME: We don't have complex SValues yet.
00799       if (Ex->getType()->isAnyComplexType()) {
00800         // Just report "Unknown."
00801         break;
00802       }
00803       // For all other types, UO_Imag returns 0.
00804       ProgramStateRef state = (*I)->getState();
00805       const LocationContext *LCtx = (*I)->getLocationContext();
00806       SVal X = svalBuilder.makeZeroVal(Ex->getType());
00807       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
00808       break;
00809     }
00810       
00811     case UO_Plus:
00812       assert(!U->isGLValue());
00813       // FALL-THROUGH.
00814     case UO_Deref:
00815     case UO_AddrOf:
00816     case UO_Extension: {
00817       // FIXME: We can probably just have some magic in Environment::getSVal()
00818       // that propagates values, instead of creating a new node here.
00819       //
00820       // Unary "+" is a no-op, similar to a parentheses.  We still have places
00821       // where it may be a block-level expression, so we need to
00822       // generate an extra node that just propagates the value of the
00823       // subexpression.      
00824       const Expr *Ex = U->getSubExpr()->IgnoreParens();
00825       ProgramStateRef state = (*I)->getState();
00826       const LocationContext *LCtx = (*I)->getLocationContext();
00827       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
00828                                                state->getSVal(Ex, LCtx)));
00829       break;
00830     }
00831       
00832     case UO_LNot:
00833     case UO_Minus:
00834     case UO_Not: {
00835       assert (!U->isGLValue());
00836       const Expr *Ex = U->getSubExpr()->IgnoreParens();
00837       ProgramStateRef state = (*I)->getState();
00838       const LocationContext *LCtx = (*I)->getLocationContext();
00839         
00840       // Get the value of the subexpression.
00841       SVal V = state->getSVal(Ex, LCtx);
00842         
00843       if (V.isUnknownOrUndef()) {
00844         Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
00845         break;
00846       }
00847         
00848       switch (U->getOpcode()) {
00849         default:
00850           llvm_unreachable("Invalid Opcode.");
00851         case UO_Not:
00852           // FIXME: Do we need to handle promotions?
00853           state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
00854           break;
00855         case UO_Minus:
00856           // FIXME: Do we need to handle promotions?
00857           state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
00858           break;
00859         case UO_LNot:
00860           // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
00861           //
00862           //  Note: technically we do "E == 0", but this is the same in the
00863           //    transfer functions as "0 == E".
00864           SVal Result;          
00865           if (Optional<Loc> LV = V.getAs<Loc>()) {
00866             Loc X = svalBuilder.makeNull();
00867             Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
00868           }
00869           else if (Ex->getType()->isFloatingType()) {
00870             // FIXME: handle floating point types.
00871             Result = UnknownVal();
00872           } else {
00873             nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
00874             Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
00875                                U->getType());
00876           }
00877           
00878           state = state->BindExpr(U, LCtx, Result);          
00879           break;
00880       }
00881       Bldr.generateNode(U, *I, state);
00882       break;
00883     }
00884     }
00885   }
00886 
00887   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
00888 }
00889 
00890 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
00891                                                  ExplodedNode *Pred,
00892                                                  ExplodedNodeSet &Dst) {
00893   // Handle ++ and -- (both pre- and post-increment).
00894   assert (U->isIncrementDecrementOp());
00895   const Expr *Ex = U->getSubExpr()->IgnoreParens();
00896   
00897   const LocationContext *LCtx = Pred->getLocationContext();
00898   ProgramStateRef state = Pred->getState();
00899   SVal loc = state->getSVal(Ex, LCtx);
00900   
00901   // Perform a load.
00902   ExplodedNodeSet Tmp;
00903   evalLoad(Tmp, U, Ex, Pred, state, loc);
00904   
00905   ExplodedNodeSet Dst2;
00906   StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
00907   for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
00908     
00909     state = (*I)->getState();
00910     assert(LCtx == (*I)->getLocationContext());
00911     SVal V2_untested = state->getSVal(Ex, LCtx);
00912     
00913     // Propagate unknown and undefined values.
00914     if (V2_untested.isUnknownOrUndef()) {
00915       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
00916       continue;
00917     }
00918     DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
00919     
00920     // Handle all other values.
00921     BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
00922     
00923     // If the UnaryOperator has non-location type, use its type to create the
00924     // constant value. If the UnaryOperator has location type, create the
00925     // constant with int type and pointer width.
00926     SVal RHS;
00927     
00928     if (U->getType()->isAnyPointerType())
00929       RHS = svalBuilder.makeArrayIndex(1);
00930     else if (U->getType()->isIntegralOrEnumerationType())
00931       RHS = svalBuilder.makeIntVal(1, U->getType());
00932     else
00933       RHS = UnknownVal();
00934     
00935     SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
00936     
00937     // Conjure a new symbol if necessary to recover precision.
00938     if (Result.isUnknown()){
00939       DefinedOrUnknownSVal SymVal =
00940         svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
00941                                      currBldrCtx->blockCount());
00942       Result = SymVal;
00943       
00944       // If the value is a location, ++/-- should always preserve
00945       // non-nullness.  Check if the original value was non-null, and if so
00946       // propagate that constraint.
00947       if (Loc::isLocType(U->getType())) {
00948         DefinedOrUnknownSVal Constraint =
00949         svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
00950         
00951         if (!state->assume(Constraint, true)) {
00952           // It isn't feasible for the original value to be null.
00953           // Propagate this constraint.
00954           Constraint = svalBuilder.evalEQ(state, SymVal,
00955                                        svalBuilder.makeZeroVal(U->getType()));
00956           
00957           
00958           state = state->assume(Constraint, false);
00959           assert(state);
00960         }
00961       }
00962     }
00963     
00964     // Since the lvalue-to-rvalue conversion is explicit in the AST,
00965     // we bind an l-value if the operator is prefix and an lvalue (in C++).
00966     if (U->isGLValue())
00967       state = state->BindExpr(U, LCtx, loc);
00968     else
00969       state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
00970     
00971     // Perform the store.
00972     Bldr.takeNodes(*I);
00973     ExplodedNodeSet Dst3;
00974     evalStore(Dst3, U, U, *I, state, loc, Result);
00975     Bldr.addNodes(Dst3);
00976   }
00977   Dst.insert(Dst2);
00978 }