Skip to content

Commit

Permalink
[clang][dataflow] Fix initializing a reference field with an `InitLis…
Browse files Browse the repository at this point in the history
…tExpr`.

I added a test for this as the ongoing migration to strict handling of value categories (see https://discourse.llvm.org/t/70086) will change the code that handles this case. It turns out we already didn't handle this correctly, so I fixed the existing implementation.

Depends On D154961

Reviewed By: xazax.hun

Differential Revision: https://reviews.llvm.org/D154965
  • Loading branch information
martinboehme committed Jul 12, 2023
1 parent b47bdcb commit bd9b57d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
11 changes: 6 additions & 5 deletions clang/lib/Analysis/FlowSensitive/Transfer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -717,14 +717,15 @@ class TransferVisitor : public ConstStmtVisitor<TransferVisitor> {
if (Type->isStructureOrClassType()) {
std::vector<FieldDecl *> Fields =
getFieldsForInitListExpr(Type->getAsRecordDecl());
for (auto It : llvm::zip(Fields, S->inits())) {
const FieldDecl *Field = std::get<0>(It);
for (auto [Field, Init] : llvm::zip(Fields, S->inits())) {
assert(Field != nullptr);

const Expr *Init = std::get<1>(It);
assert(Init != nullptr);

if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
if (Field->getType()->isReferenceType()) {
if (StorageLocation *Loc = Env.getStorageLocationStrict(*Init))
cast<StructValue>(Val)->setChild(*Field,
Env.create<ReferenceValue>(*Loc));
} else if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
cast<StructValue>(Val)->setChild(*Field, *InitVal);
}
}
Expand Down
28 changes: 28 additions & 0 deletions clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2912,6 +2912,34 @@ TEST(TransferTest, AggregateInitialization) {
}
}

TEST(TransferTest, AggregateInitializationReferenceField) {
std::string Code = R"(
struct S {
int &RefField;
};
void target(int i) {
S s = { i };
/*[[p]]*/
}
)";
runDataflow(
Code,
[](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &Results,
ASTContext &ASTCtx) {
const Environment &Env = getEnvironmentAtAnnotation(Results, "p");

const ValueDecl *RefFieldDecl = findValueDecl(ASTCtx, "RefField");

auto &ILoc = getLocForDecl<StorageLocation>(ASTCtx, Env, "i");
auto &SLoc = getLocForDecl<AggregateStorageLocation>(ASTCtx, Env, "s");

auto &RefValue =
*cast<ReferenceValue>(getFieldValue(&SLoc, *RefFieldDecl, Env));
EXPECT_EQ(&RefValue.getReferentLoc(), &ILoc);
});
}

TEST(TransferTest, AssignToUnionMember) {
std::string Code = R"(
union A {
Expand Down

0 comments on commit bd9b57d

Please sign in to comment.