Skip to content

Invalid IR when accessing union #224

@yugr

Description

@yugr

This code

typedef union {                                                                 
  char x;                                                                       
  struct {                                                                      
    short h, l;                                                                 
  } b;                                                                          
} T;                                                                            
                                                                                
void foo(T reg) {                                                               
  reg.b.l;                                                                      
}                                                                               

currently generates invalid IR:

$ ~/src/clangir/build/bin/clang -fclangir-enable -emit-llvm -S tmp.c
loc("tmp.c":4:14): error: 'llvm.getelementptr' op index 1 indexing a struct is out of bounds

It seems that we are missing a bitcast in buildLValueForField and code even has a comment about this:

  // TODO(CIR): CodeGen requires a bitcast here for unions or for structs where 
  // the LLVM type doesn't match the desired type. No idea when the latter might
  // occur, though.                                                             

Indeed adding

  if (rec->isUnion()) {
    auto memTy = getTypes().convertTypeForMem(FieldType);
    addr = builder.createElementBitCast(getLoc(field->getSourceRange()), addr, memTy);
  }

fixes the problem.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions