clang 22.0.0git
SValBuilder.cpp
Go to the documentation of this file.
1//===- SValBuilder.cpp - Basic class for all SValBuilder implementations --===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines SValBuilder, the base class for all (complete) SValBuilder
10// implementations.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/Stmt.h"
21#include "clang/AST/Type.h"
23#include "clang/Basic/LLVM.h"
37#include "llvm/ADT/APSInt.h"
38#include "llvm/Support/Compiler.h"
39#include <cassert>
40#include <optional>
41#include <tuple>
42
43using namespace clang;
44using namespace ento;
45
46//===----------------------------------------------------------------------===//
47// Basic SVal creation.
48//===----------------------------------------------------------------------===//
49
50void SValBuilder::anchor() {}
51
52SValBuilder::SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
53 ProgramStateManager &stateMgr)
54 : Context(context), BasicVals(context, alloc),
55 SymMgr(context, BasicVals, alloc), MemMgr(context, alloc),
56 StateMgr(stateMgr),
57 AnOpts(
58 stateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions()),
59 ArrayIndexTy(context.LongLongTy),
60 ArrayIndexWidth(context.getTypeSize(ArrayIndexTy)) {}
61
64 return makeNullWithType(type);
65
66 if (type->isIntegralOrEnumerationType())
67 return makeIntVal(0, type);
68
69 if (type->isArrayType() || type->isRecordType() || type->isVectorType() ||
70 type->isAnyComplexType())
72
73 // FIXME: Handle floats.
74 return UnknownVal();
75}
76
79 APSIntPtr rhs, QualType type) {
80 assert(lhs);
81 assert(!Loc::isLocType(type));
82 return nonloc::SymbolVal(SymMgr.acquire<SymIntExpr>(lhs, op, rhs, type));
83}
84
87 const SymExpr *rhs, QualType type) {
88 assert(rhs);
89 assert(!Loc::isLocType(type));
90 return nonloc::SymbolVal(SymMgr.acquire<IntSymExpr>(lhs, op, rhs, type));
91}
92
95 const SymExpr *rhs, QualType type) {
96 assert(lhs && rhs);
97 assert(!Loc::isLocType(type));
98 return nonloc::SymbolVal(SymMgr.acquire<SymSymExpr>(lhs, op, rhs, type));
99}
100
102 QualType type) {
103 assert(operand);
104 assert(!Loc::isLocType(type));
105 return nonloc::SymbolVal(SymMgr.acquire<UnarySymExpr>(operand, op, type));
106}
107
109 QualType fromTy, QualType toTy) {
110 assert(operand);
111 assert(!Loc::isLocType(toTy));
112 if (fromTy == toTy)
113 return nonloc::SymbolVal(operand);
114 return nonloc::SymbolVal(SymMgr.acquire<SymbolCast>(operand, fromTy, toTy));
115}
116
118 if (val.isUnknownOrUndef())
119 return val;
120
121 // Common case: we have an appropriately sized integer.
122 if (std::optional<nonloc::ConcreteInt> CI =
123 val.getAs<nonloc::ConcreteInt>()) {
124 const llvm::APSInt& I = CI->getValue();
125 if (I.getBitWidth() == ArrayIndexWidth && I.isSigned())
126 return val;
127 }
128
129 return evalCast(val, ArrayIndexTy, QualType{});
130}
131
133 return makeTruthVal(boolean->getValue());
134}
135
138 QualType T = region->getValueType();
139
140 if (T->isNullPtrType())
141 return makeZeroVal(T);
142
144 return UnknownVal();
145
147
148 if (Loc::isLocType(T))
150
151 return nonloc::SymbolVal(sym);
152}
153
156 const LocationContext *LCtx,
157 unsigned Count) {
158 const Expr *Ex = dyn_cast<Expr>(elem->getAs<CFGStmt>()->getStmt());
159 assert(Ex && "elem must be a CFGStmt containing an Expr");
160 QualType T = Ex->getType();
161
162 if (T->isNullPtrType())
163 return makeZeroVal(T);
164
165 // Compute the type of the result. If the expression is not an R-value, the
166 // result should be a location.
167 QualType ExType = Ex->getType();
168 if (Ex->isGLValue())
170
171 return conjureSymbolVal(SymbolTag, elem, LCtx, T, Count);
172}
173
176 const LocationContext *LCtx,
178 unsigned count) {
179 if (type->isNullPtrType())
180 return makeZeroVal(type);
181
183 return UnknownVal();
184
185 SymbolRef sym = SymMgr.conjureSymbol(elem, LCtx, type, count, symbolTag);
186
187 if (Loc::isLocType(type))
189
190 return nonloc::SymbolVal(sym);
191}
192
194 const LocationContext *LCtx,
196 unsigned visitCount) {
197 return conjureSymbolVal(/*symbolTag=*/nullptr, elem, LCtx, type, visitCount);
198}
199
201 unsigned visitCount,
202 const void *symbolTag) {
203 return conjureSymbolVal(symbolTag, call.getCFGElementRef(),
204 call.getLocationContext(), call.getResultType(),
205 visitCount);
206}
207
210 unsigned visitCount,
211 const void *symbolTag) {
212 return conjureSymbolVal(symbolTag, call.getCFGElementRef(),
213 call.getLocationContext(), type, visitCount);
214}
215
217 const LocationContext *LCtx,
219 unsigned VisitCount) {
220 assert(Loc::isLocType(type));
222 if (type->isNullPtrType()) {
223 // makeZeroVal() returns UnknownVal only in case of FP number, which
224 // is not the case.
226 }
227
228 SymbolRef sym = SymMgr.conjureSymbol(elem, LCtx, type, VisitCount);
230}
231
233 const LocationContext *LCtx,
234 unsigned VisitCount) {
235 const AllocaRegion *R =
237 return loc::MemRegionVal(R);
238}
239
241 const MemRegion *region,
242 const Expr *expr, QualType type,
243 const LocationContext *LCtx,
244 unsigned count) {
245 assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type");
246
247 SymbolRef sym = SymMgr.acquire<SymbolMetadata>(region, expr, type, LCtx,
248 count, symbolTag);
249
250 if (Loc::isLocType(type))
252
253 return nonloc::SymbolVal(sym);
254}
255
258 const TypedValueRegion *region) {
259 QualType T = region->getValueType();
260
261 if (T->isNullPtrType())
262 return makeZeroVal(T);
263
265 return UnknownVal();
266
267 SymbolRef sym = SymMgr.acquire<SymbolDerived>(parentSymbol, region);
268
269 if (Loc::isLocType(T))
271
272 return nonloc::SymbolVal(sym);
273}
274
276 assert(!ND || (isa<CXXMethodDecl, FieldDecl, IndirectFieldDecl>(ND)));
277
278 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) {
279 // Sema treats pointers to static member functions as have function pointer
280 // type, so return a function pointer for the method.
281 // We don't need to play a similar trick for static member fields
282 // because these are represented as plain VarDecls and not FieldDecls
283 // in the AST.
284 if (!MD->isImplicitObjectMemberFunction())
285 return getFunctionPointer(MD);
286 }
287
288 return nonloc::PointerToMember(ND);
289}
290
293}
294
296 CanQualType locTy,
297 const LocationContext *locContext,
298 unsigned blockCount) {
299 const BlockCodeRegion *BC =
300 MemMgr.getBlockCodeRegion(block, locTy, locContext->getAnalysisDeclContext());
301 const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext,
302 blockCount);
303 return loc::MemRegionVal(BD);
304}
305
306std::optional<loc::MemRegionVal>
308 if (auto OptR = StateMgr.getStoreManager().castRegion(R, Ty))
309 return loc::MemRegionVal(*OptR);
310 return std::nullopt;
311}
312
313/// Return a memory region for the 'this' object reference.
315 const StackFrameContext *SFC) {
316 return loc::MemRegionVal(
317 getRegionManager().getCXXThisRegion(D->getThisType(), SFC));
318}
319
320/// Return a memory region for the 'this' object reference.
322 const StackFrameContext *SFC) {
323 CanQualType PT =
324 getContext().getPointerType(getContext().getCanonicalTagType(D));
325 return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC));
326}
327
328std::optional<SVal> SValBuilder::getConstantVal(const Expr *E) {
329 E = E->IgnoreParens();
330
331 switch (E->getStmtClass()) {
332 // Handle expressions that we treat differently from the AST's constant
333 // evaluator.
334 case Stmt::AddrLabelExprClass:
335 return makeLoc(cast<AddrLabelExpr>(E));
336
337 case Stmt::CXXScalarValueInitExprClass:
338 case Stmt::ImplicitValueInitExprClass:
339 return makeZeroVal(E->getType());
340
341 case Stmt::ObjCStringLiteralClass: {
342 const auto *SL = cast<ObjCStringLiteral>(E);
343 return makeLoc(getRegionManager().getObjCStringRegion(SL));
344 }
345
346 case Stmt::StringLiteralClass: {
347 const auto *SL = cast<StringLiteral>(E);
348 return makeLoc(getRegionManager().getStringRegion(SL));
349 }
350
351 case Stmt::PredefinedExprClass: {
352 const auto *PE = cast<PredefinedExpr>(E);
353 assert(PE->getFunctionName() &&
354 "Since we analyze only instantiated functions, PredefinedExpr "
355 "should have a function name.");
356 return makeLoc(getRegionManager().getStringRegion(PE->getFunctionName()));
357 }
358
359 // Fast-path some expressions to avoid the overhead of going through the AST's
360 // constant evaluator
361 case Stmt::CharacterLiteralClass: {
362 const auto *C = cast<CharacterLiteral>(E);
363 return makeIntVal(C->getValue(), C->getType());
364 }
365
366 case Stmt::CXXBoolLiteralExprClass:
367 return makeBoolVal(cast<CXXBoolLiteralExpr>(E));
368
369 case Stmt::TypeTraitExprClass: {
370 const auto *TE = cast<TypeTraitExpr>(E);
371 if (TE->isStoredAsBoolean())
372 return makeTruthVal(TE->getBoolValue(), TE->getType());
373 assert(TE->getAPValue().isInt() && "APValue type not supported");
374 return makeIntVal(TE->getAPValue().getInt());
375 }
376
377 case Stmt::IntegerLiteralClass:
378 return makeIntVal(cast<IntegerLiteral>(E));
379
380 case Stmt::ObjCBoolLiteralExprClass:
381 return makeBoolVal(cast<ObjCBoolLiteralExpr>(E));
382
383 case Stmt::CXXNullPtrLiteralExprClass:
384 return makeNullWithType(E->getType());
385
386 case Stmt::CStyleCastExprClass:
387 case Stmt::CXXFunctionalCastExprClass:
388 case Stmt::CXXConstCastExprClass:
389 case Stmt::CXXReinterpretCastExprClass:
390 case Stmt::CXXStaticCastExprClass:
391 case Stmt::ImplicitCastExprClass: {
392 const auto *CE = cast<CastExpr>(E);
393 switch (CE->getCastKind()) {
394 default:
395 break;
396 case CK_ArrayToPointerDecay:
397 case CK_IntegralToPointer:
398 case CK_NoOp:
399 case CK_BitCast: {
400 const Expr *SE = CE->getSubExpr();
401 std::optional<SVal> Val = getConstantVal(SE);
402 if (!Val)
403 return std::nullopt;
404 return evalCast(*Val, CE->getType(), SE->getType());
405 }
406 }
407 [[fallthrough]];
408 }
409
410 // If we don't have a special case, fall back to the AST's constant evaluator.
411 default: {
412 // Don't try to come up with a value for materialized temporaries.
413 if (E->isGLValue())
414 return std::nullopt;
415
416 ASTContext &Ctx = getContext();
418 if (E->EvaluateAsInt(Result, Ctx))
419 return makeIntVal(Result.Val.getInt());
420
421 if (Loc::isLocType(E->getType()))
423 return makeNullWithType(E->getType());
424
425 return std::nullopt;
426 }
427 }
428}
429
431 NonLoc LHS, NonLoc RHS,
432 QualType ResultTy) {
433 SymbolRef symLHS = LHS.getAsSymbol();
434 SymbolRef symRHS = RHS.getAsSymbol();
435
436 // TODO: When the Max Complexity is reached, we should conjure a symbol
437 // instead of generating an Unknown value and propagate the taint info to it.
438 const unsigned MaxComp = AnOpts.MaxSymbolComplexity;
439
440 if (symLHS && symRHS &&
441 (symLHS->computeComplexity() + symRHS->computeComplexity()) < MaxComp)
442 return makeNonLoc(symLHS, Op, symRHS, ResultTy);
443
444 if (symLHS && symLHS->computeComplexity() < MaxComp)
445 if (std::optional<nonloc::ConcreteInt> rInt =
447 return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
448
449 if (symRHS && symRHS->computeComplexity() < MaxComp)
450 if (std::optional<nonloc::ConcreteInt> lInt =
452 return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
453
454 return UnknownVal();
455}
456
458 switch (X.getKind()) {
459 case nonloc::ConcreteIntKind:
460 return makeIntVal(-X.castAs<nonloc::ConcreteInt>().getValue());
461 case nonloc::SymbolValKind:
462 return makeNonLoc(X.castAs<nonloc::SymbolVal>().getSymbol(), UO_Minus,
463 X.getType(Context));
464 default:
465 return UnknownVal();
466 }
467}
468
470 switch (X.getKind()) {
471 case nonloc::ConcreteIntKind:
472 return makeIntVal(~X.castAs<nonloc::ConcreteInt>().getValue());
473 case nonloc::SymbolValKind:
474 return makeNonLoc(X.castAs<nonloc::SymbolVal>().getSymbol(), UO_Not,
475 X.getType(Context));
476 default:
477 return UnknownVal();
478 }
479}
480
482 SVal operand, QualType type) {
483 auto OpN = operand.getAs<NonLoc>();
484 if (!OpN)
485 return UnknownVal();
486
487 if (opc == UO_Minus)
488 return evalMinus(*OpN);
489 if (opc == UO_Not)
490 return evalComplement(*OpN);
491 llvm_unreachable("Unexpected unary operator");
492}
493
495 SVal lhs, SVal rhs, QualType type) {
496 if (lhs.isUndef() || rhs.isUndef())
497 return UndefinedVal();
498
499 if (lhs.isUnknown() || rhs.isUnknown())
500 return UnknownVal();
501
502 if (isa<nonloc::LazyCompoundVal>(lhs) || isa<nonloc::LazyCompoundVal>(rhs)) {
503 return UnknownVal();
504 }
505
506 if (op == BinaryOperatorKind::BO_Cmp) {
507 // We can't reason about C++20 spaceship operator yet.
508 //
509 // FIXME: Support C++20 spaceship operator.
510 // The main problem here is that the result is not integer.
511 return UnknownVal();
512 }
513
514 if (std::optional<Loc> LV = lhs.getAs<Loc>()) {
515 if (std::optional<Loc> RV = rhs.getAs<Loc>())
516 return evalBinOpLL(state, op, *LV, *RV, type);
517
518 return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type);
519 }
520
521 if (const std::optional<Loc> RV = rhs.getAs<Loc>()) {
522 const auto IsCommutative = [](BinaryOperatorKind Op) {
523 return Op == BO_Mul || Op == BO_Add || Op == BO_And || Op == BO_Xor ||
524 Op == BO_Or;
525 };
526
527 if (IsCommutative(op)) {
528 // Swap operands.
529 return evalBinOpLN(state, op, *RV, lhs.castAs<NonLoc>(), type);
530 }
531
532 // If the right operand is a concrete int location then we have nothing
533 // better but to treat it as a simple nonloc.
534 if (auto RV = rhs.getAs<loc::ConcreteInt>()) {
535 const nonloc::ConcreteInt RhsAsLoc = makeIntVal(RV->getValue());
536 return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), RhsAsLoc, type);
537 }
538 }
539
540 return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), rhs.castAs<NonLoc>(),
541 type);
542}
543
545 SVal rhs) {
546 return state->isNonNull(evalEQ(state, lhs, rhs));
547}
548
550 return evalBinOp(state, BO_EQ, lhs, rhs, getConditionType());
551}
552
556 return evalEQ(state, static_cast<SVal>(lhs), static_cast<SVal>(rhs))
558}
559
560/// Recursively check if the pointer types are equal modulo const, volatile,
561/// and restrict qualifiers. Also, assume that all types are similar to 'void'.
562/// Assumes the input types are canonical.
563static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy,
564 QualType FromTy) {
565 while (Context.UnwrapSimilarTypes(ToTy, FromTy)) {
566 Qualifiers Quals1, Quals2;
567 ToTy = Context.getUnqualifiedArrayType(ToTy, Quals1);
568 FromTy = Context.getUnqualifiedArrayType(FromTy, Quals2);
569
570 // Make sure that non-cvr-qualifiers the other qualifiers (e.g., address
571 // spaces) are identical.
572 Quals1.removeCVRQualifiers();
573 Quals2.removeCVRQualifiers();
574 if (Quals1 != Quals2)
575 return false;
576 }
577
578 // If we are casting to void, the 'From' value can be used to represent the
579 // 'To' value.
580 //
581 // FIXME: Doing this after unwrapping the types doesn't make any sense. A
582 // cast from 'int**' to 'void**' is not special in the way that a cast from
583 // 'int*' to 'void*' is.
584 if (ToTy->isVoidType())
585 return true;
586
587 if (ToTy != FromTy)
588 return false;
589
590 return true;
591}
592
593// Handles casts of type CK_IntegralCast.
594// At the moment, this function will redirect to evalCast, except when the range
595// of the original value is known to be greater than the max of the target type.
597 QualType castTy, QualType originalTy) {
598 // No truncations if target type is big enough.
599 if (getContext().getTypeSize(castTy) >= getContext().getTypeSize(originalTy))
600 return evalCast(val, castTy, originalTy);
601
602 auto AsNonLoc = val.getAs<NonLoc>();
603 SymbolRef AsSymbol = val.getAsSymbol();
604 if (!AsSymbol || !AsNonLoc) // Let evalCast handle non symbolic expressions.
605 return evalCast(val, castTy, originalTy);
606
607 // Find the maximum value of the target type.
608 APSIntType ToType(getContext().getTypeSize(castTy),
609 castTy->isUnsignedIntegerType());
610 llvm::APSInt ToTypeMax = ToType.getMaxValue();
611
612 NonLoc ToTypeMaxVal = makeIntVal(ToTypeMax);
613
614 // Check the range of the symbol being casted against the maximum value of the
615 // target type.
616 QualType CmpTy = getConditionType();
617 NonLoc CompVal = evalBinOpNN(state, BO_LE, *AsNonLoc, ToTypeMaxVal, CmpTy)
618 .castAs<NonLoc>();
619 ProgramStateRef IsNotTruncated, IsTruncated;
620 std::tie(IsNotTruncated, IsTruncated) = state->assume(CompVal);
621 if (!IsNotTruncated && IsTruncated) {
622 // Symbol is truncated so we evaluate it as a cast.
623 return makeNonLoc(AsSymbol, originalTy, castTy);
624 }
625 return evalCast(val, castTy, originalTy);
626}
627
628//===----------------------------------------------------------------------===//
629// Cast method.
630// `evalCast` and its helper `EvalCastVisitor`
631//===----------------------------------------------------------------------===//
632
633namespace {
634class EvalCastVisitor : public SValVisitor<EvalCastVisitor, SVal> {
635private:
636 SValBuilder &VB;
637 ASTContext &Context;
638 QualType CastTy, OriginalTy;
639
640public:
641 EvalCastVisitor(SValBuilder &VB, QualType CastTy, QualType OriginalTy)
642 : VB(VB), Context(VB.getContext()), CastTy(CastTy),
643 OriginalTy(OriginalTy) {}
644
645 SVal Visit(SVal V) {
646 if (CastTy.isNull())
647 return V;
648
649 CastTy = Context.getCanonicalType(CastTy);
650
651 const bool IsUnknownOriginalType = OriginalTy.isNull();
652 if (!IsUnknownOriginalType) {
653 OriginalTy = Context.getCanonicalType(OriginalTy);
654
655 if (CastTy == OriginalTy)
656 return V;
657
658 // FIXME: Move this check to the most appropriate
659 // evalCastKind/evalCastSubKind function. For const casts, casts to void,
660 // just propagate the value.
661 if (!CastTy->isVariableArrayType() && !OriginalTy->isVariableArrayType())
662 if (shouldBeModeledWithNoOp(Context, Context.getPointerType(CastTy),
663 Context.getPointerType(OriginalTy)))
664 return V;
665 }
666 return SValVisitor::Visit(V);
667 }
668 SVal VisitUndefinedVal(UndefinedVal V) { return V; }
669 SVal VisitUnknownVal(UnknownVal V) { return V; }
670 SVal VisitConcreteInt(loc::ConcreteInt V) {
671 // Pointer to bool.
672 if (CastTy->isBooleanType())
673 return VB.makeTruthVal(V.getValue()->getBoolValue(), CastTy);
674
675 // Pointer to integer.
676 if (CastTy->isIntegralOrEnumerationType()) {
677 llvm::APSInt Value = V.getValue();
679 return VB.makeIntVal(Value);
680 }
681
682 // Pointer to any pointer.
683 if (Loc::isLocType(CastTy)) {
684 llvm::APSInt Value = V.getValue();
686 return loc::ConcreteInt(VB.getBasicValueFactory().getValue(Value));
687 }
688
689 // Pointer to whatever else.
690 return UnknownVal();
691 }
692 SVal VisitGotoLabel(loc::GotoLabel V) {
693 // Pointer to bool.
694 if (CastTy->isBooleanType())
695 // Labels are always true.
696 return VB.makeTruthVal(true, CastTy);
697
698 // Pointer to integer.
699 if (CastTy->isIntegralOrEnumerationType()) {
700 const unsigned BitWidth = Context.getIntWidth(CastTy);
701 return VB.makeLocAsInteger(V, BitWidth);
702 }
703
704 const bool IsUnknownOriginalType = OriginalTy.isNull();
705 if (!IsUnknownOriginalType) {
706 // Array to pointer.
707 if (isa<ArrayType>(OriginalTy))
708 if (CastTy->isPointerType() || CastTy->isReferenceType())
709 return UnknownVal();
710 }
711
712 // Pointer to any pointer.
713 if (Loc::isLocType(CastTy))
714 return V;
715
716 // Pointer to whatever else.
717 return UnknownVal();
718 }
719 SVal VisitMemRegionVal(loc::MemRegionVal V) {
720 // Pointer to bool.
721 if (CastTy->isBooleanType()) {
722 const MemRegion *R = V.getRegion();
723 if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
724 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
725 if (FD->isWeak())
726 // FIXME: Currently we are using an extent symbol here,
727 // because there are no generic region address metadata
728 // symbols to use, only content metadata.
729 return nonloc::SymbolVal(
731
732 if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
733 SymbolRef Sym = SymR->getSymbol();
734 QualType Ty = Sym->getType();
735 // This change is needed for architectures with varying
736 // pointer widths. See the amdgcn opencl reproducer with
737 // this change as an example: solver-sym-simplification-ptr-bool.cl
738 if (!Ty->isReferenceType())
739 return VB.makeNonLoc(
740 Sym, BO_NE, VB.getBasicValueFactory().getZeroWithTypeSize(Ty),
741 CastTy);
742 }
743 // Non-symbolic memory regions are always true.
744 return VB.makeTruthVal(true, CastTy);
745 }
746
747 const bool IsUnknownOriginalType = OriginalTy.isNull();
748 // Try to cast to array
749 const auto *ArrayTy =
750 IsUnknownOriginalType
751 ? nullptr
752 : dyn_cast<ArrayType>(OriginalTy.getCanonicalType());
753
754 // Pointer to integer.
755 if (CastTy->isIntegralOrEnumerationType()) {
756 SVal Val = V;
757 // Array to integer.
758 if (ArrayTy) {
759 // We will always decay to a pointer.
760 QualType ElemTy = ArrayTy->getElementType();
761 Val = VB.getStateManager().ArrayToPointer(V, ElemTy);
762 // FIXME: Keep these here for now in case we decide soon that we
763 // need the original decayed type.
764 // QualType elemTy = cast<ArrayType>(originalTy)->getElementType();
765 // QualType pointerTy = C.getPointerType(elemTy);
766 }
767 const unsigned BitWidth = Context.getIntWidth(CastTy);
768 return VB.makeLocAsInteger(Val.castAs<Loc>(), BitWidth);
769 }
770
771 // Pointer to pointer.
772 if (Loc::isLocType(CastTy)) {
773
774 if (IsUnknownOriginalType) {
775 // When retrieving symbolic pointer and expecting a non-void pointer,
776 // wrap them into element regions of the expected type if necessary.
777 // It is necessary to make sure that the retrieved value makes sense,
778 // because there's no other cast in the AST that would tell us to cast
779 // it to the correct pointer type. We might need to do that for non-void
780 // pointers as well.
781 // FIXME: We really need a single good function to perform casts for us
782 // correctly every time we need it.
783 const MemRegion *R = V.getRegion();
784 if (CastTy->isPointerType() && !CastTy->isVoidPointerType()) {
785 if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
786 QualType SRTy = SR->getSymbol()->getType();
787
788 auto HasSameUnqualifiedPointeeType = [](QualType ty1,
789 QualType ty2) {
790 return ty1->getPointeeType().getCanonicalType().getTypePtr() ==
792 };
793 if (!HasSameUnqualifiedPointeeType(SRTy, CastTy)) {
794 if (auto OptMemRegV = VB.getCastedMemRegionVal(SR, CastTy))
795 return *OptMemRegV;
796 }
797 }
798 }
799 // Next fixes pointer dereference using type different from its initial
800 // one. See PR37503 and PR49007 for details.
801 if (const auto *ER = dyn_cast<ElementRegion>(R)) {
802 if (auto OptMemRegV = VB.getCastedMemRegionVal(ER, CastTy))
803 return *OptMemRegV;
804 }
805
806 return V;
807 }
808
809 if (OriginalTy->isIntegralOrEnumerationType() ||
810 OriginalTy->isBlockPointerType() ||
811 OriginalTy->isFunctionPointerType())
812 return V;
813
814 // Array to pointer.
815 if (ArrayTy) {
816 // Are we casting from an array to a pointer? If so just pass on
817 // the decayed value.
818 if (CastTy->isPointerType() || CastTy->isReferenceType()) {
819 // We will always decay to a pointer.
820 QualType ElemTy = ArrayTy->getElementType();
821 return VB.getStateManager().ArrayToPointer(V, ElemTy);
822 }
823 // Are we casting from an array to an integer? If so, cast the decayed
824 // pointer value to an integer.
825 assert(CastTy->isIntegralOrEnumerationType());
826 }
827
828 // Other pointer to pointer.
829 assert(Loc::isLocType(OriginalTy) || OriginalTy->isFunctionType() ||
830 CastTy->isReferenceType());
831
832 // We get a symbolic function pointer for a dereference of a function
833 // pointer, but it is of function type. Example:
834
835 // struct FPRec {
836 // void (*my_func)(int * x);
837 // };
838 //
839 // int bar(int x);
840 //
841 // int f1_a(struct FPRec* foo) {
842 // int x;
843 // (*foo->my_func)(&x);
844 // return bar(x)+1; // no-warning
845 // }
846
847 // Get the result of casting a region to a different type.
848 const MemRegion *R = V.getRegion();
849 if (auto OptMemRegV = VB.getCastedMemRegionVal(R, CastTy))
850 return *OptMemRegV;
851 }
852
853 // Pointer to whatever else.
854 // FIXME: There can be gross cases where one casts the result of a
855 // function (that returns a pointer) to some other value that happens to
856 // fit within that pointer value. We currently have no good way to model
857 // such operations. When this happens, the underlying operation is that
858 // the caller is reasoning about bits. Conceptually we are layering a
859 // "view" of a location on top of those bits. Perhaps we need to be more
860 // lazy about mutual possible views, even on an SVal? This may be
861 // necessary for bit-level reasoning as well.
862 return UnknownVal();
863 }
864 SVal VisitCompoundVal(nonloc::CompoundVal V) {
865 // Compound to whatever.
866 return UnknownVal();
867 }
868 SVal VisitConcreteInt(nonloc::ConcreteInt V) {
869 auto CastedValue = [V, this]() {
870 llvm::APSInt Value = V.getValue();
872 return Value;
873 };
874
875 // Integer to bool.
876 if (CastTy->isBooleanType())
877 return VB.makeTruthVal(V.getValue()->getBoolValue(), CastTy);
878
879 // Integer to pointer.
880 if (CastTy->isIntegralOrEnumerationType())
881 return VB.makeIntVal(CastedValue());
882
883 // Integer to pointer.
884 if (Loc::isLocType(CastTy))
885 return VB.makeIntLocVal(CastedValue());
886
887 // Pointer to whatever else.
888 return UnknownVal();
889 }
890 SVal VisitLazyCompoundVal(nonloc::LazyCompoundVal V) {
891 // LazyCompound to whatever.
892 return UnknownVal();
893 }
894 SVal VisitLocAsInteger(nonloc::LocAsInteger V) {
895 Loc L = V.getLoc();
896
897 // Pointer as integer to bool.
898 if (CastTy->isBooleanType())
899 // Pass to Loc function.
900 return Visit(L);
901
902 const bool IsUnknownOriginalType = OriginalTy.isNull();
903 // Pointer as integer to pointer.
904 if (!IsUnknownOriginalType && Loc::isLocType(CastTy) &&
905 OriginalTy->isIntegralOrEnumerationType()) {
906 if (const MemRegion *R = L.getAsRegion())
907 if (auto OptMemRegV = VB.getCastedMemRegionVal(R, CastTy))
908 return *OptMemRegV;
909 return L;
910 }
911
912 // Pointer as integer with region to integer/pointer.
913 const MemRegion *R = L.getAsRegion();
914 if (!IsUnknownOriginalType && R) {
915 if (CastTy->isIntegralOrEnumerationType())
916 return VisitMemRegionVal(loc::MemRegionVal(R));
917
918 if (Loc::isLocType(CastTy)) {
919 assert(Loc::isLocType(OriginalTy) || OriginalTy->isFunctionType() ||
920 CastTy->isReferenceType());
921 // Delegate to store manager to get the result of casting a region to a
922 // different type. If the MemRegion* returned is NULL, this expression
923 // Evaluates to UnknownVal.
924 if (auto OptMemRegV = VB.getCastedMemRegionVal(R, CastTy))
925 return *OptMemRegV;
926 }
927 } else {
928 if (Loc::isLocType(CastTy)) {
929 if (IsUnknownOriginalType)
930 return VisitMemRegionVal(loc::MemRegionVal(R));
931 return L;
932 }
933
934 SymbolRef SE = nullptr;
935 if (R) {
936 if (const SymbolicRegion *SR =
937 dyn_cast<SymbolicRegion>(R->StripCasts())) {
938 SE = SR->getSymbol();
939 }
940 }
941
942 if (!CastTy->isFloatingType() || !SE || SE->getType()->isFloatingType()) {
943 // FIXME: Correctly support promotions/truncations.
944 const unsigned CastSize = Context.getIntWidth(CastTy);
945 if (CastSize == V.getNumBits())
946 return V;
947
948 return VB.makeLocAsInteger(L, CastSize);
949 }
950 }
951
952 // Pointer as integer to whatever else.
953 return UnknownVal();
954 }
955 SVal VisitSymbolVal(nonloc::SymbolVal V) {
956 SymbolRef SE = V.getSymbol();
957
958 const bool IsUnknownOriginalType = OriginalTy.isNull();
959 // Symbol to bool.
960 if (!IsUnknownOriginalType && CastTy->isBooleanType()) {
961 // Non-float to bool.
962 if (Loc::isLocType(OriginalTy) ||
963 OriginalTy->isIntegralOrEnumerationType() ||
964 OriginalTy->isMemberPointerType()) {
966 return VB.makeNonLoc(SE, BO_NE, BVF.getValue(0, SE->getType()), CastTy);
967 }
968 } else {
969 // Symbol to integer, float.
970 QualType T = Context.getCanonicalType(SE->getType());
971
972 // Produce SymbolCast if CastTy and T are different integers.
973 // NOTE: In the end the type of SymbolCast shall be equal to CastTy.
980 // If appropriate option is disabled, ignore the cast.
981 // NOTE: ShouldSupportSymbolicIntegerCasts is `false` by default.
982 if (!Opts.ShouldSupportSymbolicIntegerCasts)
983 return V;
984 return simplifySymbolCast(V, CastTy);
985 }
986 if (!Loc::isLocType(CastTy))
987 if (!IsUnknownOriginalType || !CastTy->isFloatingType() ||
988 T->isFloatingType())
989 return VB.makeNonLoc(SE, T, CastTy);
990 }
991
992 // FIXME: We should be able to cast NonLoc -> Loc
993 // (when Loc::isLocType(CastTy) is true)
994 // But it's hard to do as SymbolicRegions can't refer to SymbolCasts holding
995 // generic SymExprs. Check the commit message for the details.
996
997 // Symbol to pointer and whatever else.
998 return UnknownVal();
999 }
1000 SVal VisitPointerToMember(nonloc::PointerToMember V) {
1001 // Member pointer to whatever.
1002 return V;
1003 }
1004
1005 /// Reduce cast expression by removing redundant intermediate casts.
1006 /// E.g.
1007 /// - (char)(short)(int x) -> (char)(int x)
1008 /// - (int)(int x) -> int x
1009 ///
1010 /// \param V -- SymbolVal, which pressumably contains SymbolCast or any symbol
1011 /// that is applicable for cast operation.
1012 /// \param CastTy -- QualType, which `V` shall be cast to.
1013 /// \return SVal with simplified cast expression.
1014 /// \note: Currently only support integral casts.
1015 nonloc::SymbolVal simplifySymbolCast(nonloc::SymbolVal V, QualType CastTy) {
1016 // We use seven conditions to recognize a simplification case.
1017 // For the clarity let `CastTy` be `C`, SE->getType() - `T`, root type -
1018 // `R`, prefix `u` for unsigned, `s` for signed, no prefix - any sign: E.g.
1019 // (char)(short)(uint x)
1020 // ( sC )( sT )( uR x)
1021 //
1022 // C === R (the same type)
1023 // (char)(char x) -> (char x)
1024 // (long)(long x) -> (long x)
1025 // Note: Comparisons operators below are for bit width.
1026 // C == T
1027 // (short)(short)(int x) -> (short)(int x)
1028 // (int)(long)(char x) -> (int)(char x) (sizeof(long) == sizeof(int))
1029 // (long)(ullong)(char x) -> (long)(char x) (sizeof(long) ==
1030 // sizeof(ullong))
1031 // C < T
1032 // (short)(int)(char x) -> (short)(char x)
1033 // (char)(int)(short x) -> (char)(short x)
1034 // (short)(int)(short x) -> (short x)
1035 // C > T > uR
1036 // (int)(short)(uchar x) -> (int)(uchar x)
1037 // (uint)(short)(uchar x) -> (uint)(uchar x)
1038 // (int)(ushort)(uchar x) -> (int)(uchar x)
1039 // C > sT > sR
1040 // (int)(short)(char x) -> (int)(char x)
1041 // (uint)(short)(char x) -> (uint)(char x)
1042 // C > sT == sR
1043 // (int)(char)(char x) -> (int)(char x)
1044 // (uint)(short)(short x) -> (uint)(short x)
1045 // C > uT == uR
1046 // (int)(uchar)(uchar x) -> (int)(uchar x)
1047 // (uint)(ushort)(ushort x) -> (uint)(ushort x)
1048 // (llong)(ulong)(uint x) -> (llong)(uint x) (sizeof(ulong) ==
1049 // sizeof(uint))
1050
1051 SymbolRef SE = V.getSymbol();
1052 QualType T = Context.getCanonicalType(SE->getType());
1053
1054 if (T == CastTy)
1055 return V;
1056
1057 if (!isa<SymbolCast>(SE))
1058 return VB.makeNonLoc(SE, T, CastTy);
1059
1060 SymbolRef RootSym = cast<SymbolCast>(SE)->getOperand();
1061 QualType RT = RootSym->getType().getCanonicalType();
1062
1063 // FIXME support simplification from non-integers.
1064 if (!RT->isIntegralOrEnumerationType())
1065 return VB.makeNonLoc(SE, T, CastTy);
1066
1068 APSIntType CTy = BVF.getAPSIntType(CastTy);
1069 APSIntType TTy = BVF.getAPSIntType(T);
1070
1071 const auto WC = CTy.getBitWidth();
1072 const auto WT = TTy.getBitWidth();
1073
1074 if (WC <= WT) {
1075 const bool isSameType = (RT == CastTy);
1076 if (isSameType)
1077 return nonloc::SymbolVal(RootSym);
1078 return VB.makeNonLoc(RootSym, RT, CastTy);
1079 }
1080
1081 APSIntType RTy = BVF.getAPSIntType(RT);
1082 const auto WR = RTy.getBitWidth();
1083 const bool UT = TTy.isUnsigned();
1084 const bool UR = RTy.isUnsigned();
1085
1086 if (((WT > WR) && (UR || !UT)) || ((WT == WR) && (UT == UR)))
1087 return VB.makeNonLoc(RootSym, RT, CastTy);
1088
1089 return VB.makeNonLoc(SE, T, CastTy);
1090 }
1091};
1092} // end anonymous namespace
1093
1094/// Cast a given SVal to another SVal using given QualType's.
1095/// \param V -- SVal that should be casted.
1096/// \param CastTy -- QualType that V should be casted according to.
1097/// \param OriginalTy -- QualType which is associated to V. It provides
1098/// additional information about what type the cast performs from.
1099/// \returns the most appropriate casted SVal.
1100/// Note: Many cases don't use an exact OriginalTy. It can be extracted
1101/// from SVal or the cast can performs unconditionaly. Always pass OriginalTy!
1102/// It can be crucial in certain cases and generates different results.
1103/// FIXME: If `OriginalTy.isNull()` is true, then cast performs based on CastTy
1104/// only. This behavior is uncertain and should be improved.
1106 EvalCastVisitor TRV{*this, CastTy, OriginalTy};
1107 return TRV.Visit(V);
1108}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
#define X(type, name)
Definition: Value.h:145
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::DenseMap< const CFGBlock *, unsigned > VisitCount
Definition: Logger.cpp:30
static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy, QualType FromTy)
Recursively check if the pointer types are equal modulo const, volatile, and restrict qualifiers.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
ASTContext & getASTContext() const
Stores options for the analyzer from the command line.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4630
const Stmt * getStmt() const
Definition: CFG.h:139
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:723
bool getValue() const
Definition: ExprCXX.h:740
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
This represents one expression.
Definition: Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isGLValue() const
Definition: Expr.h:287
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:837
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:4001
QualType getType() const
Definition: Expr.h:144
Represents a function declaration or definition.
Definition: Decl.h:1999
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
This represents a decl that may have a name.
Definition: Decl.h:273
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
QualType getCanonicalType() const
Definition: TypeBase.h:8395
The collection of all-type qualifiers we support.
Definition: TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition: TypeBase.h:495
It represents a stack frame of the call stack (based on CallEvent).
StmtClass getStmtClass() const
Definition: Stmt.h:1483
bool isBlockPointerType() const
Definition: TypeBase.h:8600
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2119
bool isVoidPointerType() const
Definition: Type.cpp:712
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isPointerType() const
Definition: TypeBase.h:8580
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isVariableArrayType() const
Definition: TypeBase.h:8691
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: TypeBase.h:9054
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isFloatingType() const
Definition: Type.cpp:2308
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2257
bool isNullPtrType() const
Definition: TypeBase.h:8973
A safe wrapper around APSInt objects allocated and owned by BasicValueFactory.
Definition: APSIntPtr.h:19
A record of the "type" of an APSInt, used for conversions.
Definition: APSIntType.h:19
bool isUnsigned() const
Definition: APSIntType.h:31
uint32_t getBitWidth() const
Definition: APSIntType.h:30
llvm::APSInt getMaxValue() const LLVM_READONLY
Returns the maximum value for this type.
Definition: APSIntType.h:65
void apply(llvm::APSInt &Value) const
Convert a given APSInt, in place, to match this type.
Definition: APSIntType.h:37
AllocaRegion - A region that represents an untyped blob of bytes created by a call to 'alloca'.
Definition: MemRegion.h:506
AnalyzerOptions & getAnalyzerOptions() override
APSIntPtr getZeroWithTypeSize(QualType T)
APSIntType getAPSIntType(QualType T) const
Returns the type of the APSInt used to store values of the given QualType.
llvm::ImmutableList< SVal > getEmptySValList()
Template implementation for all binary symbolic expressions.
BlockCodeRegion - A region that represents code texts of blocks (closures).
Definition: MemRegion.h:659
BlockDataRegion - A region that represents a block instance.
Definition: MemRegion.h:706
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
QualType getResultType() const
Returns the result type, adjusted for references.
Definition: CallEvent.cpp:70
const LocationContext * getLocationContext() const
The context in which the call is being evaluated.
Definition: CallEvent.h:238
const CFGBlock::ConstCFGElementRef & getCFGElementRef() const
Definition: CallEvent.h:240
AnalysisManager & getAnalysisManager()
Definition: ExprEngine.h:198
FunctionCodeRegion - A region that represents code texts of function.
Definition: MemRegion.h:612
static bool isLocType(QualType T)
Definition: SVals.h:262
const BlockCodeRegion * getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy, AnalysisDeclContext *AC)
Definition: MemRegion.cpp:1254
const AllocaRegion * getAllocaRegion(const Expr *Ex, unsigned Cnt, const LocationContext *LC)
getAllocaRegion - Retrieve a region associated with a call to alloca().
Definition: MemRegion.cpp:1378
const SymbolicRegion * getSymbolicHeapRegion(SymbolRef sym)
Return a unique symbolic region belonging to heap memory space.
Definition: MemRegion.cpp:1267
const SymbolicRegion * getSymbolicRegion(SymbolRef Sym, const MemSpaceRegion *MemSpace=nullptr)
Retrieve or create a "symbolic" memory region.
Definition: MemRegion.cpp:1260
const FunctionCodeRegion * getFunctionCodeRegion(const NamedDecl *FD)
Definition: MemRegion.cpp:1248
const BlockDataRegion * getBlockDataRegion(const BlockCodeRegion *bc, const LocationContext *lc, unsigned blockCount)
getBlockDataRegion - Get the memory region associated with an instance of a block.
Definition: MemRegion.cpp:1169
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:98
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * StripCasts(bool StripBaseAndDerivedCasts=true) const
Definition: MemRegion.cpp:1457
const SymbolicRegion * getSymbolicBase() const
If this is a symbolic region, returns the region.
Definition: MemRegion.cpp:1480
SVal ArrayToPointer(Loc Array, QualType ElementTy)
Definition: ProgramState.h:589
DefinedSVal getConjuredHeapSymbolVal(ConstCFGElementRef elem, const LocationContext *LCtx, QualType type, unsigned Count)
Conjure a symbol representing heap allocated memory region.
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
Definition: SValBuilder.cpp:62
DefinedSVal getMemberPointer(const NamedDecl *ND)
SVal evalMinus(NonLoc val)
SVal evalComplement(NonLoc val)
BasicValueFactory & getBasicValueFactory()
Definition: SValBuilder.h:162
NonLoc makeCompoundVal(QualType type, llvm::ImmutableList< SVal > vals)
Definition: SValBuilder.h:249
SymbolManager SymMgr
Manages the creation of symbols.
Definition: SValBuilder.h:64
virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op, Loc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with a memory location and non-location opera...
DefinedSVal getMetadataSymbolVal(const void *symbolTag, const MemRegion *region, const Expr *expr, QualType type, const LocationContext *LCtx, unsigned count)
MemRegionManager & getRegionManager()
Definition: SValBuilder.h:168
ProgramStateManager & getStateManager()
Definition: SValBuilder.h:152
SVal makeSymExprValNN(BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)
Constructs a symbolic expression for two non-location values.
virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op, Loc lhs, Loc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two memory location operands.
const unsigned ArrayIndexWidth
The width of the scalar type used for array indices.
Definition: SValBuilder.h:77
DefinedSVal getBlockPointer(const BlockDecl *block, CanQualType locTy, const LocationContext *locContext, unsigned blockCount)
DefinedSVal getFunctionPointer(const FunctionDecl *func)
const QualType ArrayIndexTy
The scalar type to use for array indices.
Definition: SValBuilder.h:74
ASTContext & getContext()
Definition: SValBuilder.h:149
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:277
SVal convertToArrayIndex(SVal val)
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:363
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two non- location operands.
SVal evalCast(SVal V, QualType CastTy, QualType OriginalTy)
Cast a given SVal to another SVal using given QualType's.
BasicValueFactory BasicVals
Manager of APSInt values.
Definition: SValBuilder.h:61
ConditionTruthVal areEqual(ProgramStateRef state, SVal lhs, SVal rhs)
QualType getConditionType() const
Definition: SValBuilder.h:154
MemRegionManager MemMgr
Manages the creation of memory regions.
Definition: SValBuilder.h:67
SVal evalEQ(ProgramStateRef state, SVal lhs, SVal rhs)
SVal evalUnaryOp(ProgramStateRef state, UnaryOperator::Opcode opc, SVal operand, QualType type)
DefinedOrUnknownSVal getDerivedRegionValueSymbolVal(SymbolRef parentSymbol, const TypedValueRegion *region)
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the 'this' object reference.
nonloc::ConcreteInt makeTruthVal(bool b, QualType type)
Definition: SValBuilder.h:336
loc::ConcreteInt makeNullWithType(QualType type)
Create NULL pointer, with proper pointer bit-width for given address space.
Definition: SValBuilder.h:347
ProgramStateManager & StateMgr
Definition: SValBuilder.h:69
std::optional< SVal > getConstantVal(const Expr *E)
Returns the value of E, if it can be determined in a non-path-sensitive manner.
NonLoc makeLocAsInteger(Loc loc, unsigned bits)
Definition: SValBuilder.h:316
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique 'name'.
SVal evalIntegralCast(ProgramStateRef state, SVal val, QualType castTy, QualType originalType)
SymbolManager & getSymbolManager()
Definition: SValBuilder.h:165
DefinedOrUnknownSVal getRegionValueSymbolVal(const TypedValueRegion *region)
Make a unique symbol for value of region.
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
loc::ConcreteInt makeIntLocVal(const llvm::APSInt &integer)
Definition: SValBuilder.h:293
nonloc::SymbolVal makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, APSIntPtr rhs, QualType type)
Definition: SValBuilder.cpp:77
const AnalyzerOptions & AnOpts
Definition: SValBuilder.h:71
std::optional< loc::MemRegionVal > getCastedMemRegionVal(const MemRegion *region, QualType type)
Return MemRegionVal on success cast, otherwise return std::nullopt.
loc::MemRegionVal getAllocaRegionVal(const Expr *E, const LocationContext *LCtx, unsigned Count)
Create an SVal representing the result of an alloca()-like call, that is, an AllocaRegion on the stac...
nonloc::ConcreteInt makeBoolVal(const ObjCBoolLiteralExpr *boolean)
Definition: SValBuilder.h:283
SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, ProgramStateManager &stateMgr)
Definition: SValBuilder.cpp:52
SValVisitor - this class implements a simple visitor for SVal subclasses.
Definition: SValVisitor.h:27
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:56
bool isUndef() const
Definition: SVals.h:107
bool isUnknownOrUndef() const
Definition: SVals.h:109
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition: SVals.cpp:103
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition: SVals.h:87
const MemRegion * getAsRegion() const
Definition: SVals.cpp:119
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:83
bool isUnknown() const
Definition: SVals.h:105
std::optional< const MemRegion * > castRegion(const MemRegion *region, QualType CastToTy)
castRegion - Used by ExprEngine::VisitCast to handle casts from a MemRegion* to a specific location t...
Definition: Store.cpp:76
Symbolic value.
Definition: SymExpr.h:32
virtual QualType getType() const =0
virtual unsigned computeComplexity() const =0
Represents a cast expression.
A symbol representing the value of a MemRegion whose parent region has symbolic value.
SymbolExtent - Represents the extent (size in bytes) of a bounded region.
const SymExprT * acquire(Args &&...args)
Create or retrieve a SymExpr of type SymExprT for the given arguments.
const SymbolConjured * conjureSymbol(ConstCFGElementRef Elem, const LocationContext *LCtx, QualType T, unsigned VisitCount, const void *SymbolTag=nullptr)
static bool canSymbolicate(QualType T)
SymbolMetadata - Represents path-dependent metadata about a specific region.
A symbol representing the value stored at a MemRegion.
Definition: SymbolManager.h:44
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:808
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:563
virtual QualType getValueType() const =0
Represents a symbolic expression involving a unary operator.
The simplest example of a concrete compound value is nonloc::CompoundVal, which represents a concrete...
Definition: SVals.h:339
Value representing integer constant.
Definition: SVals.h:300
APSIntPtr getValue() const
Definition: SVals.h:304
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition: SVals.h:389
Value representing pointer-to-member.
Definition: SVals.h:434
Represents symbolic expression that isn't a location.
Definition: SVals.h:279
LLVM_ATTRIBUTE_RETURNS_NONNULL SymbolRef getSymbol() const
Definition: SVals.h:288
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
The JSON file list parser is used to communicate input to InstallAPI.
BinaryOperatorKind
CFGBlock::ConstCFGElementRef ConstCFGElementRef
Definition: CFG.h:1199
@ Result
The result type of a method or function.
UnaryOperatorKind
const FunctionProtoType * T
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:645