#include "clang/Analysis/CFG.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/Type.h"
#include "clang/Analysis/ConstructionContext.h"
#include "clang/Analysis/Support/BumpVector.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/JsonSupport.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DOTGraphTraits.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace clang;
static SourceLocation GetEndLoc(Decl *D) {
if (VarDecl *VD = dyn_cast<VarDecl>(D))
if (Expr *Ex = VD->getInit())
return Ex->getSourceRange().getEnd();
return D->getLocation();
}
static bool IsIntegerLiteralConstantExpr(const Expr *E) {
E = E->IgnoreParens();
if (const auto *CE = dyn_cast<CastExpr>(E)) {
if (CE->getCastKind() != CK_IntegralCast)
return false;
E = CE->getSubExpr();
}
if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
if (UO->getOpcode() != UO_Minus)
return false;
E = UO->getSubExpr();
}
return isa<IntegerLiteral>(E);
}
static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
E = E->IgnoreParens();
if (IsIntegerLiteralConstantExpr(E))
return E;
if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
return nullptr;
}
static std::tuple<const Expr *, BinaryOperatorKind, const Expr *>
tryNormalizeBinaryOperator(const BinaryOperator *B) {
BinaryOperatorKind Op = B->getOpcode();
const Expr *MaybeDecl = B->getLHS();
const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
if (Constant == nullptr) {
if (Op == BO_GT)
Op = BO_LT;
else if (Op == BO_GE)
Op = BO_LE;
else if (Op == BO_LT)
Op = BO_GT;
else if (Op == BO_LE)
Op = BO_GE;
MaybeDecl = B->getRHS();
Constant = tryTransformToIntOrEnumConstant(B->getLHS());
}
return std::make_tuple(MaybeDecl, Op, Constant);
}
static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2))
return false;
if (!isa<DeclRefExpr>(E1))
return true;
assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
const DeclContext *DC1 = Decl1->getDeclContext();
const DeclContext *DC2 = Decl2->getDeclContext();
assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
return DC1 == DC2;
}
namespace {
class CFGBuilder;
class AddStmtChoice {
public:
enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
bool alwaysAdd(CFGBuilder &builder,
const Stmt *stmt) const;
AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
}
private:
Kind kind;
};
class LocalScope {
public:
using AutomaticVarsTy = BumpVector<VarDecl *>;
class const_iterator {
const LocalScope* Scope = nullptr;
unsigned VarIter = 0;
public:
const_iterator() = default;
const_iterator(const LocalScope& S, unsigned I)
: Scope(&S), VarIter(I) {
if (VarIter == 0 && Scope)
*this = Scope->Prev;
}
VarDecl *const* operator->() const {
assert(Scope && "Dereferencing invalid iterator is not allowed");
assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
return &Scope->Vars[VarIter - 1];
}
const VarDecl *getFirstVarInScope() const {
assert(Scope && "Dereferencing invalid iterator is not allowed");
assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
return Scope->Vars[0];
}
VarDecl *operator*() const {
return *this->operator->();
}
const_iterator &operator++() {
if (!Scope)
return *this;
assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
--VarIter;
if (VarIter == 0)
*this = Scope->Prev;
return *this;
}
const_iterator operator++(int) {
const_iterator P = *this;
++*this;
return P;
}
bool operator==(const const_iterator &rhs) const {
return Scope == rhs.Scope && VarIter == rhs.VarIter;
}
bool operator!=(const const_iterator &rhs) const {
return !(*this == rhs);
}
explicit operator bool() const {
return *this != const_iterator();
}
int distance(const_iterator L);
const_iterator shared_parent(const_iterator L);
bool pointsToFirstDeclaredVar() { return VarIter == 1; }
};
private:
BumpVectorContext ctx;
AutomaticVarsTy Vars;
const_iterator Prev;
public:
LocalScope(BumpVectorContext ctx, const_iterator P)
: ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
const_iterator begin() const { return const_iterator(*this, Vars.size()); }
void addVar(VarDecl *VD) {
Vars.push_back(VD, ctx);
}
};
}
int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
int D = 0;
const_iterator F = *this;
while (F.Scope != L.Scope) {
assert(F != const_iterator() &&
"L iterator is not reachable from F iterator.");
D += F.VarIter;
F = F.Scope->Prev;
}
D += F.VarIter - L.VarIter;
return D;
}
LocalScope::const_iterator
LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
while (true) {
ScopesOfL.insert(L.Scope);
if (L == const_iterator())
break;
L = L.Scope->Prev;
}
const_iterator F = *this;
while (true) {
if (ScopesOfL.count(F.Scope))
return F;
assert(F != const_iterator() &&
"L iterator is not reachable from F iterator.");
F = F.Scope->Prev;
}
}
namespace {
struct BlockScopePosPair {
CFGBlock *block = nullptr;
LocalScope::const_iterator scopePosition;
BlockScopePosPair() = default;
BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
: block(b), scopePosition(scopePos) {}
};
class TryResult {
int X = -1;
public:
TryResult() = default;
TryResult(bool b) : X(b ? 1 : 0) {}
bool isTrue() const { return X == 1; }
bool isFalse() const { return X == 0; }
bool isKnown() const { return X >= 0; }
void negate() {
assert(isKnown());
X ^= 0x1;
}
};
}
static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
if (!R1.isKnown() || !R2.isKnown())
return TryResult();
return TryResult(R1.isTrue() && R2.isTrue());
}
namespace {
class reverse_children {
llvm::SmallVector<Stmt *, 12> childrenBuf;
ArrayRef<Stmt *> children;
public:
reverse_children(Stmt *S);
using iterator = ArrayRef<Stmt *>::reverse_iterator;
iterator begin() const { return children.rbegin(); }
iterator end() const { return children.rend(); }
};
}
reverse_children::reverse_children(Stmt *S) {
if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
children = CE->getRawSubExprs();
return;
}
switch (S->getStmtClass()) {
case Stmt::InitListExprClass: {
InitListExpr *IE = cast<InitListExpr>(S);
children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
IE->getNumInits());
return;
}
default:
break;
}
llvm::append_range(childrenBuf, S->children());
children = childrenBuf;
}
namespace {
class CFGBuilder {
using JumpTarget = BlockScopePosPair;
using JumpSource = BlockScopePosPair;
ASTContext *Context;
std::unique_ptr<CFG> cfg;
CFGBlock *Block = nullptr;
CFGBlock *Succ = nullptr;
JumpTarget ContinueJumpTarget;
JumpTarget BreakJumpTarget;
JumpTarget SEHLeaveJumpTarget;
CFGBlock *SwitchTerminatedBlock = nullptr;
CFGBlock *DefaultCaseBlock = nullptr;
CFGBlock *TryTerminatedBlock = nullptr;
LocalScope::const_iterator ScopePos;
using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
LabelMapTy LabelMap;
using BackpatchBlocksTy = std::vector<JumpSource>;
BackpatchBlocksTy BackpatchBlocks;
using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
LabelSetTy AddressTakenLabels;
llvm::DenseMap<Expr *, const ConstructionContextLayer *>
ConstructionContextMap;
using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>;
DeclsWithEndedScopeSetTy DeclsWithEndedScope;
bool badCFG = false;
const CFG::BuildOptions &BuildOpts;
bool switchExclusivelyCovered = false;
Expr::EvalResult *switchCond = nullptr;
CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
const Stmt *lastLookup = nullptr;
using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
CachedBoolEvalsTy CachedBoolEvals;
public:
explicit CFGBuilder(ASTContext *astContext,
const CFG::BuildOptions &buildOpts)
: Context(astContext), cfg(new CFG()), BuildOpts(buildOpts) {}
std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
bool alwaysAdd(const Stmt *stmt);
private:
CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc);
CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
CFGBlock *VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc);
CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
CFGBlock *VisitBreakStmt(BreakStmt *B);
CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
CFGBlock *VisitCaseStmt(CaseStmt *C);
CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
AddStmtChoice asc);
CFGBlock *VisitContinueStmt(ContinueStmt *C);
CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
AddStmtChoice asc);
CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
AddStmtChoice asc);
CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
AddStmtChoice asc);
CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
CFGBlock *VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc);
CFGBlock *VisitDeclStmt(DeclStmt *DS);
CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
CFGBlock *VisitDefaultStmt(DefaultStmt *D);
CFGBlock *VisitDoStmt(DoStmt *D);
CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
AddStmtChoice asc, bool ExternallyDestructed);
CFGBlock *VisitForStmt(ForStmt *F);
CFGBlock *VisitGotoStmt(GotoStmt *G);
CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
CFGBlock *VisitIfStmt(IfStmt *I);
CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
CFGBlock *VisitLabelStmt(LabelStmt *L);
CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
CFGBlock *VisitLogicalOperator(BinaryOperator *B);
std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
Stmt *Term,
CFGBlock *TrueBlock,
CFGBlock *FalseBlock);
CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
AddStmtChoice asc);
CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
CFGBlock *VisitReturnStmt(Stmt *S);
CFGBlock *VisitCoroutineSuspendExpr(CoroutineSuspendExpr *S,
AddStmtChoice asc);
CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
CFGBlock *VisitSwitchStmt(SwitchStmt *S);
CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
AddStmtChoice asc);
CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
CFGBlock *VisitWhileStmt(WhileStmt *W);
CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
bool ExternallyDestructed = false);
CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
CFGBlock *VisitChildren(Stmt *S);
CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
AddStmtChoice asc);
void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
const Stmt *S) {
if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
appendScopeBegin(B, VD, S);
}
struct TempDtorContext {
TempDtorContext() = default;
TempDtorContext(TryResult KnownExecuted)
: IsConditional(true), KnownExecuted(KnownExecuted) {}
bool needsTempDtorBranch() const {
return IsConditional && !TerminatorExpr;
}
void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
Succ = S;
TerminatorExpr = E;
}
const bool IsConditional = false;
const TryResult KnownExecuted = true;
CFGBlock *Succ = nullptr;
CXXBindTemporaryExpr *TerminatorExpr = nullptr;
};
CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
TempDtorContext &Context);
CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
TempDtorContext &Context);
CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
bool ExternallyDestructed,
TempDtorContext &Context);
CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
CFGBlock *VisitConditionalOperatorForTemporaryDtors(
AbstractConditionalOperator *E, bool ExternallyDestructed,
TempDtorContext &Context);
void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
CFGBlock *FalseSucc = nullptr);
CFGBlock *NYS() {
badCFG = true;
return Block;
}
void consumeConstructionContext(const ConstructionContextLayer *Layer,
Expr *E);
void findConstructionContexts(const ConstructionContextLayer *Layer,
Stmt *Child);
template <typename CallLikeExpr,
typename = std::enable_if_t<
std::is_base_of<CallExpr, CallLikeExpr>::value ||
std::is_base_of<CXXConstructExpr, CallLikeExpr>::value ||
std::is_base_of<ObjCMessageExpr, CallLikeExpr>::value>>
void findConstructionContextsForArguments(CallLikeExpr *E) {
for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Expr *Arg = E->getArg(i);
if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(),
ConstructionContextItem(E, i)),
Arg);
}
}
void cleanupConstructionContext(Expr *E);
void autoCreateBlock() { if (!Block) Block = createBlock(); }
CFGBlock *createBlock(bool add_successor = true);
CFGBlock *createNoReturnBlock();
CFGBlock *addStmt(Stmt *S) {
return Visit(S, AddStmtChoice::AlwaysAdd);
}
CFGBlock *addInitializer(CXXCtorInitializer *I);
void addLoopExit(const Stmt *LoopStmt);
void addAutomaticObjDtors(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S);
void addLifetimeEnds(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S);
void addAutomaticObjHandling(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S);
void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
Stmt *S);
void getDeclsWithEndedScope(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S);
LocalScope* createOrReuseLocalScope(LocalScope* Scope);
void addLocalScopeForStmt(Stmt *S);
LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
LocalScope* Scope = nullptr);
LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
void addLocalScopeAndDtors(Stmt *S);
const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
if (!BuildOpts.AddRichCXXConstructors)
return nullptr;
const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
if (!Layer)
return nullptr;
cleanupConstructionContext(E);
return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
Layer);
}
void appendStmt(CFGBlock *B, const Stmt *S) {
if (alwaysAdd(S) && cachedEntry)
cachedEntry->second = B;
assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
}
void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
if (const ConstructionContext *CC =
retrieveAndCleanupConstructionContext(CE)) {
B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
return;
}
B->appendStmt(CE, cfg->getBumpVectorContext());
}
void appendCall(CFGBlock *B, CallExpr *CE) {
if (alwaysAdd(CE) && cachedEntry)
cachedEntry->second = B;
if (const ConstructionContext *CC =
retrieveAndCleanupConstructionContext(CE)) {
B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
return;
}
B->appendStmt(CE, cfg->getBumpVectorContext());
}
void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
B->appendInitializer(I, cfg->getBumpVectorContext());
}
void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
B->appendNewAllocator(NE, cfg->getBumpVectorContext());
}
void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
B->appendBaseDtor(BS, cfg->getBumpVectorContext());
}
void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
B->appendMemberDtor(FD, cfg->getBumpVectorContext());
}
void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
if (alwaysAdd(ME) && cachedEntry)
cachedEntry->second = B;
if (const ConstructionContext *CC =
retrieveAndCleanupConstructionContext(ME)) {
B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
return;
}
B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
cfg->getBumpVectorContext());
}
void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
}
void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
}
void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
}
void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
}
void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
}
void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
LocalScope::const_iterator B, LocalScope::const_iterator E);
void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
LocalScope::const_iterator B,
LocalScope::const_iterator E);
const VarDecl *
prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
LocalScope::const_iterator B,
LocalScope::const_iterator E);
void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
cfg->getBumpVectorContext());
}
void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
cfg->getBumpVectorContext());
}
void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
if (BuildOpts.AddScopes)
B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
}
void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
if (BuildOpts.AddScopes)
B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
}
void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
if (BuildOpts.AddScopes)
B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
}
void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
if (BuildOpts.AddScopes)
B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
}
TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
const Expr *LHSExpr = B->getLHS()->IgnoreParens();
const Expr *RHSExpr = B->getRHS()->IgnoreParens();
const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
const Expr *BoolExpr = RHSExpr;
bool IntFirst = true;
if (!IntLiteral) {
IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
BoolExpr = LHSExpr;
IntFirst = false;
}
if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
return TryResult();
llvm::APInt IntValue = IntLiteral->getValue();
if ((IntValue == 1) || (IntValue == 0))
return TryResult();
bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
!IntValue.isNegative();
BinaryOperatorKind Bok = B->getOpcode();
if (Bok == BO_GT || Bok == BO_GE) {
return TryResult(IntFirst == IntLarger);
} else {
return TryResult(IntFirst != IntLarger);
}
}
TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
const Expr *LHSExpr = B->getLHS()->IgnoreParens();
const Expr *RHSExpr = B->getRHS()->IgnoreParens();
const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
const Expr *BoolExpr = RHSExpr;
if (!IntLiteral) {
IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
BoolExpr = LHSExpr;
}
if (!IntLiteral)
return TryResult();
const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
if (BitOp && (BitOp->getOpcode() == BO_And ||
BitOp->getOpcode() == BO_Or)) {
const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
if (!IntLiteral2)
IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
if (!IntLiteral2)
return TryResult();
llvm::APInt L1 = IntLiteral->getValue();
llvm::APInt L2 = IntLiteral2->getValue();
if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
(BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
if (BuildOpts.Observer)
BuildOpts.Observer->compareBitwiseEquality(B,
B->getOpcode() != BO_EQ);
TryResult(B->getOpcode() != BO_EQ);
}
} else if (BoolExpr->isKnownToHaveBooleanValue()) {
llvm::APInt IntValue = IntLiteral->getValue();
if ((IntValue == 1) || (IntValue == 0)) {
return TryResult();
}
return TryResult(B->getOpcode() != BO_EQ);
}
return TryResult();
}
TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
const llvm::APSInt &Value1,
const llvm::APSInt &Value2) {
assert(Value1.isSigned() == Value2.isSigned());
switch (Relation) {
default:
return TryResult();
case BO_EQ:
return TryResult(Value1 == Value2);
case BO_NE:
return TryResult(Value1 != Value2);
case BO_LT:
return TryResult(Value1 < Value2);
case BO_LE:
return TryResult(Value1 <= Value2);
case BO_GT:
return TryResult(Value1 > Value2);
case BO_GE:
return TryResult(Value1 >= Value2);
}
}
TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
assert(B->isLogicalOp());
const BinaryOperator *LHS =
dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
const BinaryOperator *RHS =
dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
if (!LHS || !RHS)
return {};
if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
return {};
const Expr *DeclExpr1;
const Expr *NumExpr1;
BinaryOperatorKind BO1;
std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS);
if (!DeclExpr1 || !NumExpr1)
return {};
const Expr *DeclExpr2;
const Expr *NumExpr2;
BinaryOperatorKind BO2;
std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS);
if (!DeclExpr2 || !NumExpr2)
return {};
if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2))
return {};
if (!areExprTypesCompatible(NumExpr1, NumExpr2))
return {};
Expr::EvalResult L1Result, L2Result;
if (!NumExpr1->EvaluateAsInt(L1Result, *Context) ||
!NumExpr2->EvaluateAsInt(L2Result, *Context))
return {};
llvm::APSInt L1 = L1Result.Val.getInt();
llvm::APSInt L2 = L2Result.Val.getInt();
if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
return {};
const llvm::APSInt Values[] = {
llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
L1,
((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
L1.isUnsigned()),
L2,
llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
};
bool AlwaysTrue = true, AlwaysFalse = true;
bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
for (const llvm::APSInt &Value : Values) {
TryResult Res1, Res2;
Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
if (!Res1.isKnown() || !Res2.isKnown())
return {};
if (B->getOpcode() == BO_LAnd) {
AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
} else {
AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
}
LHSAlwaysTrue &= Res1.isTrue();
LHSAlwaysFalse &= Res1.isFalse();
RHSAlwaysTrue &= Res2.isTrue();
RHSAlwaysFalse &= Res2.isFalse();
}
if (AlwaysTrue || AlwaysFalse) {
if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
!RHSAlwaysFalse && BuildOpts.Observer)
BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
return TryResult(AlwaysTrue);
}
return {};
}
TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
const Expr *LHSConstant =
tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts());
const Expr *RHSConstant =
tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts());
if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
return {};
const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
Expr::EvalResult Result;
if (!Constant->EvaluateAsInt(Result, *Context))
return {};
if (Result.Val.getInt() == 0)
return {};
if (BuildOpts.Observer)
BuildOpts.Observer->compareBitwiseOr(B);
return TryResult(true);
}
bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
if (!BuildOpts.PruneTriviallyFalseEdges)
return false;
return !S->isTypeDependent() &&
!S->isValueDependent() &&
S->EvaluateAsRValue(outResult, *Context);
}
TryResult tryEvaluateBool(Expr *S) {
if (!BuildOpts.PruneTriviallyFalseEdges ||
S->isTypeDependent() || S->isValueDependent())
return {};
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
if (I != CachedBoolEvals.end())
return I->second;
TryResult Result = evaluateAsBooleanConditionNoCache(S);
CachedBoolEvals[S] = Result; return Result;
}
else {
switch (Bop->getOpcode()) {
default: break;
case BO_Mul:
case BO_And: {
Expr::EvalResult LHSResult;
if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
llvm::APSInt IntVal = LHSResult.Val.getInt();
if (!IntVal.getBoolValue()) {
return TryResult(false);
}
}
Expr::EvalResult RHSResult;
if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
llvm::APSInt IntVal = RHSResult.Val.getInt();
if (!IntVal.getBoolValue()) {
return TryResult(false);
}
}
}
break;
}
}
}
return evaluateAsBooleanConditionNoCache(S);
}
TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
if (Bop->isLogicalOp()) {
TryResult LHS = tryEvaluateBool(Bop->getLHS());
if (LHS.isKnown()) {
if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
return LHS.isTrue();
TryResult RHS = tryEvaluateBool(Bop->getRHS());
if (RHS.isKnown()) {
if (Bop->getOpcode() == BO_LOr)
return LHS.isTrue() || RHS.isTrue();
else
return LHS.isTrue() && RHS.isTrue();
}
} else {
TryResult RHS = tryEvaluateBool(Bop->getRHS());
if (RHS.isKnown()) {
if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
return RHS.isTrue();
} else {
TryResult BopRes = checkIncorrectLogicOperator(Bop);
if (BopRes.isKnown())
return BopRes.isTrue();
}
}
return {};
} else if (Bop->isEqualityOp()) {
TryResult BopRes = checkIncorrectEqualityOperator(Bop);
if (BopRes.isKnown())
return BopRes.isTrue();
} else if (Bop->isRelationalOp()) {
TryResult BopRes = checkIncorrectRelationalOperator(Bop);
if (BopRes.isKnown())
return BopRes.isTrue();
} else if (Bop->getOpcode() == BO_Or) {
TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop);
if (BopRes.isKnown())
return BopRes.isTrue();
}
}
bool Result;
if (E->EvaluateAsBooleanCondition(Result, *Context))
return Result;
return {};
}
bool hasTrivialDestructor(VarDecl *VD);
};
}
inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
const Stmt *stmt) const {
return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
}
bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
bool shouldAdd = BuildOpts.alwaysAdd(stmt);
if (!BuildOpts.forcedBlkExprs)
return shouldAdd;
if (lastLookup == stmt) {
if (cachedEntry) {
assert(cachedEntry->first == stmt);
return true;
}
return shouldAdd;
}
lastLookup = stmt;
CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
if (!fb) {
assert(!cachedEntry);
return shouldAdd;
}
CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
if (itr == fb->end()) {
cachedEntry = nullptr;
return shouldAdd;
}
cachedEntry = &*itr;
return true;
}
static const VariableArrayType *FindVA(const Type *t) {
while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
if (vat->getSizeExpr())
return vat;
t = vt->getElementType().getTypePtr();
}
return nullptr;
}
void CFGBuilder::consumeConstructionContext(
const ConstructionContextLayer *Layer, Expr *E) {
assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
if (const ConstructionContextLayer *PreviouslyStoredLayer =
ConstructionContextMap.lookup(E)) {
(void)PreviouslyStoredLayer;
assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
"Already within a different construction context!");
} else {
ConstructionContextMap[E] = Layer;
}
}
void CFGBuilder::findConstructionContexts(
const ConstructionContextLayer *Layer, Stmt *Child) {
if (!BuildOpts.AddRichCXXConstructors)
return;
if (!Child)
return;
auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
Layer);
};
switch(Child->getStmtClass()) {
case Stmt::CXXConstructExprClass:
case Stmt::CXXTemporaryObjectExprClass: {
auto *CE = cast<CXXConstructExpr>(Child);
if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
}
consumeConstructionContext(Layer, CE);
break;
}
case Stmt::CallExprClass:
case Stmt::CXXMemberCallExprClass:
case Stmt::CXXOperatorCallExprClass:
case Stmt::UserDefinedLiteralClass:
case Stmt::ObjCMessageExprClass: {
auto *E = cast<Expr>(Child);
if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
consumeConstructionContext(Layer, E);
break;
}
case Stmt::ExprWithCleanupsClass: {
auto *Cleanups = cast<ExprWithCleanups>(Child);
findConstructionContexts(Layer, Cleanups->getSubExpr());
break;
}
case Stmt::CXXFunctionalCastExprClass: {
auto *Cast = cast<CXXFunctionalCastExpr>(Child);
findConstructionContexts(Layer, Cast->getSubExpr());
break;
}
case Stmt::ImplicitCastExprClass: {
auto *Cast = cast<ImplicitCastExpr>(Child);
switch (Cast->getCastKind()) {
case CK_NoOp:
case CK_ConstructorConversion:
findConstructionContexts(Layer, Cast->getSubExpr());
break;
default:
break;
}
break;
}
case Stmt::CXXBindTemporaryExprClass: {
auto *BTE = cast<CXXBindTemporaryExpr>(Child);
findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
break;
}
case Stmt::MaterializeTemporaryExprClass: {
if (Layer->getItem().getKind() ==
ConstructionContextItem::ElidableConstructorKind) {
auto *MTE = cast<MaterializeTemporaryExpr>(Child);
findConstructionContexts(withExtraLayer(MTE), MTE->getSubExpr());
}
break;
}
case Stmt::ConditionalOperatorClass: {
auto *CO = cast<ConditionalOperator>(Child);
if (Layer->getItem().getKind() !=
ConstructionContextItem::MaterializationKind) {
assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
Context->getLangOpts().CPlusPlus17);
break;
}
findConstructionContexts(Layer, CO->getLHS());
findConstructionContexts(Layer, CO->getRHS());
break;
}
case Stmt::InitListExprClass: {
auto *ILE = cast<InitListExpr>(Child);
if (ILE->isTransparent()) {
findConstructionContexts(Layer, ILE->getInit(0));
break;
}
break;
}
case Stmt::ParenExprClass: {
auto *PE = cast<ParenExpr>(Child);
findConstructionContexts(Layer, PE->getSubExpr());
break;
}
default:
break;
}
}
void CFGBuilder::cleanupConstructionContext(Expr *E) {
assert(BuildOpts.AddRichCXXConstructors &&
"We should not be managing construction contexts!");
assert(ConstructionContextMap.count(E) &&
"Cannot exit construction context without the context!");
ConstructionContextMap.erase(E);
}
std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
assert(cfg.get());
if (!Statement)
return nullptr;
Succ = createBlock();
assert(Succ == &cfg->getExit());
Block = nullptr;
assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
"AddImplicitDtors and AddLifetime cannot be used at the same time");
if (BuildOpts.AddImplicitDtors)
if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
addImplicitDtorsForDestructor(DD);
CFGBlock *B = addStmt(Statement);
if (badCFG)
return nullptr;
if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
CFGBlock *VBaseSucc = nullptr;
for (auto *I : llvm::reverse(CD->inits())) {
if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
I->isBaseInitializer() && I->isBaseVirtual()) {
VBaseSucc = Succ = B ? B : &cfg->getExit();
Block = createBlock();
}
B = addInitializer(I);
if (badCFG)
return nullptr;
}
if (VBaseSucc) {
Succ = VBaseSucc;
B = createBlock();
B->setTerminator(
CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
addSuccessor(B, Block, true);
}
}
if (B)
Succ = B;
for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
E = BackpatchBlocks.end(); I != E; ++I ) {
CFGBlock *B = I->block;
if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
if (LI == LabelMap.end())
continue;
JumpTarget JT = LI->second;
prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
JT.scopePosition);
prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
JT.scopePosition);
const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
B, I->scopePosition, JT.scopePosition);
appendScopeBegin(JT.block, VD, G);
addSuccessor(B, JT.block);
};
if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
CFGBlock *Successor = (I+1)->block;
for (auto *L : G->labels()) {
LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
if (LI == LabelMap.end())
continue;
JumpTarget JT = LI->second;
if (JT.block == Successor)
continue;
addSuccessor(B, JT.block);
}
I++;
}
}
if (CFGBlock *B = cfg->getIndirectGotoBlock())
for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
E = AddressTakenLabels.end(); I != E; ++I ) {
LabelMapTy::iterator LI = LabelMap.find(*I);
if (LI == LabelMap.end()) continue;
addSuccessor(B, LI->second.block);
}
cfg->setEntry(createBlock());
if (BuildOpts.AddRichCXXConstructors)
assert(ConstructionContextMap.empty() &&
"Not all construction contexts were cleaned up!");
return std::move(cfg);
}
CFGBlock *CFGBuilder::createBlock(bool add_successor) {
CFGBlock *B = cfg->createBlock();
if (add_successor && Succ)
addSuccessor(B, Succ);
return B;
}
CFGBlock *CFGBuilder::createNoReturnBlock() {
CFGBlock *B = createBlock(false);
B->setHasNoReturnElement();
addSuccessor(B, &cfg->getExit(), Succ);
return B;
}
CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
if (!BuildOpts.AddInitializers)
return Block;
bool HasTemporaries = false;
Expr *Init = I->getInit();
if (Init) {
HasTemporaries = isa<ExprWithCleanups>(Init);
if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
TempDtorContext Context;
VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
false, Context);
}
}
autoCreateBlock();
appendInitializer(Block, I);
if (Init) {
const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init);
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
AILE ? AILE->getSubExpr() : Init);
if (HasTemporaries) {
return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
}
if (BuildOpts.AddCXXDefaultInitExprInCtors) {
if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
autoCreateBlock();
appendStmt(Block, Default);
if (Stmt *Child = Default->getExpr())
if (CFGBlock *R = Visit(Child))
Block = R;
return Block;
}
}
return Visit(Init);
}
return Block;
}
static QualType getReferenceInitTemporaryType(const Expr *Init,
bool *FoundMTE = nullptr) {
while (true) {
Init = Init->IgnoreParens();
if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
Init = EWC->getSubExpr();
continue;
}
if (const MaterializeTemporaryExpr *MTE
= dyn_cast<MaterializeTemporaryExpr>(Init)) {
Init = MTE->getSubExpr();
if (FoundMTE)
*FoundMTE = true;
continue;
}
SmallVector<const Expr *, 2> CommaLHSs;
SmallVector<SubobjectAdjustment, 2> Adjustments;
const Expr *SkippedInit =
Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
if (SkippedInit != Init) {
Init = SkippedInit;
continue;
}
break;
}
return Init->getType();
}
void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
if(!BuildOpts.AddLoopExit)
return;
autoCreateBlock();
appendLoopExit(Block, LoopStmt);
}
void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S) {
if (!BuildOpts.AddScopes)
return;
if (B == E)
return;
LocalScope::const_iterator P = B.shared_parent(E);
int Dist = B.distance(P);
if (Dist <= 0)
return;
for (LocalScope::const_iterator I = B; I != P; ++I)
if (I.pointsToFirstDeclaredVar())
DeclsWithEndedScope.insert(*I);
}
void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
LocalScope::const_iterator E,
Stmt *S) {
getDeclsWithEndedScope(B, E, S);
if (BuildOpts.AddScopes)
addScopesEnd(B, E, S);
if (BuildOpts.AddImplicitDtors)
addAutomaticObjDtors(B, E, S);
if (BuildOpts.AddLifetime)
addLifetimeEnds(B, E, S);
}
void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S) {
if (!BuildOpts.AddLifetime)
return;
if (B == E)
return;
LocalScope::const_iterator P = B.shared_parent(E);
int dist = B.distance(P);
if (dist <= 0)
return;
SmallVector<VarDecl *, 10> DeclsTrivial;
SmallVector<VarDecl *, 10> DeclsNonTrivial;
DeclsTrivial.reserve(dist);
DeclsNonTrivial.reserve(dist);
for (LocalScope::const_iterator I = B; I != P; ++I)
if (hasTrivialDestructor(*I))
DeclsTrivial.push_back(*I);
else
DeclsNonTrivial.push_back(*I);
autoCreateBlock();
for (VarDecl *VD : llvm::reverse(DeclsTrivial))
appendLifetimeEnds(Block, VD, S);
for (VarDecl *VD : llvm::reverse(DeclsNonTrivial))
appendLifetimeEnds(Block, VD, S);
}
void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S) {
if (BuildOpts.AddImplicitDtors)
return;
autoCreateBlock();
for (VarDecl *VD : llvm::reverse(DeclsWithEndedScope))
appendScopeEnd(Block, VD, S);
}
void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
LocalScope::const_iterator E, Stmt *S) {
if (!BuildOpts.AddImplicitDtors)
return;
if (B == E)
return;
SmallVector<VarDecl*, 10> Decls;
Decls.reserve(B.distance(E));
for (LocalScope::const_iterator I = B; I != E; ++I)
Decls.push_back(*I);
for (VarDecl *VD : llvm::reverse(Decls)) {
if (hasTrivialDestructor(VD)) {
if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) {
autoCreateBlock();
appendScopeEnd(Block, VD, S);
}
continue;
}
QualType Ty = VD->getType();
if (Ty->isReferenceType()) {
Ty = getReferenceInitTemporaryType(VD->getInit());
}
Ty = Context->getBaseElementType(Ty);
if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Block = createNoReturnBlock();
else
autoCreateBlock();
if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD))
appendScopeEnd(Block, VD, S);
appendAutomaticObjDtor(Block, VD, S);
}
}
void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
assert(BuildOpts.AddImplicitDtors &&
"Can be called only when dtors should be added");
const CXXRecordDecl *RD = DD->getParent();
for (const auto &VI : RD->vbases()) {
const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
if (!CD->hasTrivialDestructor()) {
autoCreateBlock();
appendBaseDtor(Block, &VI);
}
}
for (const auto &BI : RD->bases()) {
if (!BI.isVirtual()) {
const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
if (!CD->hasTrivialDestructor()) {
autoCreateBlock();
appendBaseDtor(Block, &BI);
}
}
}
for (auto *FI : RD->fields()) {
QualType QT = FI->getType();
if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
if (AT->getSize() == 0)
continue;
QT = AT->getElementType();
}
if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
if (!CD->hasTrivialDestructor()) {
autoCreateBlock();
appendMemberDtor(Block, FI);
}
}
}
LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
if (Scope)
return Scope;
llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
return new (alloc.Allocate<LocalScope>())
LocalScope(BumpVectorContext(alloc), ScopePos);
}
void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
!BuildOpts.AddScopes)
return;
LocalScope *Scope = nullptr;
if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
for (auto *BI : CS->body()) {
Stmt *SI = BI->stripLabelLikeStatements();
if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Scope = addLocalScopeForDeclStmt(DS, Scope);
}
return;
}
if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
addLocalScopeForDeclStmt(DS);
}
LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
LocalScope* Scope) {
if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
!BuildOpts.AddScopes)
return Scope;
for (auto *DI : DS->decls())
if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Scope = addLocalScopeForVarDecl(VD, Scope);
return Scope;
}
bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
QualType QT = VD->getType();
if (QT->isReferenceType()) {
const Expr *Init = VD->getInit();
if (!Init) {
return true;
}
bool FoundMTE = false;
QT = getReferenceInitTemporaryType(Init, &FoundMTE);
if (!FoundMTE)
return true;
}
while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
if (AT->getSize() == 0)
return true;
QT = AT->getElementType();
}
if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
return !CD->hasDefinition() || CD->hasTrivialDestructor();
return true;
}
LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
LocalScope* Scope) {
assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
"AddImplicitDtors and AddLifetime cannot be used at the same time");
if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
!BuildOpts.AddScopes)
return Scope;
if (!VD->hasLocalStorage())
return Scope;
if (BuildOpts.AddImplicitDtors) {
if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
Scope = createOrReuseLocalScope(Scope);
Scope->addVar(VD);
ScopePos = Scope->begin();
}
return Scope;
}
assert(BuildOpts.AddLifetime);
Scope = createOrReuseLocalScope(Scope);
Scope->addVar(VD);
ScopePos = Scope->begin();
return Scope;
}
void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
LocalScope::const_iterator scopeBeginPos = ScopePos;
addLocalScopeForStmt(S);
addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
}
void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
LocalScope::const_iterator B, LocalScope::const_iterator E) {
if (!BuildOpts.AddImplicitDtors)
return;
BumpVectorContext &C = cfg->getBumpVectorContext();
CFGBlock::iterator InsertPos
= Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
for (LocalScope::const_iterator I = B; I != E; ++I)
InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
Blk->getTerminatorStmt());
}
void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
if (!BuildOpts.AddLifetime)
return;
BumpVectorContext &C = cfg->getBumpVectorContext();
CFGBlock::iterator InsertPos =
Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
for (LocalScope::const_iterator I = B; I != E; ++I) {
InsertPos =
Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt());
}
}
const VarDecl *
CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
if (!BuildOpts.AddScopes)
return nullptr;
BumpVectorContext &C = cfg->getBumpVectorContext();
CFGBlock::iterator InsertPos =
Blk->beginScopeEndInsert(Blk->end(), 1, C);
LocalScope::const_iterator PlaceToInsert = B;
for (LocalScope::const_iterator I = B; I != E; ++I)
PlaceToInsert = I;
Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt());
return *PlaceToInsert;
}
CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
bool ExternallyDestructed) {
if (!S) {
badCFG = true;
return nullptr;
}
if (Expr *E = dyn_cast<Expr>(S))
S = E->IgnoreParens();
if (Context->getLangOpts().OpenMP)
if (auto *D = dyn_cast<OMPExecutableDirective>(S))
return VisitOMPExecutableDirective(D, asc);
switch (S->getStmtClass()) {
default:
return VisitStmt(S, asc);
case Stmt::ImplicitValueInitExprClass:
if (BuildOpts.OmitImplicitValueInitializers)
return Block;
return VisitStmt(S, asc);
case Stmt::InitListExprClass:
return VisitInitListExpr(cast<InitListExpr>(S), asc);
case Stmt::AttributedStmtClass:
return VisitAttributedStmt(cast<AttributedStmt>(S), asc);
case Stmt::AddrLabelExprClass:
return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
case Stmt::BinaryConditionalOperatorClass:
return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
case Stmt::BinaryOperatorClass:
return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
case Stmt::BlockExprClass:
return VisitBlockExpr(cast<BlockExpr>(S), asc);
case Stmt::BreakStmtClass:
return VisitBreakStmt(cast<BreakStmt>(S));
case Stmt::CallExprClass:
case Stmt::CXXOperatorCallExprClass:
case Stmt::CXXMemberCallExprClass:
case Stmt::UserDefinedLiteralClass:
return VisitCallExpr(cast<CallExpr>(S), asc);
case Stmt::CaseStmtClass:
return VisitCaseStmt(cast<CaseStmt>(S));
case Stmt::ChooseExprClass:
return VisitChooseExpr(cast<ChooseExpr>(S), asc);
case Stmt::CompoundStmtClass:
return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed);
case Stmt::ConditionalOperatorClass:
return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
case Stmt::ContinueStmtClass:
return VisitContinueStmt(cast<ContinueStmt>(S));
case Stmt::CXXCatchStmtClass:
return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
case Stmt::ExprWithCleanupsClass:
return VisitExprWithCleanups(cast<ExprWithCleanups>(S),
asc, ExternallyDestructed);
case Stmt::CXXDefaultArgExprClass:
case Stmt::CXXDefaultInitExprClass:
return VisitStmt(S, asc);
case Stmt::CXXBindTemporaryExprClass:
return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
case Stmt::CXXConstructExprClass:
return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
case Stmt::CXXNewExprClass:
return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
case Stmt::CXXDeleteExprClass:
return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
case Stmt::CXXFunctionalCastExprClass:
return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
case Stmt::CXXTemporaryObjectExprClass:
return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
case Stmt::CXXThrowExprClass:
return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
case Stmt::CXXTryStmtClass:
return VisitCXXTryStmt(cast<CXXTryStmt>(S));
case Stmt::CXXTypeidExprClass:
return VisitCXXTypeidExpr(cast<CXXTypeidExpr>(S), asc);
case Stmt::CXXForRangeStmtClass:
return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
case Stmt::DeclStmtClass:
return VisitDeclStmt(cast<DeclStmt>(S));
case Stmt::DefaultStmtClass:
return VisitDefaultStmt(cast<DefaultStmt>(S));
case Stmt::DoStmtClass:
return VisitDoStmt(cast<DoStmt>(S));
case Stmt::ForStmtClass:
return VisitForStmt(cast<ForStmt>(S));
case Stmt::GotoStmtClass:
return VisitGotoStmt(cast<GotoStmt>(S));
case Stmt::GCCAsmStmtClass:
return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
case Stmt::IfStmtClass:
return VisitIfStmt(cast<IfStmt>(S));
case Stmt::ImplicitCastExprClass:
return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
case Stmt::ConstantExprClass:
return VisitConstantExpr(cast<ConstantExpr>(S), asc);
case Stmt::IndirectGotoStmtClass:
return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
case Stmt::LabelStmtClass:
return VisitLabelStmt(cast<LabelStmt>(S));
case Stmt::LambdaExprClass:
return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
case Stmt::MaterializeTemporaryExprClass:
return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
asc);
case Stmt::MemberExprClass:
return VisitMemberExpr(cast<MemberExpr>(S), asc);
case Stmt::NullStmtClass:
return Block;
case Stmt::ObjCAtCatchStmtClass:
return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
case Stmt::ObjCAutoreleasePoolStmtClass:
return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
case Stmt::ObjCAtSynchronizedStmtClass:
return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
case Stmt::ObjCAtThrowStmtClass:
return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
case Stmt::ObjCAtTryStmtClass:
return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
case Stmt::ObjCForCollectionStmtClass:
return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
case Stmt::ObjCMessageExprClass:
return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
case Stmt::OpaqueValueExprClass:
return Block;
case Stmt::PseudoObjectExprClass:
return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
case Stmt::ReturnStmtClass:
case Stmt::CoreturnStmtClass:
return VisitReturnStmt(S);
case Stmt::CoyieldExprClass:
case Stmt::CoawaitExprClass:
return VisitCoroutineSuspendExpr(cast<CoroutineSuspendExpr>(S), asc);
case Stmt::SEHExceptStmtClass:
return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
case Stmt::SEHFinallyStmtClass:
return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
case Stmt::SEHLeaveStmtClass:
return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
case Stmt::SEHTryStmtClass:
return VisitSEHTryStmt(cast<SEHTryStmt>(S));
case Stmt::UnaryExprOrTypeTraitExprClass:
return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
asc);
case Stmt::StmtExprClass:
return VisitStmtExpr(cast<StmtExpr>(S), asc);
case Stmt::SwitchStmtClass:
return VisitSwitchStmt(cast<SwitchStmt>(S));
case Stmt::UnaryOperatorClass:
return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
case Stmt::WhileStmtClass:
return VisitWhileStmt(cast<WhileStmt>(S));
case Stmt::ArrayInitLoopExprClass:
return VisitArrayInitLoopExpr(cast<ArrayInitLoopExpr>(S), asc);
}
}
CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
if (asc.alwaysAdd(*this, S)) {
autoCreateBlock();
appendStmt(Block, S);
}
return VisitChildren(S);
}
CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
CFGBlock *B = Block;
reverse_children RChildren(S);
for (Stmt *Child : RChildren) {
if (Child)
if (CFGBlock *R = Visit(Child))
B = R;
}
return B;
}
CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) {
if (asc.alwaysAdd(*this, ILE)) {
autoCreateBlock();
appendStmt(Block, ILE);
}
CFGBlock *B = Block;
reverse_children RChildren(ILE);
for (Stmt *Child : RChildren) {
if (!Child)
continue;
if (CFGBlock *R = Visit(Child))
B = R;
if (BuildOpts.AddCXXDefaultInitExprInAggregates) {
if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Child))
if (Stmt *Child = DIE->getExpr())
if (CFGBlock *R = Visit(Child))
B = R;
}
}
return B;
}
CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
AddStmtChoice asc) {
AddressTakenLabels.insert(A->getLabel());
if (asc.alwaysAdd(*this, A)) {
autoCreateBlock();
appendStmt(Block, A);
}
return Block;
}
static bool isFallthroughStatement(const AttributedStmt *A) {
bool isFallthrough = hasSpecificAttr<FallThroughAttr>(A->getAttrs());
assert((!isFallthrough || isa<NullStmt>(A->getSubStmt())) &&
"expected fallthrough not to have children");
return isFallthrough;
}
CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A,
AddStmtChoice asc) {
if (isFallthroughStatement(A) && asc.alwaysAdd(*this, A)) {
autoCreateBlock();
appendStmt(Block, A);
}
return VisitChildren(A);
}
CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc) {
if (asc.alwaysAdd(*this, U)) {
autoCreateBlock();
appendStmt(Block, U);
}
if (U->getOpcode() == UO_LNot)
tryEvaluateBool(U->getSubExpr()->IgnoreParens());
return Visit(U->getSubExpr(), AddStmtChoice());
}
CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
appendStmt(ConfluenceBlock, B);
if (badCFG)
return nullptr;
return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
ConfluenceBlock).first;
}
std::pair<CFGBlock*, CFGBlock*>
CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
Stmt *Term,
CFGBlock *TrueBlock,
CFGBlock *FalseBlock) {
Expr *RHS = B->getRHS()->IgnoreParens();
CFGBlock *RHSBlock, *ExitBlock;
do {
if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
if (B_RHS->isLogicalOp()) {
std::tie(RHSBlock, ExitBlock) =
VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
break;
}
ExitBlock = RHSBlock = createBlock(false);
TryResult KnownVal = tryEvaluateBool(RHS);
if (!KnownVal.isKnown())
KnownVal = tryEvaluateBool(B);
if (!Term) {
assert(TrueBlock == FalseBlock);
addSuccessor(RHSBlock, TrueBlock);
}
else {
RHSBlock->setTerminator(Term);
addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
}
Block = RHSBlock;
RHSBlock = addStmt(RHS);
}
while (false);
if (badCFG)
return std::make_pair(nullptr, nullptr);
Expr *LHS = B->getLHS()->IgnoreParens();
if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
if (B_LHS->isLogicalOp()) {
if (B->getOpcode() == BO_LOr)
FalseBlock = RHSBlock;
else
TrueBlock = RHSBlock;
return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
}
CFGBlock *LHSBlock = createBlock(false);
LHSBlock->setTerminator(B);
Block = LHSBlock;
CFGBlock *EntryLHSBlock = addStmt(LHS);
if (badCFG)
return std::make_pair(nullptr, nullptr);
TryResult KnownVal = tryEvaluateBool(LHS);
if (B->getOpcode() == BO_LOr) {
addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
} else {
assert(B->getOpcode() == BO_LAnd);
addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
}
return std::make_pair(EntryLHSBlock, ExitBlock);
}
CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
AddStmtChoice asc) {
if (B->isLogicalOp())
return VisitLogicalOperator(B);
if (B->getOpcode() == BO_Comma) { autoCreateBlock();
appendStmt(Block, B);
addStmt(B->getRHS());
return addStmt(B->getLHS());
}
if (B->isAssignmentOp()) {
if (asc.alwaysAdd(*this, B)) {
autoCreateBlock();
appendStmt(Block, B);
}
Visit(B->getLHS());
return Visit(B->getRHS());
}
if (asc.alwaysAdd(*this, B)) {
autoCreateBlock();
appendStmt(Block, B);
}
if (B->isEqualityOp() || B->isRelationalOp())
tryEvaluateBool(B);
CFGBlock *RBlock = Visit(B->getRHS());
CFGBlock *LBlock = Visit(B->getLHS());
return (LBlock ? LBlock : RBlock);
}
CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
if (asc.alwaysAdd(*this, E)) {
autoCreateBlock();
appendStmt(Block, E);
}
return Block;
}
CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
if (badCFG)
return nullptr;
Block = createBlock(false);
Block->setTerminator(B);
if (BreakJumpTarget.block) {
addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
addSuccessor(Block, BreakJumpTarget.block);
} else
badCFG = true;
return Block;
}
static bool CanThrow(Expr *E, ASTContext &Ctx) {
QualType Ty = E->getType();
if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
Ty = Ty->getPointeeType();
const FunctionType *FT = Ty->getAs<FunctionType>();
if (FT) {
if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Proto->isNothrow())
return false;
}
return true;
}
CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
QualType calleeType = C->getCallee()->getType();
if (calleeType == Context->BoundMemberTy) {
QualType boundType = Expr::findBoundMemberType(C->getCallee());
if (!boundType.isNull()) calleeType = boundType;
}
bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
bool AddEHEdge = false;
if (Context->getLangOpts().Exceptions) {
if (BuildOpts.AddEHEdges)
AddEHEdge = true;
}
bool OmitArguments = false;
if (FunctionDecl *FD = C->getDirectCallee()) {
if (!FD->isVariadic())
findConstructionContextsForArguments(C);
if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
NoReturn = true;
if (FD->hasAttr<NoThrowAttr>())
AddEHEdge = false;
if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
OmitArguments = true;
}
if (!CanThrow(C->getCallee(), *Context))
AddEHEdge = false;
if (OmitArguments) {
assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
autoCreateBlock();
appendStmt(Block, C);
return Visit(C->getCallee());
}
if (!NoReturn && !AddEHEdge) {
autoCreateBlock();
appendCall(Block, C);
return VisitChildren(C);
}
if (Block) {
Succ = Block;
if (badCFG)
return nullptr;
}
if (NoReturn)
Block = createNoReturnBlock();
else
Block = createBlock();
appendCall(Block, C);
if (AddEHEdge) {
if (TryTerminatedBlock)
addSuccessor(Block, TryTerminatedBlock);
else
addSuccessor(Block, &cfg->getExit());
}
return VisitChildren(C);
}
CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
AddStmtChoice asc) {
CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
appendStmt(ConfluenceBlock, C);
if (badCFG)
return nullptr;
AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Succ = ConfluenceBlock;
Block = nullptr;
CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
if (badCFG)
return nullptr;
Succ = ConfluenceBlock;
Block = nullptr;
CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
if (badCFG)
return nullptr;
Block = createBlock(false);
const TryResult& KnownVal = tryEvaluateBool(C->getCond());
addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Block->setTerminator(C);
return addStmt(C->getCond());
}
CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C,
bool ExternallyDestructed) {
LocalScope::const_iterator scopeBeginPos = ScopePos;
addLocalScopeForStmt(C);
if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
}
CFGBlock *LastBlock = Block;
for (Stmt *S : llvm::reverse(C->body())) {
CFGBlock *newBlock = Visit(S, AddStmtChoice::AlwaysAdd,
ExternallyDestructed);
if (newBlock)
LastBlock = newBlock;
if (badCFG)
return nullptr;
ExternallyDestructed = false;
}
return LastBlock;
}
CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
AddStmtChoice asc) {
const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
appendStmt(ConfluenceBlock, C);
if (badCFG)
return nullptr;
AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Succ = ConfluenceBlock;
Block = nullptr;
CFGBlock *LHSBlock = nullptr;
const Expr *trueExpr = C->getTrueExpr();
if (trueExpr != opaqueValue) {
LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
if (badCFG)
return nullptr;
Block = nullptr;
}
else
LHSBlock = ConfluenceBlock;
Succ = ConfluenceBlock;
CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
if (badCFG)
return nullptr;
if (BinaryOperator *Cond =
dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
if (Cond->isLogicalOp())
return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
Block = createBlock(false);
const TryResult& KnownVal = tryEvaluateBool(C->getCond());
addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Block->setTerminator(C);
Expr *condExpr = C->getCond();
if (opaqueValue) {
if (condExpr != opaqueValue)
addStmt(condExpr);
return addStmt(BCO->getCommon());
}
return addStmt(condExpr);
}
CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
if (isa<LabelDecl>(*DS->decl_begin()))
return Block;
if (DS->isSingleDecl())
return VisitDeclSubExpr(DS);
CFGBlock *B = nullptr;
for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
E = DS->decl_rend();
I != E; ++I) {
DeclGroupRef DG(*I);
Decl *D = *I;
DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
cfg->addSyntheticDeclStmt(DSNew, DS);
B = VisitDeclSubExpr(DSNew);
}
return B;
}
CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
assert(DS->isSingleDecl() && "Can handle single declarations only.");
if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl())) {
const Type *T = TND->getUnderlyingType().getTypePtr();
if (!T->isVariablyModifiedType())
return Block;
autoCreateBlock();
appendStmt(Block, DS);
CFGBlock *LastBlock = Block;
for (const VariableArrayType *VA = FindVA(T); VA != nullptr;
VA = FindVA(VA->getElementType().getTypePtr())) {
if (CFGBlock *NewBlock = addStmt(VA->getSizeExpr()))
LastBlock = NewBlock;
}
return LastBlock;
}
VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
if (!VD) {
return Block;
}
bool HasTemporaries = false;
CFGBlock *blockAfterStaticInit = nullptr;
if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
if (Block) {
Succ = Block;
Block = nullptr;
if (badCFG)
return nullptr;
}
blockAfterStaticInit = Succ;
}
Expr *Init = VD->getInit();
if (Init) {
HasTemporaries = isa<ExprWithCleanups>(Init);
if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
TempDtorContext Context;
VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
true, Context);
}
}
if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
for (auto BD : llvm::reverse(DD->bindings())) {
if (auto *VD = BD->getHoldingVar()) {
DeclGroupRef DG(VD);
DeclStmt *DSNew =
new (Context) DeclStmt(DG, VD->getLocation(), GetEndLoc(VD));
cfg->addSyntheticDeclStmt(DSNew, DS);
Block = VisitDeclSubExpr(DSNew);
}
}
}
autoCreateBlock();
appendStmt(Block, DS);
const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init);
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
AILE ? AILE->getSubExpr() : Init);
CFGBlock *LastBlock = Block;
if (Init) {
if (HasTemporaries) {
ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
LastBlock = newBlock;
}
else {
if (CFGBlock *newBlock = Visit(Init))
LastBlock = newBlock;
}
}
for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
LastBlock = newBlock;
}
maybeAddScopeBeginForVarDecl(Block, VD, DS);
if (ScopePos && VD == *ScopePos)
++ScopePos;
CFGBlock *B = LastBlock;
if (blockAfterStaticInit) {
Succ = B;
Block = createBlock(false);
Block->setTerminator(DS);
addSuccessor(Block, blockAfterStaticInit);
addSuccessor(Block, B);
B = Block;
}
return B;
}
CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
if (Stmt *Init = I->getInit())
addLocalScopeForStmt(Init);
if (VarDecl *VD = I->getConditionVariable())
addLocalScopeForVarDecl(VD);
addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
if (Block) {
Succ = Block;
if (badCFG)
return nullptr;
}
CFGBlock *ElseBlock = Succ;
if (Stmt *Else = I->getElse()) {
SaveAndRestore<CFGBlock*> sv(Succ);
Block = nullptr;
if (!isa<CompoundStmt>(Else))
addLocalScopeAndDtors(Else);
ElseBlock = addStmt(Else);
if (!ElseBlock) ElseBlock = sv.get();
else if (Block) {
if (badCFG)
return nullptr;
}
}
CFGBlock *ThenBlock;
{
Stmt *Then = I->getThen();
assert(Then);
SaveAndRestore<CFGBlock*> sv(Succ);
Block = nullptr;
if (!isa<CompoundStmt>(Then))
addLocalScopeAndDtors(Then);
ThenBlock = addStmt(Then);
if (!ThenBlock) {
ThenBlock = createBlock(false);
addSuccessor(ThenBlock, sv.get());
} else if (Block) {
if (badCFG)
return nullptr;
}
}
BinaryOperator *Cond =
(I->isConsteval() || I->getConditionVariable())
? nullptr
: dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
CFGBlock *LastBlock;
if (Cond && Cond->isLogicalOp())
LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
else {
Block = createBlock(false);
Block->setTerminator(I);
TryResult KnownVal;
if (!I->isConsteval())
KnownVal = tryEvaluateBool(I->getCond());
addSuccessor(Block, ThenBlock, !KnownVal.isFalse());
addSuccessor(Block, ElseBlock, !KnownVal.isTrue());
LastBlock = addStmt(I->getCond());
if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
autoCreateBlock();
LastBlock = addStmt(const_cast<DeclStmt *>(DS));
}
}
if (Stmt *Init = I->getInit()) {
autoCreateBlock();
LastBlock = addStmt(Init);
}
return LastBlock;
}
CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
Block = createBlock(false);
addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
if (auto *R = dyn_cast<ReturnStmt>(S))
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
R->getRetValue());
if (!Block->hasNoReturnElement())
addSuccessor(Block, &cfg->getExit());
appendStmt(Block, S);
if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) {
if (Expr *O = RS->getRetValue())
return Visit(O, AddStmtChoice::AlwaysAdd, true);
return Block;
}
CoreturnStmt *CRS = cast<CoreturnStmt>(S);
auto *B = Block;
if (CFGBlock *R = Visit(CRS->getPromiseCall()))
B = R;
if (Expr *RV = CRS->getOperand())
if (RV->getType()->isVoidType() && !isa<InitListExpr>(RV))
if (CFGBlock *R = Visit(RV))
B = R;
return B;
}
CFGBlock *CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr *E,
AddStmtChoice asc) {
if (asc.alwaysAdd(*this, E)) {
autoCreateBlock();
appendStmt(Block, E);
}
CFGBlock *B = Block;
if (auto *R = Visit(E->getResumeExpr()))
B = R;
if (auto *R = Visit(E->getSuspendExpr()))
B = R;
if (auto *R = Visit(E->getReadyExpr()))
B = R;
if (auto *R = Visit(E->getCommonExpr()))
B = R;
return B;
}
CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
addStmt(ES->getBlock());
CFGBlock *SEHExceptBlock = Block;
if (!SEHExceptBlock)
SEHExceptBlock = createBlock();
appendStmt(SEHExceptBlock, ES);
SEHExceptBlock->setLabel(ES);
if (badCFG)
return nullptr;
Block = nullptr;
return SEHExceptBlock;
}
CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
return VisitCompoundStmt(FS->getBlock(), false);
}
CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
if (badCFG)
return nullptr;
Block = createBlock(false);
Block->setTerminator(LS);
if (SEHLeaveJumpTarget.block) {
addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
addSuccessor(Block, SEHLeaveJumpTarget.block);
} else
badCFG = true;
return Block;
}
CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
CFGBlock *SEHTrySuccessor = nullptr;
if (Block) {
if (badCFG)
return nullptr;
SEHTrySuccessor = Block;
} else SEHTrySuccessor = Succ;
if (Terminator->getFinallyHandler())
return NYS();
CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
CFGBlock *NewTryTerminatedBlock = createBlock(false);
NewTryTerminatedBlock->setTerminator(Terminator);
if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
Succ = SEHTrySuccessor;
Block = nullptr;
CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
if (!ExceptBlock)
return nullptr;
addSuccessor(NewTryTerminatedBlock, ExceptBlock);
}
if (PrevSEHTryTerminatedBlock)
addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
else
addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Succ = SEHTrySuccessor;
SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
cfg->addTryDispatchBlock(TryTerminatedBlock);
SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
Block = nullptr;
return addStmt(Terminator->getTryBlock());
}
CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
addStmt(L->getSubStmt());
CFGBlock *LabelBlock = Block;
if (!LabelBlock) LabelBlock = createBlock();
assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
"label already in map");
LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
LabelBlock->setLabel(L);
if (badCFG)
return nullptr;
Block = nullptr;
Succ = LabelBlock;
return LabelBlock;
}
CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
CFGBlock *LastBlock = VisitNoRecurse(E, asc);
for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
if (Expr *CopyExpr = CI.getCopyExpr()) {
CFGBlock *Tmp = Visit(CopyExpr);
if (Tmp)
LastBlock = Tmp;
}
}
return LastBlock;
}
CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
CFGBlock *LastBlock = VisitNoRecurse(E, asc);
unsigned Idx = 0;
for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
et = E->capture_init_end();
it != et; ++it, ++Idx) {
if (Expr *Init = *it) {
const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init);
findConstructionContexts(ConstructionContextLayer::create(
cfg->getBumpVectorContext(), {E, Idx}),
AILE ? AILE->getSubExpr() : Init);
CFGBlock *Tmp = Visit(Init);
if (Tmp)
LastBlock = Tmp;
}
}
return LastBlock;
}
CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Block = createBlock(false);
Block->setTerminator(G);
LabelMapTy::iterator I = LabelMap.find(G->getLabel());
if (I == LabelMap.end())
BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
else {
JumpTarget JT = I->second;
addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
addSuccessor(Block, JT.block);
}
return Block;
}
CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
if (!G->isAsmGoto())
return VisitStmt(G, asc);
if (Block) {
Succ = Block;
if (badCFG)
return nullptr;
}
Block = createBlock();
Block->setTerminator(G);
BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
return VisitChildren(G);
}
CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
CFGBlock *LoopSuccessor = nullptr;
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
if (Stmt *Init = F->getInit())
addLocalScopeForStmt(Init);
LocalScope::const_iterator LoopBeginScopePos = ScopePos;
if (VarDecl *VD = F->getConditionVariable())
addLocalScopeForVarDecl(VD);
LocalScope::const_iterator ContinueScopePos = ScopePos;
addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
addLoopExit(F);
if (Block) {
if (badCFG)
return nullptr;
LoopSuccessor = Block;
} else
LoopSuccessor = Succ;
SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
{
assert(F->getBody());
SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Block = Succ = TransitionBlock = createBlock(false);
TransitionBlock->setLoopTarget(F);
if (Stmt *I = F->getInc()) {
Succ = addStmt(I);
}
if (Block) {
assert(Block == Succ);
if (badCFG)
return nullptr;
Block = nullptr;
}
ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
ContinueJumpTarget.block->setLoopTarget(F);
addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
if (!isa<CompoundStmt>(F->getBody()))
addLocalScopeAndDtors(F->getBody());
BodyBlock = addStmt(F->getBody());
if (!BodyBlock) {
BodyBlock = ContinueJumpTarget.block;
}
else if (badCFG)
return nullptr;
}
CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
do {
Expr *C = F->getCond();
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
if (BinaryOperator *Cond =
dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
if (Cond->isLogicalOp()) {
std::tie(EntryConditionBlock, ExitConditionBlock) =
VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
break;
}
EntryConditionBlock = ExitConditionBlock = createBlock(false);
ExitConditionBlock->setTerminator(F);
TryResult KnownVal(true);
if (C) {
Block = ExitConditionBlock;
EntryConditionBlock = addStmt(C);
if (VarDecl *VD = F->getConditionVariable()) {
if (Expr *Init = VD->getInit()) {
autoCreateBlock();
const DeclStmt *DS = F->getConditionVariableDeclStmt();
assert(DS->isSingleDecl());
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
Init);
appendStmt(Block, DS);
EntryConditionBlock = addStmt(Init);
assert(Block == EntryConditionBlock);
maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
}
}
if (Block && badCFG)
return nullptr;
KnownVal = tryEvaluateBool(C);
}
addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
addSuccessor(ExitConditionBlock,
KnownVal.isTrue() ? nullptr : LoopSuccessor);
} while (false);
addSuccessor(TransitionBlock, EntryConditionBlock);
Succ = EntryConditionBlock;
if (Stmt *I = F->getInit()) {
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
ScopePos = LoopBeginScopePos;
Block = createBlock();
return addStmt(I);
}
Block = nullptr;
Succ = EntryConditionBlock;
return EntryConditionBlock;
}
CFGBlock *
CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
AddStmtChoice asc) {
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
MTE->getSubExpr());
return VisitStmt(MTE, asc);
}
CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
if (asc.alwaysAdd(*this, M)) {
autoCreateBlock();
appendStmt(Block, M);
}
return Visit(M->getBase());
}
CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
CFGBlock *LoopSuccessor = nullptr;
if (Block) {
if (badCFG)
return nullptr;
LoopSuccessor = Block;
Block = nullptr;
} else
LoopSuccessor = Succ;
CFGBlock *ExitConditionBlock = createBlock(false);
ExitConditionBlock->setTerminator(S);
appendStmt(ExitConditionBlock, S);
Block = ExitConditionBlock;
CFGBlock *EntryConditionBlock = Visit(S->getElement(),
AddStmtChoice::NotAlwaysAdd);
if (Block) {
if (badCFG)
return nullptr;
Block = nullptr;
}
Succ = EntryConditionBlock;
{
SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
save_break(BreakJumpTarget);
CFGBlock *LoopBackBlock = nullptr;
Succ = LoopBackBlock = createBlock();
LoopBackBlock->setLoopTarget(S);
BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
ContinueJumpTarget = JumpTarget(Succ, ScopePos);
CFGBlock *BodyBlock = addStmt(S->getBody());
if (!BodyBlock)
BodyBlock = ContinueJumpTarget.block; else if (Block) {
if (badCFG)
return nullptr;
}
addSuccessor(ExitConditionBlock, BodyBlock);
}
addSuccessor(ExitConditionBlock, LoopSuccessor);
Block = createBlock();
return addStmt(S->getCollection());
}
CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
return addStmt(S->getSubStmt());
}
CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
CFGBlock *SyncBlock = addStmt(S->getSynchBody());
if (SyncBlock) {
if (badCFG)
return nullptr;
Block = nullptr;
Succ = SyncBlock;
}
autoCreateBlock();
appendStmt(Block, S);
return addStmt(S->getSynchExpr());
}
CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
autoCreateBlock();
appendStmt(Block, E);
CFGBlock *lastBlock = Block;
for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
Expr *Semantic = E->getSemanticExpr(--i);
if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
Semantic = OVE->getSourceExpr();
if (CFGBlock *B = Visit(Semantic))
lastBlock = B;
}
return lastBlock;
}
CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
CFGBlock *LoopSuccessor = nullptr;
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
LocalScope::const_iterator LoopBeginScopePos = ScopePos;
if (VarDecl *VD = W->getConditionVariable()) {
addLocalScopeForVarDecl(VD);
addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
}
addLoopExit(W);
if (Block) {
if (badCFG)
return nullptr;
LoopSuccessor = Block;
Block = nullptr;
} else {
LoopSuccessor = Succ;
}
CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
{
assert(W->getBody());
SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
save_break(BreakJumpTarget);
Succ = TransitionBlock = createBlock(false);
TransitionBlock->setLoopTarget(W);
ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
if (!isa<CompoundStmt>(W->getBody()))
addLocalScopeAndDtors(W->getBody());
BodyBlock = addStmt(W->getBody());
if (!BodyBlock)
BodyBlock = ContinueJumpTarget.block; else if (Block && badCFG)
return nullptr;
}
CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
do {
Expr *C = W->getCond();
if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
if (Cond->isLogicalOp()) {
std::tie(EntryConditionBlock, ExitConditionBlock) =
VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
break;
}
ExitConditionBlock = createBlock(false);
ExitConditionBlock->setTerminator(W);
Block = ExitConditionBlock;
Block = EntryConditionBlock = addStmt(C);
if (VarDecl *VD = W->getConditionVariable()) {
if (Expr *Init = VD->getInit()) {
autoCreateBlock();
const DeclStmt *DS = W->getConditionVariableDeclStmt();
assert(DS->isSingleDecl());
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(),
const_cast<DeclStmt *>(DS)),
Init);
appendStmt(Block, DS);
EntryConditionBlock = addStmt(Init);
assert(Block == EntryConditionBlock);
maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
}
}
if (Block && badCFG)
return nullptr;
const TryResult& KnownVal = tryEvaluateBool(C);
addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
addSuccessor(ExitConditionBlock,
KnownVal.isTrue() ? nullptr : LoopSuccessor);
} while(false);
addSuccessor(TransitionBlock, EntryConditionBlock);
Block = nullptr;
Succ = EntryConditionBlock;
return EntryConditionBlock;
}
CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
AddStmtChoice asc) {
if (asc.alwaysAdd(*this, A)) {
autoCreateBlock();
appendStmt(Block, A);
}
CFGBlock *B = Block;
if (CFGBlock *R = Visit(A->getSubExpr()))
B = R;
auto *OVE = dyn_cast<OpaqueValueExpr>(A->getCommonExpr());
assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
"OpaqueValueExpr!");
if (CFGBlock *R = Visit(OVE->getSourceExpr()))
B = R;
return B;
}
CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
if (CS->getCatchBody())
addStmt(CS->getCatchBody());
CFGBlock *CatchBlock = Block;
if (!CatchBlock)
CatchBlock = createBlock();
appendStmt(CatchBlock, CS);
CatchBlock->setLabel(CS);
if (badCFG)
return nullptr;
Block = nullptr;
return CatchBlock;
}
CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
if (badCFG)
return nullptr;
Block = createBlock(false);
if (TryTerminatedBlock)
addSuccessor(Block, TryTerminatedBlock);
else
addSuccessor(Block, &cfg->getExit());
return VisitStmt(S, AddStmtChoice::AlwaysAdd);
}
CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
CFGBlock *TrySuccessor = nullptr;
if (Block) {
if (badCFG)
return nullptr;
TrySuccessor = Block;
} else
TrySuccessor = Succ;
if (Terminator->getFinallyStmt())
return NYS();
CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
CFGBlock *NewTryTerminatedBlock = createBlock(false);
NewTryTerminatedBlock->setTerminator(Terminator);
bool HasCatchAll = false;
for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
Succ = TrySuccessor;
if (CS->hasEllipsis()) {
HasCatchAll = true;
}
Block = nullptr;
CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
if (!CatchBlock)
return nullptr;
addSuccessor(NewTryTerminatedBlock, CatchBlock);
}
if (!HasCatchAll) {
if (PrevTryTerminatedBlock)
addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
else
addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
}
Succ = TrySuccessor;
SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
cfg->addTryDispatchBlock(TryTerminatedBlock);
assert(Terminator->getTryBody() && "try must contain a non-NULL body");
Block = nullptr;
return addStmt(Terminator->getTryBody());
}
CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
AddStmtChoice asc) {
findConstructionContextsForArguments(ME);
autoCreateBlock();
appendObjCMessage(Block, ME);
return VisitChildren(ME);
}
CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
if (badCFG)
return nullptr;
Block = createBlock(false);
if (TryTerminatedBlock)
addSuccessor(Block, TryTerminatedBlock);
else
addSuccessor(Block, &cfg->getExit());
return VisitStmt(T, AddStmtChoice::AlwaysAdd);
}
CFGBlock *CFGBuilder::VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc) {
if (asc.alwaysAdd(*this, S)) {
autoCreateBlock();
appendStmt(Block, S);
}
if (S && !S->isTypeDependent() && S->isPotentiallyEvaluated())
return VisitChildren(S);
return Block;
}
CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
CFGBlock *LoopSuccessor = nullptr;
addLoopExit(D);
if (Block) {
if (badCFG)
return nullptr;
LoopSuccessor = Block;
} else
LoopSuccessor = Succ;
CFGBlock *ExitConditionBlock = createBlock(false);
CFGBlock *EntryConditionBlock = ExitConditionBlock;
ExitConditionBlock->setTerminator(D);
if (Stmt *C = D->getCond()) {
Block = ExitConditionBlock;
EntryConditionBlock = addStmt(C);
if (Block) {
if (badCFG)
return nullptr;
}
}
Succ = EntryConditionBlock;
const TryResult &KnownVal = tryEvaluateBool(D->getCond());
CFGBlock *BodyBlock = nullptr;
{
assert(D->getBody());
SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
save_break(BreakJumpTarget);
ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Block = nullptr;
if (!isa<CompoundStmt>(D->getBody()))
addLocalScopeAndDtors(D->getBody());
BodyBlock = addStmt(D->getBody());
if (!BodyBlock)
BodyBlock = EntryConditionBlock; else if (Block) {
if (badCFG)
return nullptr;
}
Block = nullptr;
Succ = BodyBlock;
CFGBlock *LoopBackBlock = createBlock();
LoopBackBlock->setLoopTarget(D);
if (!KnownVal.isFalse())
addSuccessor(ExitConditionBlock, LoopBackBlock);
else
addSuccessor(ExitConditionBlock, nullptr);
}
addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Block = nullptr;
Succ = BodyBlock;
return BodyBlock;
}
CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
if (badCFG)
return nullptr;
Block = createBlock(false);
Block->setTerminator(C);
if (ContinueJumpTarget.block) {
addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
addSuccessor(Block, ContinueJumpTarget.block);
} else
badCFG = true;
return Block;
}
CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
AddStmtChoice asc) {
if (asc.alwaysAdd(*this, E)) {
autoCreateBlock();
appendStmt(Block, E);
}
if (E->getKind() != UETT_SizeOf)
return Block;
CFGBlock *lastBlock = Block;
if (E->isArgumentType()) {
for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
lastBlock = addStmt(VA->getSizeExpr());
}
return lastBlock;
}
CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
if (asc.alwaysAdd(*this, SE)) {
autoCreateBlock();
appendStmt(Block, SE);
}
return VisitCompoundStmt(SE->getSubStmt(), true);
}
CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
CFGBlock *SwitchSuccessor = nullptr;
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
if (Stmt *Init = Terminator->getInit())
addLocalScopeForStmt(Init);
if (VarDecl *VD = Terminator->getConditionVariable())
addLocalScopeForVarDecl(VD);
addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
if (Block) {
if (badCFG)
return nullptr;
SwitchSuccessor = Block;
} else SwitchSuccessor = Succ;
SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
save_default(DefaultCaseBlock);
SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
DefaultCaseBlock = SwitchSuccessor;
SwitchTerminatedBlock = createBlock(false);
Succ = SwitchSuccessor;
BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
assert(Terminator->getBody() && "switch must contain a non-NULL body");
Block = nullptr;
SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
false);
assert(Terminator->getCond() && "switch condition must be non-NULL");
Expr::EvalResult result;
bool b = tryEvaluate(Terminator->getCond(), result);
SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
b ? &result : nullptr);
if (!isa<CompoundStmt>(Terminator->getBody()))
addLocalScopeAndDtors(Terminator->getBody());
addStmt(Terminator->getBody());
if (Block) {
if (badCFG)
return nullptr;
}
bool SwitchAlwaysHasSuccessor = false;
SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
Terminator->getSwitchCaseList();
addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
!SwitchAlwaysHasSuccessor);
SwitchTerminatedBlock->setTerminator(Terminator);
Block = SwitchTerminatedBlock;
CFGBlock *LastBlock = addStmt(Terminator->getCond());
if (VarDecl *VD = Terminator->getConditionVariable()) {
if (Expr *Init = VD->getInit()) {
autoCreateBlock();
appendStmt(Block, Terminator->getConditionVariableDeclStmt());
LastBlock = addStmt(Init);
maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
}
}
if (Stmt *Init = Terminator->getInit()) {
autoCreateBlock();
LastBlock = addStmt(Init);
}
return LastBlock;
}
static bool shouldAddCase(bool &switchExclusivelyCovered,
const Expr::EvalResult *switchCond,
const CaseStmt *CS,
ASTContext &Ctx) {
if (!switchCond)
return true;
bool addCase = false;
if (!switchExclusivelyCovered) {
if (switchCond->Val.isInt()) {
const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
const llvm::APSInt &condInt = switchCond->Val.getInt();
if (condInt == lhsInt) {
addCase = true;
switchExclusivelyCovered = true;
}
else if (condInt > lhsInt) {
if (const Expr *RHS = CS->getRHS()) {
const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
if (V2 >= condInt) {
addCase = true;
switchExclusivelyCovered = true;
}
}
}
}
else
addCase = true;
}
return addCase;
}
CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
if (Stmt *Sub = CS->getSubStmt()) {
while (isa<CaseStmt>(Sub)) {
CFGBlock *currentBlock = createBlock(false);
currentBlock->setLabel(CS);
if (TopBlock)
addSuccessor(LastBlock, currentBlock);
else
TopBlock = currentBlock;
addSuccessor(SwitchTerminatedBlock,
shouldAddCase(switchExclusivelyCovered, switchCond,
CS, *Context)
? currentBlock : nullptr);
LastBlock = currentBlock;
CS = cast<CaseStmt>(Sub);
Sub = CS->getSubStmt();
}
addStmt(Sub);
}
CFGBlock *CaseBlock = Block;
if (!CaseBlock)
CaseBlock = createBlock();
CaseBlock->setLabel(CS);
if (badCFG)
return nullptr;
assert(SwitchTerminatedBlock);
addSuccessor(SwitchTerminatedBlock, CaseBlock,
shouldAddCase(switchExclusivelyCovered, switchCond,
CS, *Context));
Block = nullptr;
if (TopBlock) {
addSuccessor(LastBlock, CaseBlock);
Succ = TopBlock;
} else {
Succ = CaseBlock;
}
return Succ;
}
CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
if (Terminator->getSubStmt())
addStmt(Terminator->getSubStmt());
DefaultCaseBlock = Block;
if (!DefaultCaseBlock)
DefaultCaseBlock = createBlock();
DefaultCaseBlock->setLabel(Terminator);
if (badCFG)
return nullptr;
Block = nullptr;
Succ = DefaultCaseBlock;
return DefaultCaseBlock;
}
CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
CFGBlock *TrySuccessor = nullptr;
if (Block) {
if (badCFG)
return nullptr;
TrySuccessor = Block;
} else
TrySuccessor = Succ;
CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
CFGBlock *NewTryTerminatedBlock = createBlock(false);
NewTryTerminatedBlock->setTerminator(Terminator);
bool HasCatchAll = false;
for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) {
Succ = TrySuccessor;
CXXCatchStmt *CS = Terminator->getHandler(I);
if (CS->getExceptionDecl() == nullptr) {
HasCatchAll = true;
}
Block = nullptr;
CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
if (!CatchBlock)
return nullptr;
addSuccessor(NewTryTerminatedBlock, CatchBlock);
}
if (!HasCatchAll) {
if (PrevTryTerminatedBlock)
addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
else
addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
}
Succ = TrySuccessor;
SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
cfg->addTryDispatchBlock(TryTerminatedBlock);
assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Block = nullptr;
return addStmt(Terminator->getTryBlock());
}
CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
if (VarDecl *VD = CS->getExceptionDecl()) {
LocalScope::const_iterator BeginScopePos = ScopePos;
addLocalScopeForVarDecl(VD);
addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
}
if (CS->getHandlerBlock())
addStmt(CS->getHandlerBlock());
CFGBlock *CatchBlock = Block;
if (!CatchBlock)
CatchBlock = createBlock();
appendStmt(CatchBlock, CS);
CatchBlock->setLabel(CS);
if (badCFG)
return nullptr;
Block = nullptr;
return CatchBlock;
}
CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
if (Stmt *Range = S->getRangeStmt())
addLocalScopeForStmt(Range);
if (Stmt *Begin = S->getBeginStmt())
addLocalScopeForStmt(Begin);
if (Stmt *End = S->getEndStmt())
addLocalScopeForStmt(End);
addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
LocalScope::const_iterator ContinueScopePos = ScopePos;
CFGBlock *LoopSuccessor = nullptr;
if (Block) {
if (badCFG)
return nullptr;
LoopSuccessor = Block;
} else
LoopSuccessor = Succ;
SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
CFGBlock *ConditionBlock = createBlock(false);
ConditionBlock->setTerminator(S);
if (Expr *C = S->getCond()) {
Block = ConditionBlock;
CFGBlock *BeginConditionBlock = addStmt(C);
if (badCFG)
return nullptr;
assert(BeginConditionBlock == ConditionBlock &&
"condition block in for-range was unexpectedly complex");
(void)BeginConditionBlock;
}
Succ = ConditionBlock;
TryResult KnownVal(true);
if (S->getCond())
KnownVal = tryEvaluateBool(S->getCond());
{
assert(S->getBody());
SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Block = nullptr;
Succ = addStmt(S->getInc());
if (badCFG)
return nullptr;
ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
ContinueJumpTarget.block->setLoopTarget(S);
assert(Block);
if (badCFG)
return nullptr;
Block = nullptr;
addLocalScopeAndDtors(S->getLoopVarStmt());
if (!isa<CompoundStmt>(S->getBody()))
addLocalScopeAndDtors(S->getBody());
addStmt(S->getBody());
if (badCFG)
return nullptr;
CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
if (badCFG)
return nullptr;
addSuccessor(ConditionBlock,
KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
}
addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Block = createBlock();
addStmt(S->getBeginStmt());
addStmt(S->getEndStmt());
CFGBlock *Head = addStmt(S->getRangeStmt());
if (S->getInit())
Head = addStmt(S->getInit());
return Head;
}
CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
AddStmtChoice asc, bool ExternallyDestructed) {
if (BuildOpts.AddTemporaryDtors) {
TempDtorContext Context;
VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context);
asc = asc.withAlwaysAdd(true);
}
return Visit(E->getSubExpr(), asc);
}
CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
AddStmtChoice asc) {
if (asc.alwaysAdd(*this, E)) {
autoCreateBlock();
appendStmt(Block, E);
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
E->getSubExpr());
asc = asc.withAlwaysAdd(false);
}
return Visit(E->getSubExpr(), asc);
}
CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
AddStmtChoice asc) {
findConstructionContextsForArguments(C);
autoCreateBlock();
appendConstructor(Block, C);
return VisitChildren(C);
}
CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
AddStmtChoice asc) {
autoCreateBlock();
appendStmt(Block, NE);
findConstructionContexts(
ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
if (NE->getInitializer())
Block = Visit(NE->getInitializer());
if (BuildOpts.AddCXXNewAllocator)
appendNewAllocator(Block, NE);
if (NE->isArray() && *NE->getArraySize())
Block = Visit(*NE->getArraySize());
for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
E = NE->placement_arg_end(); I != E; ++I)
Block = Visit(*I);
return Block;
}
CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
AddStmtChoice asc) {
autoCreateBlock();
appendStmt(Block, DE);
QualType DTy = DE->getDestroyedType();
if (!DTy.isNull()) {
DTy = DTy.getNonReferenceType();
CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
if (RD) {
if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
appendDeleteDtor(Block, RD, DE);
}
}
return VisitChildren(DE);
}
CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
AddStmtChoice asc) {
if (asc.alwaysAdd(*this, E)) {
autoCreateBlock();
appendStmt(Block, E);
asc = asc.withAlwaysAdd(false);
}
return Visit(E->getSubExpr(), asc);
}
CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
AddStmtChoice asc) {
findConstructionContextsForArguments(C);
autoCreateBlock();
appendConstructor(Block, C);
return VisitChildren(C);
}
CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
AddStmtChoice asc) {
if (asc.alwaysAdd(*this, E)) {
autoCreateBlock();
appendStmt(Block, E);
}
if (E->getCastKind() == CK_IntegralToBoolean)
tryEvaluateBool(E->getSubExpr()->IgnoreParens());
return Visit(E->getSubExpr(), AddStmtChoice());
}
CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
return Visit(E->getSubExpr(), AddStmtChoice());
}
CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
CFGBlock *IBlock = cfg->getIndirectGotoBlock();
if (!IBlock) {
IBlock = createBlock(false);
cfg->setIndirectGotoBlock(IBlock);
}
if (badCFG)
return nullptr;
Block = createBlock(false);
Block->setTerminator(I);
addSuccessor(Block, IBlock);
return addStmt(I->getTarget());
}
CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
TempDtorContext &Context) {
assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
tryAgain:
if (!E) {
badCFG = true;
return nullptr;
}
switch (E->getStmtClass()) {
default:
return VisitChildrenForTemporaryDtors(E, false, Context);
case Stmt::InitListExprClass:
return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
case Stmt::BinaryOperatorClass:
return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
ExternallyDestructed,
Context);
case Stmt::CXXBindTemporaryExprClass:
return VisitCXXBindTemporaryExprForTemporaryDtors(
cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
case Stmt::BinaryConditionalOperatorClass:
case Stmt::ConditionalOperatorClass:
return VisitConditionalOperatorForTemporaryDtors(
cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
case Stmt::ImplicitCastExprClass:
E = cast<CastExpr>(E)->getSubExpr();
goto tryAgain;
case Stmt::CXXFunctionalCastExprClass:
E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
goto tryAgain;
case Stmt::ConstantExprClass:
E = cast<ConstantExpr>(E)->getSubExpr();
goto tryAgain;
case Stmt::ParenExprClass:
E = cast<ParenExpr>(E)->getSubExpr();
goto tryAgain;
case Stmt::MaterializeTemporaryExprClass: {
const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
SmallVector<const Expr *, 2> CommaLHSs;
SmallVector<SubobjectAdjustment, 2> Adjustments;
E = const_cast<Expr *>(
cast<MaterializeTemporaryExpr>(E)
->getSubExpr()
->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
for (const Expr *CommaLHS : CommaLHSs) {
VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
false, Context);
}
goto tryAgain;
}
case Stmt::BlockExprClass:
return Block;
case Stmt::LambdaExprClass: {
auto *LE = cast<LambdaExpr>(E);
CFGBlock *B = Block;
for (Expr *Init : LE->capture_inits()) {
if (Init) {
if (CFGBlock *R = VisitForTemporaryDtors(
Init, true, Context))
B = R;
}
}
return B;
}
case Stmt::StmtExprClass:
return Block;
case Stmt::CXXDefaultArgExprClass:
E = cast<CXXDefaultArgExpr>(E)->getExpr();
goto tryAgain;
case Stmt::CXXDefaultInitExprClass:
E = cast<CXXDefaultInitExpr>(E)->getExpr();
goto tryAgain;
}
}
CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
bool ExternallyDestructed,
TempDtorContext &Context) {
if (isa<LambdaExpr>(E)) {
return Block;
}
CFGBlock *B = Block;
for (Stmt *Child : E->children())
if (Child)
if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context))
B = R;
return B;
}
CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
if (E->isCommaOp()) {
CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
return RHSBlock ? RHSBlock : LHSBlock;
}
if (E->isLogicalOp()) {
VisitForTemporaryDtors(E->getLHS(), false, Context);
TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
RHSExecuted.negate();
TempDtorContext RHSContext(
bothKnownTrue(Context.KnownExecuted, RHSExecuted));
VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
InsertTempDtorDecisionBlock(RHSContext);
return Block;
}
if (E->isAssignmentOp()) {
CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
return LHSBlock ? LHSBlock : RHSBlock;
}
return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
}
CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
if (!ExternallyDestructed) {
const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
if (Dtor->getParent()->isAnyDestructorNoReturn()) {
if (B) Succ = B;
Block = createNoReturnBlock();
} else if (Context.needsTempDtorBranch()) {
if (B) Succ = B;
Block = createBlock();
} else {
autoCreateBlock();
}
if (Context.needsTempDtorBranch()) {
Context.setDecisionPoint(Succ, E);
}
appendTemporaryDtor(Block, E);
B = Block;
}
return B;
}
void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
CFGBlock *FalseSucc) {
if (!Context.TerminatorExpr) {
return;
}
assert(Context.TerminatorExpr);
CFGBlock *Decision = createBlock(false);
Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
CFGTerminator::TemporaryDtorsBranch));
addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
!Context.KnownExecuted.isTrue());
Block = Decision;
}
CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
AbstractConditionalOperator *E, bool ExternallyDestructed,
TempDtorContext &Context) {
VisitForTemporaryDtors(E->getCond(), false, Context);
CFGBlock *ConditionBlock = Block;
CFGBlock *ConditionSucc = Succ;
TryResult ConditionVal = tryEvaluateBool(E->getCond());
TryResult NegatedVal = ConditionVal;
if (NegatedVal.isKnown()) NegatedVal.negate();
TempDtorContext TrueContext(
bothKnownTrue(Context.KnownExecuted, ConditionVal));
VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
CFGBlock *TrueBlock = Block;
Block = ConditionBlock;
Succ = ConditionSucc;
TempDtorContext FalseContext(
bothKnownTrue(Context.KnownExecuted, NegatedVal));
VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
} else if (TrueContext.TerminatorExpr) {
Block = TrueBlock;
InsertTempDtorDecisionBlock(TrueContext);
} else {
InsertTempDtorDecisionBlock(FalseContext);
}
return Block;
}
CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
AddStmtChoice asc) {
if (asc.alwaysAdd(*this, D)) {
autoCreateBlock();
appendStmt(Block, D);
}
CFGBlock *B = Block;
SmallVector<Stmt *, 8> Used(
OMPExecutableDirective::used_clauses_children(D->clauses()));
for (Stmt *S : llvm::reverse(Used)) {
assert(S && "Expected non-null used-in-clause child.");
if (CFGBlock *R = Visit(S))
B = R;
}
if (!D->isStandaloneDirective()) {
Stmt *S = D->getRawStmt();
if (!isa<CompoundStmt>(S))
addLocalScopeAndDtors(S);
if (CFGBlock *R = addStmt(S))
B = R;
}
return B;
}
CFGBlock *CFG::createBlock() {
bool first_block = begin() == end();
CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Blocks.push_back(Mem, BlkBVC);
if (first_block)
Entry = Exit = &back();
return &back();
}
std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
ASTContext *C, const BuildOptions &BO) {
CFGBuilder Builder(C, BO);
return Builder.buildCFG(D, Statement);
}
bool CFG::isLinear() const {
if (size() <= 3)
return true;
llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
const CFGBlock *B = Entry;
while (B != Exit) {
auto IteratorAndFlag = Visited.insert(B);
if (!IteratorAndFlag.second) {
return false;
}
const CFGBlock *FirstReachableB = nullptr;
for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
if (!AB.isReachable())
continue;
if (FirstReachableB == nullptr) {
FirstReachableB = &*AB;
} else {
return false;
}
}
if (!FirstReachableB) {
return true;
}
B = FirstReachableB;
}
return true;
}
const CXXDestructorDecl *
CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
switch (getKind()) {
case CFGElement::Initializer:
case CFGElement::NewAllocator:
case CFGElement::LoopExit:
case CFGElement::LifetimeEnds:
case CFGElement::Statement:
case CFGElement::Constructor:
case CFGElement::CXXRecordTypedCall:
case CFGElement::ScopeBegin:
case CFGElement::ScopeEnd:
llvm_unreachable("getDestructorDecl should only be used with "
"ImplicitDtors");
case CFGElement::AutomaticObjectDtor: {
const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
QualType ty = var->getType();
if (ty->isReferenceType()) {
if (const Expr *Init = var->getInit()) {
ty = getReferenceInitTemporaryType(Init);
}
}
while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
ty = arrayType->getElementType();
}
const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
assert(classDecl);
return classDecl->getDestructor();
}
case CFGElement::DeleteDtor: {
const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
QualType DTy = DE->getDestroyedType();
DTy = DTy.getNonReferenceType();
const CXXRecordDecl *classDecl =
astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
return classDecl->getDestructor();
}
case CFGElement::TemporaryDtor: {
const CXXBindTemporaryExpr *bindExpr =
castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
const CXXTemporary *temp = bindExpr->getTemporary();
return temp->getDestructor();
}
case CFGElement::BaseDtor:
case CFGElement::MemberDtor:
return nullptr;
}
llvm_unreachable("getKind() returned bogus value");
}
CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
: ReachableBlock(IsReachable ? B : nullptr),
UnreachableBlock(!IsReachable ? B : nullptr,
B && IsReachable ? AB_Normal : AB_Unreachable) {}
CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
: ReachableBlock(B),
UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
B == AlternateBlock ? AB_Alternate : AB_Normal) {}
void CFGBlock::addSuccessor(AdjacentBlock Succ,
BumpVectorContext &C) {
if (CFGBlock *B = Succ.getReachableBlock())
B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Succs.push_back(Succ, C);
}
bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
const CFGBlock *From, const CFGBlock *To) {
if (F.IgnoreNullPredecessors && !From)
return true;
if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
if (const SwitchStmt *S =
dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
if (S->isAllEnumCasesCovered()) {
const Stmt *L = To->getLabel();
if (!L || !isa<CaseStmt>(L))
return true;
}
}
}
return false;
}
namespace {
class StmtPrinterHelper : public PrinterHelper {
using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
StmtMapTy StmtMap;
DeclMapTy DeclMap;
signed currentBlock = 0;
unsigned currStmt = 0;
const LangOptions &LangOpts;
public:
StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
: LangOpts(LO) {
if (!cfg)
return;
for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
unsigned j = 1;
for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
BI != BEnd; ++BI, ++j ) {
if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
const Stmt *stmt= SE->getStmt();
std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
StmtMap[stmt] = P;
switch (stmt->getStmtClass()) {
case Stmt::DeclStmtClass:
DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
break;
case Stmt::IfStmtClass: {
const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
if (var)
DeclMap[var] = P;
break;
}
case Stmt::ForStmtClass: {
const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
if (var)
DeclMap[var] = P;
break;
}
case Stmt::WhileStmtClass: {
const VarDecl *var =
cast<WhileStmt>(stmt)->getConditionVariable();
if (var)
DeclMap[var] = P;
break;
}
case Stmt::SwitchStmtClass: {
const VarDecl *var =
cast<SwitchStmt>(stmt)->getConditionVariable();
if (var)
DeclMap[var] = P;
break;
}
case Stmt::CXXCatchStmtClass: {
const VarDecl *var =
cast<CXXCatchStmt>(stmt)->getExceptionDecl();
if (var)
DeclMap[var] = P;
break;
}
default:
break;
}
}
}
}
}
~StmtPrinterHelper() override = default;
const LangOptions &getLangOpts() const { return LangOpts; }
void setBlockID(signed i) { currentBlock = i; }
void setStmtID(unsigned i) { currStmt = i; }
bool handledStmt(Stmt *S, raw_ostream &OS) override {
StmtMapTy::iterator I = StmtMap.find(S);
if (I == StmtMap.end())
return false;
if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
&& I->second.second == currStmt) {
return false;
}
OS << "[B" << I->second.first << "." << I->second.second << "]";
return true;
}
bool handleDecl(const Decl *D, raw_ostream &OS) {
DeclMapTy::iterator I = DeclMap.find(D);
if (I == DeclMap.end())
return false;
if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
&& I->second.second == currStmt) {
return false;
}
OS << "[B" << I->second.first << "." << I->second.second << "]";
return true;
}
};
class CFGBlockTerminatorPrint
: public StmtVisitor<CFGBlockTerminatorPrint,void> {
raw_ostream &OS;
StmtPrinterHelper* Helper;
PrintingPolicy Policy;
public:
CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
const PrintingPolicy &Policy)
: OS(os), Helper(helper), Policy(Policy) {
this->Policy.IncludeNewlines = false;
}
void VisitIfStmt(IfStmt *I) {
OS << "if ";
if (Stmt *C = I->getCond())
C->printPretty(OS, Helper, Policy);
}
void VisitStmt(Stmt *Terminator) {
Terminator->printPretty(OS, Helper, Policy);
}
void VisitDeclStmt(DeclStmt *DS) {
VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
OS << "static init " << VD->getName();
}
void VisitForStmt(ForStmt *F) {
OS << "for (" ;
if (F->getInit())
OS << "...";
OS << "; ";
if (Stmt *C = F->getCond())
C->printPretty(OS, Helper, Policy);
OS << "; ";
if (F->getInc())
OS << "...";
OS << ")";
}
void VisitWhileStmt(WhileStmt *W) {
OS << "while " ;
if (Stmt *C = W->getCond())
C->printPretty(OS, Helper, Policy);
}
void VisitDoStmt(DoStmt *D) {
OS << "do ... while ";
if (Stmt *C = D->getCond())
C->printPretty(OS, Helper, Policy);
}
void VisitSwitchStmt(SwitchStmt *Terminator) {
OS << "switch ";
Terminator->getCond()->printPretty(OS, Helper, Policy);
}
void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; }
void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; }
void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; }
void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
if (Stmt *Cond = C->getCond())
Cond->printPretty(OS, Helper, Policy);
OS << " ? ... : ...";
}
void VisitChooseExpr(ChooseExpr *C) {
OS << "__builtin_choose_expr( ";
if (Stmt *Cond = C->getCond())
Cond->printPretty(OS, Helper, Policy);
OS << " )";
}
void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
OS << "goto *";
if (Stmt *T = I->getTarget())
T->printPretty(OS, Helper, Policy);
}
void VisitBinaryOperator(BinaryOperator* B) {
if (!B->isLogicalOp()) {
VisitExpr(B);
return;
}
if (B->getLHS())
B->getLHS()->printPretty(OS, Helper, Policy);
switch (B->getOpcode()) {
case BO_LOr:
OS << " || ...";
return;
case BO_LAnd:
OS << " && ...";
return;
default:
llvm_unreachable("Invalid logical operator.");
}
}
void VisitExpr(Expr *E) {
E->printPretty(OS, Helper, Policy);
}
public:
void print(CFGTerminator T) {
switch (T.getKind()) {
case CFGTerminator::StmtBranch:
Visit(T.getStmt());
break;
case CFGTerminator::TemporaryDtorsBranch:
OS << "(Temp Dtor) ";
Visit(T.getStmt());
break;
case CFGTerminator::VirtualBaseBranch:
OS << "(See if most derived ctor has already initialized vbases)";
break;
}
}
};
}
static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
const CXXCtorInitializer *I) {
if (I->isBaseInitializer())
OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
else if (I->isDelegatingInitializer())
OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
else
OS << I->getAnyMember()->getName();
OS << "(";
if (Expr *IE = I->getInit())
IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
OS << ")";
if (I->isBaseInitializer())
OS << " (Base initializer)";
else if (I->isDelegatingInitializer())
OS << " (Delegating initializer)";
else
OS << " (Member initializer)";
}
static void print_construction_context(raw_ostream &OS,
StmtPrinterHelper &Helper,
const ConstructionContext *CC) {
SmallVector<const Stmt *, 3> Stmts;
switch (CC->getKind()) {
case ConstructionContext::SimpleConstructorInitializerKind: {
OS << ", ";
const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
return;
}
case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
OS << ", ";
const auto *CICC =
cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
Stmts.push_back(CICC->getCXXBindTemporaryExpr());
break;
}
case ConstructionContext::SimpleVariableKind: {
const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
Stmts.push_back(SDSCC->getDeclStmt());
break;
}
case ConstructionContext::CXX17ElidedCopyVariableKind: {
const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
Stmts.push_back(CDSCC->getDeclStmt());
Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
break;
}
case ConstructionContext::NewAllocatedObjectKind: {
const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
Stmts.push_back(NECC->getCXXNewExpr());
break;
}
case ConstructionContext::SimpleReturnedValueKind: {
const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
Stmts.push_back(RSCC->getReturnStmt());
break;
}
case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
const auto *RSCC =
cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
Stmts.push_back(RSCC->getReturnStmt());
Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
break;
}
case ConstructionContext::SimpleTemporaryObjectKind: {
const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
break;
}
case ConstructionContext::ElidedTemporaryObjectKind: {
const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
Stmts.push_back(TOCC->getConstructorAfterElision());
break;
}
case ConstructionContext::LambdaCaptureKind: {
const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
Helper.handledStmt(const_cast<LambdaExpr *>(LCC->getLambdaExpr()), OS);
OS << "+" << LCC->getIndex();
return;
}
case ConstructionContext::ArgumentKind: {
const auto *ACC = cast<ArgumentConstructionContext>(CC);
if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
OS << ", ";
Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
}
OS << ", ";
Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
OS << "+" << ACC->getIndex();
return;
}
}
for (auto I: Stmts)
if (I) {
OS << ", ";
Helper.handledStmt(const_cast<Stmt *>(I), OS);
}
}
static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
const CFGElement &E);
void CFGElement::dumpToStream(llvm::raw_ostream &OS) const {
StmtPrinterHelper Helper(nullptr, {});
print_elem(OS, Helper, *this);
}
static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
const CFGElement &E) {
switch (E.getKind()) {
case CFGElement::Kind::Statement:
case CFGElement::Kind::CXXRecordTypedCall:
case CFGElement::Kind::Constructor: {
CFGStmt CS = E.castAs<CFGStmt>();
const Stmt *S = CS.getStmt();
assert(S != nullptr && "Expecting non-null Stmt");
if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
const CompoundStmt *Sub = SE->getSubStmt();
auto Children = Sub->children();
if (Children.begin() != Children.end()) {
OS << "({ ... ; ";
Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
OS << " })\n";
return;
}
}
if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
if (B->getOpcode() == BO_Comma) {
OS << "... , ";
Helper.handledStmt(B->getRHS(),OS);
OS << '\n';
return;
}
}
S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
if (isa<CXXOperatorCallExpr>(S))
OS << " (OperatorCall)";
OS << " (CXXRecordTypedCall";
print_construction_context(OS, Helper, VTC->getConstructionContext());
OS << ")";
} else if (isa<CXXOperatorCallExpr>(S)) {
OS << " (OperatorCall)";
} else if (isa<CXXBindTemporaryExpr>(S)) {
OS << " (BindTemporary)";
} else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
OS << " (CXXConstructExpr";
if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
print_construction_context(OS, Helper, CE->getConstructionContext());
}
OS << ", " << CCE->getType() << ")";
} else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName()
<< ", " << CE->getType() << ")";
}
if (isa<Expr>(S))
OS << '\n';
break;
}
case CFGElement::Kind::Initializer:
print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer());
OS << '\n';
break;
case CFGElement::Kind::AutomaticObjectDtor: {
CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
const VarDecl *VD = DE.getVarDecl();
Helper.handleDecl(VD, OS);
QualType T = VD->getType();
if (T->isReferenceType())
T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
OS << ".~";
T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
OS << "() (Implicit destructor)\n";
break;
}
case CFGElement::Kind::LifetimeEnds:
Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
OS << " (Lifetime ends)\n";
break;
case CFGElement::Kind::LoopExit:
OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
break;
case CFGElement::Kind::ScopeBegin:
OS << "CFGScopeBegin(";
if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
OS << VD->getQualifiedNameAsString();
OS << ")\n";
break;
case CFGElement::Kind::ScopeEnd:
OS << "CFGScopeEnd(";
if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
OS << VD->getQualifiedNameAsString();
OS << ")\n";
break;
case CFGElement::Kind::NewAllocator:
OS << "CFGNewAllocator(";
if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
OS << ")\n";
break;
case CFGElement::Kind::DeleteDtor: {
CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
const CXXRecordDecl *RD = DE.getCXXRecordDecl();
if (!RD)
return;
CXXDeleteExpr *DelExpr =
const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
OS << "->~" << RD->getName().str() << "()";
OS << " (Implicit destructor)\n";
break;
}
case CFGElement::Kind::BaseDtor: {
const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
OS << " (Base object destructor)\n";
break;
}
case CFGElement::Kind::MemberDtor: {
const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
const Type *T = FD->getType()->getBaseElementTypeUnsafe();
OS << "this->" << FD->getName();
OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
OS << " (Member object destructor)\n";
break;
}
case CFGElement::Kind::TemporaryDtor: {
const CXXBindTemporaryExpr *BT =
E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
OS << "~";
BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
OS << "() (Temporary object destructor)\n";
break;
}
}
}
static void print_block(raw_ostream &OS, const CFG* cfg,
const CFGBlock &B,
StmtPrinterHelper &Helper, bool print_edges,
bool ShowColors) {
Helper.setBlockID(B.getBlockID());
if (ShowColors)
OS.changeColor(raw_ostream::YELLOW, true);
OS << "\n [B" << B.getBlockID();
if (&B == &cfg->getEntry())
OS << " (ENTRY)]\n";
else if (&B == &cfg->getExit())
OS << " (EXIT)]\n";
else if (&B == cfg->getIndirectGotoBlock())
OS << " (INDIRECT GOTO DISPATCH)]\n";
else if (B.hasNoReturnElement())
OS << " (NORETURN)]\n";
else
OS << "]\n";
if (ShowColors)
OS.resetColor();
if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
if (print_edges)
OS << " ";
if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
OS << L->getName();
else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
OS << "case ";
if (const Expr *LHS = C->getLHS())
LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
if (const Expr *RHS = C->getRHS()) {
OS << " ... ";
RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
}
} else if (isa<DefaultStmt>(Label))
OS << "default";
else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
OS << "catch (";
if (const VarDecl *ED = CS->getExceptionDecl())
ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
else
OS << "...";
OS << ")";
} else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Label)) {
OS << "@catch (";
if (const VarDecl *PD = CS->getCatchParamDecl())
PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
else
OS << "...";
OS << ")";
} else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
OS << "__except (";
ES->getFilterExpr()->printPretty(OS, &Helper,
PrintingPolicy(Helper.getLangOpts()), 0);
OS << ")";
} else
llvm_unreachable("Invalid label statement in CFGBlock.");
OS << ":\n";
}
unsigned j = 1;
for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
I != E ; ++I, ++j ) {
if (print_edges)
OS << " ";
OS << llvm::format("%3d", j) << ": ";
Helper.setStmtID(j);
print_elem(OS, Helper, *I);
}
if (B.getTerminator().isValid()) {
if (ShowColors)
OS.changeColor(raw_ostream::GREEN);
OS << " T: ";
Helper.setBlockID(-1);
PrintingPolicy PP(Helper.getLangOpts());
CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
TPrinter.print(B.getTerminator());
OS << '\n';
if (ShowColors)
OS.resetColor();
}
if (print_edges) {
if (!B.pred_empty()) {
const raw_ostream::Colors Color = raw_ostream::BLUE;
if (ShowColors)
OS.changeColor(Color);
OS << " Preds " ;
if (ShowColors)
OS.resetColor();
OS << '(' << B.pred_size() << "):";
unsigned i = 0;
if (ShowColors)
OS.changeColor(Color);
for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
I != E; ++I, ++i) {
if (i % 10 == 8)
OS << "\n ";
CFGBlock *B = *I;
bool Reachable = true;
if (!B) {
Reachable = false;
B = I->getPossiblyUnreachableBlock();
}
OS << " B" << B->getBlockID();
if (!Reachable)
OS << "(Unreachable)";
}
if (ShowColors)
OS.resetColor();
OS << '\n';
}
if (!B.succ_empty()) {
const raw_ostream::Colors Color = raw_ostream::MAGENTA;
if (ShowColors)
OS.changeColor(Color);
OS << " Succs ";
if (ShowColors)
OS.resetColor();
OS << '(' << B.succ_size() << "):";
unsigned i = 0;
if (ShowColors)
OS.changeColor(Color);
for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
I != E; ++I, ++i) {
if (i % 10 == 8)
OS << "\n ";
CFGBlock *B = *I;
bool Reachable = true;
if (!B) {
Reachable = false;
B = I->getPossiblyUnreachableBlock();
}
if (B) {
OS << " B" << B->getBlockID();
if (!Reachable)
OS << "(Unreachable)";
}
else {
OS << " NULL";
}
}
if (ShowColors)
OS.resetColor();
OS << '\n';
}
}
}
void CFG::dump(const LangOptions &LO, bool ShowColors) const {
print(llvm::errs(), LO, ShowColors);
}
void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
StmtPrinterHelper Helper(this, LO);
print_block(OS, this, getEntry(), Helper, true, ShowColors);
for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
if (&(**I) == &getEntry() || &(**I) == &getExit())
continue;
print_block(OS, this, **I, Helper, true, ShowColors);
}
print_block(OS, this, getExit(), Helper, true, ShowColors);
OS << '\n';
OS.flush();
}
size_t CFGBlock::getIndexInCFG() const {
return llvm::find(*getParent(), this) - getParent()->begin();
}
void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
bool ShowColors) const {
print(llvm::errs(), cfg, LO, ShowColors);
}
LLVM_DUMP_METHOD void CFGBlock::dump() const {
dump(getParent(), LangOptions(), false);
}
void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
const LangOptions &LO, bool ShowColors) const {
StmtPrinterHelper Helper(cfg, LO);
print_block(OS, cfg, *this, Helper, true, ShowColors);
OS << '\n';
}
void CFGBlock::printTerminator(raw_ostream &OS,
const LangOptions &LO) const {
CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
TPrinter.print(getTerminator());
}
void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
bool AddQuotes) const {
std::string Buf;
llvm::raw_string_ostream TempOut(Buf);
printTerminator(TempOut, LO);
Out << JsonFormat(TempOut.str(), AddQuotes);
}
static bool isImmediateSinkBlock(const CFGBlock *Blk) {
if (Blk->hasNoReturnElement())
return true;
if (llvm::any_of(*Blk, [](const CFGElement &Elm) {
if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
if (isa<CXXThrowExpr>(StmtElm->getStmt()))
return true;
return false;
}))
return true;
return false;
}
bool CFGBlock::isInevitablySinking() const {
const CFG &Cfg = *getParent();
const CFGBlock *StartBlk = this;
if (isImmediateSinkBlock(StartBlk))
return true;
llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
DFSWorkList.push_back(StartBlk);
while (!DFSWorkList.empty()) {
const CFGBlock *Blk = DFSWorkList.back();
DFSWorkList.pop_back();
Visited.insert(Blk);
if (Blk == &Cfg.getExit())
return false;
for (const auto &Succ : Blk->succs()) {
if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
DFSWorkList.push_back(SuccBlk);
}
}
}
}
return true;
}
const Expr *CFGBlock::getLastCondition() const {
if (Terminator.getKind() != CFGTerminator::StmtBranch)
return nullptr;
if (succ_size() < 2)
return nullptr;
if (size() == 0)
return nullptr;
auto StmtElem = rbegin()->getAs<CFGStmt>();
if (!StmtElem)
return nullptr;
const Stmt *Cond = StmtElem->getStmt();
if (isa<ObjCForCollectionStmt>(Cond) || isa<DeclStmt>(Cond))
return nullptr;
return cast<Expr>(Cond)->IgnoreParens();
}
Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Stmt *Terminator = getTerminatorStmt();
if (!Terminator)
return nullptr;
Expr *E = nullptr;
switch (Terminator->getStmtClass()) {
default:
break;
case Stmt::CXXForRangeStmtClass:
E = cast<CXXForRangeStmt>(Terminator)->getCond();
break;
case Stmt::ForStmtClass:
E = cast<ForStmt>(Terminator)->getCond();
break;
case Stmt::WhileStmtClass:
E = cast<WhileStmt>(Terminator)->getCond();
break;
case Stmt::DoStmtClass:
E = cast<DoStmt>(Terminator)->getCond();
break;
case Stmt::IfStmtClass:
E = cast<IfStmt>(Terminator)->getCond();
break;
case Stmt::ChooseExprClass:
E = cast<ChooseExpr>(Terminator)->getCond();
break;
case Stmt::IndirectGotoStmtClass:
E = cast<IndirectGotoStmt>(Terminator)->getTarget();
break;
case Stmt::SwitchStmtClass:
E = cast<SwitchStmt>(Terminator)->getCond();
break;
case Stmt::BinaryConditionalOperatorClass:
E = cast<BinaryConditionalOperator>(Terminator)->getCond();
break;
case Stmt::ConditionalOperatorClass:
E = cast<ConditionalOperator>(Terminator)->getCond();
break;
case Stmt::BinaryOperatorClass: E = cast<BinaryOperator>(Terminator)->getLHS();
break;
case Stmt::ObjCForCollectionStmtClass:
return Terminator;
}
if (!StripParens)
return E;
return E ? E->IgnoreParens() : nullptr;
}
static StmtPrinterHelper *GraphHelper;
void CFG::viewCFG(const LangOptions &LO) const {
StmtPrinterHelper H(this, LO);
GraphHelper = &H;
llvm::ViewGraph(this,"CFG");
GraphHelper = nullptr;
}
namespace llvm {
template<>
struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
std::string OutSStr;
llvm::raw_string_ostream Out(OutSStr);
print_block(Out,Graph, *Node, *GraphHelper, false, false);
std::string& OutStr = Out.str();
if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
for (unsigned i = 0; i != OutStr.length(); ++i)
if (OutStr[i] == '\n') { OutStr[i] = '\\';
OutStr.insert(OutStr.begin()+i+1, 'l');
}
return OutStr;
}
};
}