Skip to content

Commit

Permalink
[CIR][CodeGen] Fix flat offset lowering code to consider field alignm…
Browse files Browse the repository at this point in the history
…ents.

Before this fix conversion of flat offset to GlobalView indices could
crash or compute invalid result.
  • Loading branch information
yugr authored and lanza committed Dec 22, 2023
1 parent a7a64ed commit 38e962d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 6 additions & 2 deletions clang/lib/CIR/CodeGen/CIRGenBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -754,14 +754,18 @@ class CIRGenBuilderTy : public CIRBaseBuilderTy {
Offset %= EltSize;
} else if (auto StructTy = Ty.dyn_cast<mlir::cir::StructType>()) {
auto Elts = StructTy.getMembers();
unsigned Pos = 0;
for (size_t I = 0; I < Elts.size(); ++I) {
auto EltSize = Layout.getTypeAllocSize(Elts[I]);
if (Offset < EltSize) {
unsigned AlignMask = Layout.getABITypeAlign(Elts[I]) - 1;
Pos = (Pos + AlignMask) & ~AlignMask;
if (Offset < Pos + EltSize) {
Indices.push_back(I);
SubType = Elts[I];
Offset -= Pos;
break;
}
Offset -= EltSize;
Pos += EltSize;
}
} else {
llvm_unreachable("unexpected type");
Expand Down
9 changes: 9 additions & 0 deletions clang/test/CIR/CodeGen/globals.c
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,15 @@ int foo() {
// CHECK: cir.func {{.*@foo}}
// CHECK: {{.*}} = cir.get_global @optind : cir.ptr <!s32i>

struct Glob {
double a[42];
int pad1[3];
double b[42];
} glob;

double *const glob_ptr = &glob.b[1];
// CHECK: cir.global external @glob_ptr = #cir.global_view<@glob, [2 : i32, 1 : i32]> : !cir.ptr<f64>

// TODO: test tentatives with internal linkage.

// Tentative definition is THE definition. Should be zero-initialized.
Expand Down

0 comments on commit 38e962d

Please sign in to comment.