Skip to content

Commit 38e962d

Browse files
yugrlanza
authored andcommitted
[CIR][CodeGen] Fix flat offset lowering code to consider field alignments.
Before this fix conversion of flat offset to GlobalView indices could crash or compute invalid result.
1 parent a7a64ed commit 38e962d

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

clang/lib/CIR/CodeGen/CIRGenBuilder.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -754,14 +754,18 @@ class CIRGenBuilderTy : public CIRBaseBuilderTy {
754754
Offset %= EltSize;
755755
} else if (auto StructTy = Ty.dyn_cast<mlir::cir::StructType>()) {
756756
auto Elts = StructTy.getMembers();
757+
unsigned Pos = 0;
757758
for (size_t I = 0; I < Elts.size(); ++I) {
758759
auto EltSize = Layout.getTypeAllocSize(Elts[I]);
759-
if (Offset < EltSize) {
760+
unsigned AlignMask = Layout.getABITypeAlign(Elts[I]) - 1;
761+
Pos = (Pos + AlignMask) & ~AlignMask;
762+
if (Offset < Pos + EltSize) {
760763
Indices.push_back(I);
761764
SubType = Elts[I];
765+
Offset -= Pos;
762766
break;
763767
}
764-
Offset -= EltSize;
768+
Pos += EltSize;
765769
}
766770
} else {
767771
llvm_unreachable("unexpected type");

clang/test/CIR/CodeGen/globals.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ int foo() {
8383
// CHECK: cir.func {{.*@foo}}
8484
// CHECK: {{.*}} = cir.get_global @optind : cir.ptr <!s32i>
8585

86+
struct Glob {
87+
double a[42];
88+
int pad1[3];
89+
double b[42];
90+
} glob;
91+
92+
double *const glob_ptr = &glob.b[1];
93+
// CHECK: cir.global external @glob_ptr = #cir.global_view<@glob, [2 : i32, 1 : i32]> : !cir.ptr<f64>
94+
8695
// TODO: test tentatives with internal linkage.
8796

8897
// Tentative definition is THE definition. Should be zero-initialized.

0 commit comments

Comments
 (0)