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

[GlobalOpt] Reduction of global aggregate with alignment constraint unnecessarily propagates alignment to some elements

Open brunodf-gf opened this issue 2 years ago • 3 comments

When GlobalOpt performs SRA on a global aggregate with an alignment constraint, it seems to propagate the alignment to some of the elements haphazardly. For example:

alignas(32) static int params[8];

On a plain 32 bit architecture, the array elements respectively have alignment: 32, 4, 8, 4, 16, 4, 8, 4 GlobalOpt SRA creates individual global variables for the elements with respective alignments: 32, 32, 8, 32, 16, 32, 8, 32

I don't see any benefit to increase the alignments elements 1, 3, 5, 7 from 4 to 32. This is wasteful because the new elements cannot be mapped consecutively in memory anymore.

Godbolt demo: https://godbolt.org/z/WjbPjY9Kh

brunodf-gf avatar Nov 07 '24 09:11 brunodf-gf

In my debugging of GlobalOpt, there seems to be some logic flaw in this part:

https://github.com/llvm/llvm-project/blob/2d7f34f2a5df9396a33a0ea044cfe3ddf33e1f5c/llvm/lib/Transforms/IPO/GlobalOpt.cpp#L584-L586

Some lines above NGV has copied all attributes from GV. This includes the alignment. When the calculated NewAlign is not better than the ABI type align, this code seems to retain the original aggregate alignment on the element unintentionally.

@nikic I notice that your commit https://github.com/llvm/llvm-project/commit/4796b4ae7bccc7b75a26b666fbd554c49b274404 increases the expected alignment values in some of the tests such as llvm/test/Transforms/GlobalOpt/globalsra-align.ll. Is that intentional?

brunodf-gf avatar Nov 07 '24 09:11 brunodf-gf

Agree with your analysis. We should be unconditionally setting to something like std::max(NewAlign, DL.getABITypeAlign(Ty)) I think?

nikic avatar Nov 07 '24 10:11 nikic

Agree with your analysis. We should be unconditionally setting to something like std::max(NewAlign, DL.getABITypeAlign(Ty)) I think?

Yes, thanks for confirming. I'll try to create a pull request. It will have to update the expected alignments in some of the tests I think.

brunodf-gf avatar Nov 07 '24 11:11 brunodf-gf