1 //===- LoadCombine.cpp - Combine Adjacent Loads ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This transformation combines adjacent loads.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/TargetFolder.h"
19 #include "llvm/Pass.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/raw_ostream.h"
30 #define DEBUG_TYPE "load-combine"
32 STATISTIC(NumLoadsAnalyzed, "Number of loads analyzed for combining");
33 STATISTIC(NumLoadsCombined, "Number of loads combined");
36 struct PointerOffsetPair {
42 LoadPOPPair(LoadInst *L, PointerOffsetPair P, unsigned O)
43 : Load(L), POP(P), InsertOrder(O) {}
46 PointerOffsetPair POP;
47 /// \brief The new load needs to be created before the first load in IR order.
51 class LoadCombine : public BasicBlockPass {
58 C(nullptr), DL(nullptr) {
59 initializeSROAPass(*PassRegistry::getPassRegistry());
61 bool doInitialization(Function &) override;
62 bool runOnBasicBlock(BasicBlock &BB) override;
63 void getAnalysisUsage(AnalysisUsage &AU) const override;
65 const char *getPassName() const override { return "LoadCombine"; }
68 typedef IRBuilder<true, TargetFolder> BuilderTy;
73 PointerOffsetPair getPointerOffsetPair(LoadInst &);
74 bool combineLoads(DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &);
75 bool aggregateLoads(SmallVectorImpl<LoadPOPPair> &);
76 bool combineLoads(SmallVectorImpl<LoadPOPPair> &);
80 bool LoadCombine::doInitialization(Function &F) {
81 DEBUG(dbgs() << "LoadCombine function: " << F.getName() << "\n");
83 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
85 DEBUG(dbgs() << " Skipping LoadCombine -- no target data!\n");
88 DL = &DLP->getDataLayout();
92 PointerOffsetPair LoadCombine::getPointerOffsetPair(LoadInst &LI) {
93 PointerOffsetPair POP;
94 POP.Pointer = LI.getPointerOperand();
96 while (isa<BitCastInst>(POP.Pointer) || isa<GetElementPtrInst>(POP.Pointer)) {
97 if (auto *GEP = dyn_cast<GetElementPtrInst>(POP.Pointer)) {
98 unsigned BitWidth = DL->getPointerTypeSizeInBits(GEP->getType());
99 APInt Offset(BitWidth, 0);
100 if (GEP->accumulateConstantOffset(*DL, Offset))
101 POP.Offset += Offset.getZExtValue();
103 // Can't handle GEPs with variable indices.
105 POP.Pointer = GEP->getPointerOperand();
106 } else if (auto *BC = dyn_cast<BitCastInst>(POP.Pointer))
107 POP.Pointer = BC->getOperand(0);
112 bool LoadCombine::combineLoads(
113 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &LoadMap) {
114 bool Combined = false;
115 for (auto &Loads : LoadMap) {
116 if (Loads.second.size() < 2)
118 std::sort(Loads.second.begin(), Loads.second.end(),
119 [](const LoadPOPPair &A, const LoadPOPPair &B) {
120 return A.POP.Offset < B.POP.Offset;
122 if (aggregateLoads(Loads.second))
128 /// \brief Try to aggregate loads from a sorted list of loads to be combined.
130 /// It is guaranteed that no writes occur between any of the loads. All loads
131 /// have the same base pointer. There are at least two loads.
132 bool LoadCombine::aggregateLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
133 assert(Loads.size() >= 2 && "Insufficient loads!");
134 LoadInst *BaseLoad = nullptr;
135 SmallVector<LoadPOPPair, 8> AggregateLoads;
136 bool Combined = false;
137 uint64_t PrevOffset = -1ull;
138 uint64_t PrevSize = 0;
139 for (auto &L : Loads) {
140 if (PrevOffset == -1ull) {
142 PrevOffset = L.POP.Offset;
143 PrevSize = DL->getTypeStoreSize(L.Load->getType());
144 AggregateLoads.push_back(L);
147 if (L.Load->getAlignment() > BaseLoad->getAlignment())
149 if (L.POP.Offset > PrevOffset + PrevSize) {
150 // No other load will be combinable
151 if (combineLoads(AggregateLoads))
153 AggregateLoads.clear();
157 if (L.POP.Offset != PrevOffset + PrevSize)
158 // This load is offset less than the size of the last load.
159 // FIXME: We may want to handle this case.
161 PrevOffset = L.POP.Offset;
162 PrevSize = DL->getTypeStoreSize(L.Load->getType());
163 AggregateLoads.push_back(L);
165 if (combineLoads(AggregateLoads))
170 /// \brief Given a list of combinable load. Combine the maximum number of them.
171 bool LoadCombine::combineLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
172 // Remove loads from the end while the size is not a power of 2.
173 unsigned TotalSize = 0;
174 for (const auto &L : Loads)
175 TotalSize += L.Load->getType()->getPrimitiveSizeInBits();
176 while (TotalSize != 0 && !isPowerOf2_32(TotalSize))
177 TotalSize -= Loads.pop_back_val().Load->getType()->getPrimitiveSizeInBits();
178 if (Loads.size() < 2)
182 dbgs() << "***** Combining Loads ******\n";
183 for (const auto &L : Loads) {
184 dbgs() << L.POP.Offset << ": " << *L.Load << "\n";
188 // Find first load. This is where we put the new load.
190 FirstLP.InsertOrder = -1u;
191 for (const auto &L : Loads)
192 if (L.InsertOrder < FirstLP.InsertOrder)
195 unsigned AddressSpace =
196 FirstLP.POP.Pointer->getType()->getPointerAddressSpace();
198 Builder->SetInsertPoint(FirstLP.Load);
199 Value *Ptr = Builder->CreateConstGEP1_64(
200 Builder->CreatePointerCast(Loads[0].POP.Pointer,
201 Builder->getInt8PtrTy(AddressSpace)),
202 Loads[0].POP.Offset);
203 LoadInst *NewLoad = new LoadInst(
204 Builder->CreatePointerCast(
205 Ptr, PointerType::get(IntegerType::get(Ptr->getContext(), TotalSize),
206 Ptr->getType()->getPointerAddressSpace())),
207 Twine(Loads[0].Load->getName()) + ".combined", false,
208 Loads[0].Load->getAlignment(), FirstLP.Load);
210 for (const auto &L : Loads) {
211 Builder->SetInsertPoint(L.Load);
212 Value *V = Builder->CreateExtractInteger(
213 *DL, NewLoad, cast<IntegerType>(L.Load->getType()),
214 L.POP.Offset - Loads[0].POP.Offset, "combine.extract");
215 L.Load->replaceAllUsesWith(V);
218 NumLoadsCombined = NumLoadsCombined + Loads.size();
222 bool LoadCombine::runOnBasicBlock(BasicBlock &BB) {
223 if (skipOptnoneFunction(BB) || !DL)
226 IRBuilder<true, TargetFolder>
227 TheBuilder(BB.getContext(), TargetFolder(DL));
228 Builder = &TheBuilder;
230 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> LoadMap;
232 bool Combined = false;
235 if (I.mayWriteToMemory() || I.mayThrow()) {
236 if (combineLoads(LoadMap))
241 LoadInst *LI = dyn_cast<LoadInst>(&I);
245 if (!LI->isSimple() || !LI->getType()->isIntegerTy())
247 auto POP = getPointerOffsetPair(*LI);
250 LoadMap[POP.Pointer].push_back(LoadPOPPair(LI, POP, Index++));
252 if (combineLoads(LoadMap))
257 void LoadCombine::getAnalysisUsage(AnalysisUsage &AU) const {
258 AU.setPreservesCFG();
261 char LoadCombine::ID = 0;
263 BasicBlockPass *llvm::createLoadCombinePass() {
264 return new LoadCombine();
267 INITIALIZE_PASS(LoadCombine, "load-combine", "Combine Adjacent Loads", false,