[DAGCombiner] Match load by bytes idiom and fold it into a single load
authorArtur Pilipenko <apilipenko@azulsystems.com>
Tue, 13 Dec 2016 14:21:14 +0000 (14:21 +0000)
committerArtur Pilipenko <apilipenko@azulsystems.com>
Tue, 13 Dec 2016 14:21:14 +0000 (14:21 +0000)
commitc93cc5955f5b93e12f52f50f3ed47ef48cc13726
tree73fa88187e34ffd17a694ce2125b15d11cdb06a4
parent01e86444a0e5241b8be4b90dd041b2292035b75e
[DAGCombiner] Match load by bytes idiom and fold it into a single load

Match a pattern where a wide type scalar value is loaded by several narrow loads and combined by shifts and ors. Fold it into a single load or a load and a bswap if the targets supports it.

Assuming little endian target:
  i8 *a = ...
  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
=>
  i32 val = *((i32)a)

  i8 *a = ...
  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
=>
  i32 val = BSWAP(*((i32)a))

This optimization was discussed on llvm-dev some time ago in "Load combine pass" thread. We came to the conclusion that we want to do this transformation late in the pipeline because in presence of atomic loads load widening is irreversible transformation and it might hinder other optimizations.

Eventually we'd like to support folding patterns like this where the offset has a variable and a constant part:
  i32 val = a[i] | (a[i + 1] << 8) | (a[i + 2] << 16) | (a[i + 3] << 24)

Matching the pattern above is easier at SelectionDAG level since address reassociation has already happened and the fact that the loads are adjacent is clear. Understanding that these loads are adjacent at IR level would have involved looking through geps/zexts/adds while looking at the addresses.

The general scheme is to match OR expressions by recursively calculating the origin of individual bits which constitute the resulting OR value. If all the OR bits come from memory verify that they are adjacent and match with little or big endian encoding of a wider value. If so and the load of the wider type (and bswap if needed) is allowed by the target generate a load and a bswap if needed.

Reviewed By: hfinkel, RKSimon, filcab

Differential Revision: https://reviews.llvm.org/D26149

llvm-svn: 289538
llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
llvm/test/CodeGen/ARM/load-combine-big-endian.ll [new file with mode: 0644]
llvm/test/CodeGen/ARM/load-combine.ll [new file with mode: 0644]
llvm/test/CodeGen/X86/load-combine.ll [new file with mode: 0644]