llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[X64] Inst combine Pass bug - Incorrect combining lost memory de-reference

Open IshwaraK opened this issue 1 year ago • 1 comments

The inst-combine is doing incorrect combining for the below code. Instead of de-referencing and then accessing the memory, it did offset addition and accessed wrong memory address.

The CE link is here https://godbolt.org/z/G8e6GrKW8

typedef unsigned char ub1;
typedef unsigned short ub2;
typedef unsigned int ub4;
typedef int boolean;

struct spStruct
{
  ub4 phySize;
  void *hSize;
};
typedef struct spStruct spStruct;

struct kccStruct {
  ub4 kfhdbi;
  ub4 kfhcsq;
  ub4 kfhfsz; // till here size = 12 bytes
  ub4 kbsz; 
}; // Size = 16 bytes
typedef struct kccStruct kccStruct;

struct kBlkStruct
{
  kccStruct fh_blk;
  ub4 offset;
  ub4 amount;
  ub4 modtime;
};
typedef struct kBlkStruct kBlkStruct;

struct kStruct {
   ub1 tVar1;
   ub1 tVar2;
   ub2 tVar3;
   ub4 tVar4;
}; // size = 8 bytes
typedef struct kStruct kStruct;

void foo(spStruct *spPointer) {
  spPointer->phySize =
      ((kBlkStruct *)((ub1 *)spPointer->hSize + sizeof(kStruct)))
           ->fh_blk.kbsz;
}

define dso_local void @foo(spStruct*)(ptr nocapture noundef initializes((0, 4)) %0) local_unnamed_addr #0 !dbg !32 {
    #dbg_value(ptr %0, !43, !DIExpression(), !44)
  %2 = getelementptr inbounds nuw i8, ptr %0, i64 8, !dbg !45
  %3 = load ptr, ptr %2, align 8, !dbg !45
  %4 = getelementptr inbounds nuw i8, ptr %3, i64 20, !dbg !52 ; <---- Wrong, lost de-referencing via (kBlkStruct *); instead combined offset addition as 8 + 12 = 20 bytes. This lead to wrong memory slot
  %5 = load i32, ptr %4, align 4, !dbg !52
  store i32 %5, ptr %0, align 8, !dbg !56
  ret void, !dbg !58
}

IshwaraK avatar Mar 25 '25 13:03 IshwaraK

GEP calculation looks correct to me: sizeof(kStruct) + offsetof(kBlkStruct, fh_blk.kbsz) = 8 + 12 starting from hSize. Alive2 still reports a miscompilation though: https://alive2.llvm.org/ce/z/opkSK7. Seems like we incorrectly infer initializes((0, 4)) for this function.

antoniofrighetto avatar Mar 25 '25 15:03 antoniofrighetto