blob: 61b7804b59b2342c5156c93f00aa3c37b9d8ba45 [file] [log] [blame]
Michael J. Spencer289067c2014-05-29 01:55:07 +00001//===- LoadCombine.cpp - Combine Adjacent Loads ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation combines adjacent loads.
11///
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Scalar.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/Statistic.h"
Hal Finkel840257a2014-11-03 23:19:16 +000017#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/Analysis/AliasSetTracker.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000019#include "llvm/Analysis/GlobalsModRef.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000020#include "llvm/Analysis/TargetFolder.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Function.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000023#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000024#include "llvm/IR/Instructions.h"
Mehdi Amini46a43552015-03-04 18:43:29 +000025#include "llvm/IR/Module.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000026#include "llvm/Pass.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/MathExtras.h"
29#include "llvm/Support/raw_ostream.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "load-combine"
34
35STATISTIC(NumLoadsAnalyzed, "Number of loads analyzed for combining");
36STATISTIC(NumLoadsCombined, "Number of loads combined");
37
Chad Rosier7ab9a7b2016-05-04 15:19:02 +000038#define LDCOMBINE_NAME "Combine Adjacent Loads"
39
Michael J. Spencer289067c2014-05-29 01:55:07 +000040namespace {
41struct PointerOffsetPair {
42 Value *Pointer;
David Majnemer3ffe2dd2016-06-19 21:36:35 +000043 APInt Offset;
Michael J. Spencer289067c2014-05-29 01:55:07 +000044};
45
46struct LoadPOPPair {
Michael J. Spencer289067c2014-05-29 01:55:07 +000047 LoadInst *Load;
48 PointerOffsetPair POP;
49 /// \brief The new load needs to be created before the first load in IR order.
50 unsigned InsertOrder;
51};
52
53class LoadCombine : public BasicBlockPass {
54 LLVMContext *C;
Hal Finkel840257a2014-11-03 23:19:16 +000055 AliasAnalysis *AA;
Michael J. Spencer289067c2014-05-29 01:55:07 +000056
57public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +000058 LoadCombine() : BasicBlockPass(ID), C(nullptr), AA(nullptr) {
Chandler Carruth1688a772015-09-09 09:46:16 +000059 initializeLoadCombinePass(*PassRegistry::getPassRegistry());
Michael J. Spencer289067c2014-05-29 01:55:07 +000060 }
Aaron Ballman573f3b52014-07-30 19:23:59 +000061
62 using llvm::Pass::doInitialization;
Michael J. Spencer289067c2014-05-29 01:55:07 +000063 bool doInitialization(Function &) override;
64 bool runOnBasicBlock(BasicBlock &BB) override;
Davide Italiano84e14142016-06-02 22:04:43 +000065 void getAnalysisUsage(AnalysisUsage &AU) const override {
66 AU.setPreservesCFG();
67 AU.addRequired<AAResultsWrapperPass>();
68 AU.addPreserved<GlobalsAAWrapperPass>();
69 }
Michael J. Spencer289067c2014-05-29 01:55:07 +000070
Mehdi Amini117296c2016-10-01 02:56:57 +000071 StringRef getPassName() const override { return LDCOMBINE_NAME; }
Michael J. Spencer289067c2014-05-29 01:55:07 +000072 static char ID;
73
Mehdi Aminiba9fba82016-03-13 21:05:13 +000074 typedef IRBuilder<TargetFolder> BuilderTy;
Michael J. Spencer289067c2014-05-29 01:55:07 +000075
76private:
77 BuilderTy *Builder;
78
79 PointerOffsetPair getPointerOffsetPair(LoadInst &);
80 bool combineLoads(DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &);
81 bool aggregateLoads(SmallVectorImpl<LoadPOPPair> &);
82 bool combineLoads(SmallVectorImpl<LoadPOPPair> &);
83};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000084}
Michael J. Spencer289067c2014-05-29 01:55:07 +000085
86bool LoadCombine::doInitialization(Function &F) {
87 DEBUG(dbgs() << "LoadCombine function: " << F.getName() << "\n");
88 C = &F.getContext();
Michael J. Spencer289067c2014-05-29 01:55:07 +000089 return true;
90}
91
92PointerOffsetPair LoadCombine::getPointerOffsetPair(LoadInst &LI) {
David Majnemer3ffe2dd2016-06-19 21:36:35 +000093 auto &DL = LI.getModule()->getDataLayout();
94
Michael J. Spencer289067c2014-05-29 01:55:07 +000095 PointerOffsetPair POP;
96 POP.Pointer = LI.getPointerOperand();
David Majnemer3ffe2dd2016-06-19 21:36:35 +000097 unsigned BitWidth = DL.getPointerSizeInBits(LI.getPointerAddressSpace());
98 POP.Offset = APInt(BitWidth, 0);
99
Michael J. Spencer289067c2014-05-29 01:55:07 +0000100 while (isa<BitCastInst>(POP.Pointer) || isa<GetElementPtrInst>(POP.Pointer)) {
101 if (auto *GEP = dyn_cast<GetElementPtrInst>(POP.Pointer)) {
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000102 APInt LastOffset = POP.Offset;
103 if (!GEP->accumulateConstantOffset(DL, POP.Offset)) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000104 // Can't handle GEPs with variable indices.
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000105 POP.Offset = LastOffset;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000106 return POP;
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000107 }
Michael J. Spencer289067c2014-05-29 01:55:07 +0000108 POP.Pointer = GEP->getPointerOperand();
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000109 } else if (auto *BC = dyn_cast<BitCastInst>(POP.Pointer)) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000110 POP.Pointer = BC->getOperand(0);
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000111 }
Michael J. Spencer289067c2014-05-29 01:55:07 +0000112 }
113 return POP;
114}
115
116bool LoadCombine::combineLoads(
117 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &LoadMap) {
118 bool Combined = false;
119 for (auto &Loads : LoadMap) {
120 if (Loads.second.size() < 2)
121 continue;
122 std::sort(Loads.second.begin(), Loads.second.end(),
123 [](const LoadPOPPair &A, const LoadPOPPair &B) {
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000124 return A.POP.Offset.slt(B.POP.Offset);
125 });
Michael J. Spencer289067c2014-05-29 01:55:07 +0000126 if (aggregateLoads(Loads.second))
127 Combined = true;
128 }
129 return Combined;
130}
131
132/// \brief Try to aggregate loads from a sorted list of loads to be combined.
133///
134/// It is guaranteed that no writes occur between any of the loads. All loads
135/// have the same base pointer. There are at least two loads.
136bool LoadCombine::aggregateLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
137 assert(Loads.size() >= 2 && "Insufficient loads!");
138 LoadInst *BaseLoad = nullptr;
139 SmallVector<LoadPOPPair, 8> AggregateLoads;
140 bool Combined = false;
David Majnemer31195992016-06-19 06:14:56 +0000141 bool ValidPrevOffset = false;
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000142 APInt PrevOffset;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000143 uint64_t PrevSize = 0;
144 for (auto &L : Loads) {
David Majnemer31195992016-06-19 06:14:56 +0000145 if (ValidPrevOffset == false) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000146 BaseLoad = L.Load;
147 PrevOffset = L.POP.Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000148 PrevSize = L.Load->getModule()->getDataLayout().getTypeStoreSize(
149 L.Load->getType());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000150 AggregateLoads.push_back(L);
David Majnemer31195992016-06-19 06:14:56 +0000151 ValidPrevOffset = true;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000152 continue;
153 }
154 if (L.Load->getAlignment() > BaseLoad->getAlignment())
155 continue;
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000156 APInt PrevEnd = PrevOffset + PrevSize;
157 if (L.POP.Offset.sgt(PrevEnd)) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000158 // No other load will be combinable
159 if (combineLoads(AggregateLoads))
160 Combined = true;
161 AggregateLoads.clear();
David Majnemer31195992016-06-19 06:14:56 +0000162 ValidPrevOffset = false;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000163 continue;
164 }
David Majnemer31195992016-06-19 06:14:56 +0000165 if (L.POP.Offset != PrevEnd)
Michael J. Spencer289067c2014-05-29 01:55:07 +0000166 // This load is offset less than the size of the last load.
167 // FIXME: We may want to handle this case.
168 continue;
169 PrevOffset = L.POP.Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000170 PrevSize = L.Load->getModule()->getDataLayout().getTypeStoreSize(
171 L.Load->getType());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000172 AggregateLoads.push_back(L);
173 }
174 if (combineLoads(AggregateLoads))
175 Combined = true;
176 return Combined;
177}
178
179/// \brief Given a list of combinable load. Combine the maximum number of them.
180bool LoadCombine::combineLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
181 // Remove loads from the end while the size is not a power of 2.
182 unsigned TotalSize = 0;
183 for (const auto &L : Loads)
184 TotalSize += L.Load->getType()->getPrimitiveSizeInBits();
185 while (TotalSize != 0 && !isPowerOf2_32(TotalSize))
186 TotalSize -= Loads.pop_back_val().Load->getType()->getPrimitiveSizeInBits();
187 if (Loads.size() < 2)
188 return false;
189
190 DEBUG({
191 dbgs() << "***** Combining Loads ******\n";
192 for (const auto &L : Loads) {
193 dbgs() << L.POP.Offset << ": " << *L.Load << "\n";
194 }
195 });
196
197 // Find first load. This is where we put the new load.
198 LoadPOPPair FirstLP;
199 FirstLP.InsertOrder = -1u;
200 for (const auto &L : Loads)
201 if (L.InsertOrder < FirstLP.InsertOrder)
202 FirstLP = L;
203
204 unsigned AddressSpace =
205 FirstLP.POP.Pointer->getType()->getPointerAddressSpace();
206
207 Builder->SetInsertPoint(FirstLP.Load);
208 Value *Ptr = Builder->CreateConstGEP1_64(
209 Builder->CreatePointerCast(Loads[0].POP.Pointer,
210 Builder->getInt8PtrTy(AddressSpace)),
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000211 Loads[0].POP.Offset.getSExtValue());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000212 LoadInst *NewLoad = new LoadInst(
213 Builder->CreatePointerCast(
214 Ptr, PointerType::get(IntegerType::get(Ptr->getContext(), TotalSize),
215 Ptr->getType()->getPointerAddressSpace())),
216 Twine(Loads[0].Load->getName()) + ".combined", false,
217 Loads[0].Load->getAlignment(), FirstLP.Load);
218
219 for (const auto &L : Loads) {
220 Builder->SetInsertPoint(L.Load);
221 Value *V = Builder->CreateExtractInteger(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000222 L.Load->getModule()->getDataLayout(), NewLoad,
223 cast<IntegerType>(L.Load->getType()),
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000224 (L.POP.Offset - Loads[0].POP.Offset).getZExtValue(), "combine.extract");
Michael J. Spencer289067c2014-05-29 01:55:07 +0000225 L.Load->replaceAllUsesWith(V);
226 }
227
228 NumLoadsCombined = NumLoadsCombined + Loads.size();
229 return true;
230}
231
232bool LoadCombine::runOnBasicBlock(BasicBlock &BB) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000233 if (skipBasicBlock(BB))
Michael J. Spencer289067c2014-05-29 01:55:07 +0000234 return false;
235
Chandler Carruth7b560d42015-09-09 17:55:00 +0000236 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Hal Finkel840257a2014-11-03 23:19:16 +0000237
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000238 IRBuilder<TargetFolder> TheBuilder(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000239 BB.getContext(), TargetFolder(BB.getModule()->getDataLayout()));
Michael J. Spencer289067c2014-05-29 01:55:07 +0000240 Builder = &TheBuilder;
241
242 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> LoadMap;
Hal Finkel840257a2014-11-03 23:19:16 +0000243 AliasSetTracker AST(*AA);
Michael J. Spencer289067c2014-05-29 01:55:07 +0000244
245 bool Combined = false;
246 unsigned Index = 0;
247 for (auto &I : BB) {
Michael J. Spencer714d9d22017-02-09 21:46:49 +0000248 if (I.mayThrow() || AST.containsUnknown(&I)) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000249 if (combineLoads(LoadMap))
250 Combined = true;
251 LoadMap.clear();
Hal Finkel840257a2014-11-03 23:19:16 +0000252 AST.clear();
Michael J. Spencer289067c2014-05-29 01:55:07 +0000253 continue;
254 }
Michael J. Spencer714d9d22017-02-09 21:46:49 +0000255 if (I.mayWriteToMemory()) {
256 AST.add(&I);
257 continue;
258 }
Michael J. Spencer289067c2014-05-29 01:55:07 +0000259 LoadInst *LI = dyn_cast<LoadInst>(&I);
260 if (!LI)
261 continue;
262 ++NumLoadsAnalyzed;
263 if (!LI->isSimple() || !LI->getType()->isIntegerTy())
264 continue;
265 auto POP = getPointerOffsetPair(*LI);
266 if (!POP.Pointer)
267 continue;
Benjamin Kramera3d4def2016-08-06 12:11:11 +0000268 LoadMap[POP.Pointer].push_back({LI, std::move(POP), Index++});
Hal Finkel840257a2014-11-03 23:19:16 +0000269 AST.add(LI);
Michael J. Spencer289067c2014-05-29 01:55:07 +0000270 }
271 if (combineLoads(LoadMap))
272 Combined = true;
273 return Combined;
274}
275
Michael J. Spencer289067c2014-05-29 01:55:07 +0000276char LoadCombine::ID = 0;
277
278BasicBlockPass *llvm::createLoadCombinePass() {
279 return new LoadCombine();
280}
281
Chad Rosier7ab9a7b2016-05-04 15:19:02 +0000282INITIALIZE_PASS_BEGIN(LoadCombine, "load-combine", LDCOMBINE_NAME, false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000283INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chad Rosier7ab9a7b2016-05-04 15:19:02 +0000284INITIALIZE_PASS_END(LoadCombine, "load-combine", LDCOMBINE_NAME, false, false)