blob: 74050fa1b5daf58bb75a6f69351b14ca927e2dda [file] [log] [blame]
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001//===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
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//
10// This pass identifies expensive constants to hoist and coalesces them to
11// better prepare it for SelectionDAG-based code generation. This works around
12// the limitations of the basic-block-at-a-time approach.
13//
14// First it scans all instructions for integer constants and calculates its
15// cost. If the constant can be folded into the instruction (the cost is
16// TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
17// consider it expensive and leave it alone. This is the default behavior and
18// the default implementation of getIntImmCost will always return TCC_Free.
19//
20// If the cost is more than TCC_BASIC, then the integer constant can't be folded
21// into the instruction and it might be beneficial to hoist the constant.
22// Similar constants are coalesced to reduce register pressure and
23// materialization code.
24//
25// When a constant is hoisted, it is also hidden behind a bitcast to force it to
26// be live-out of the basic block. Otherwise the constant would be just
27// duplicated and each basic block would have its own copy in the SelectionDAG.
28// The SelectionDAG recognizes such constants as opaque and doesn't perform
29// certain transformations on them, which would create a new expensive constant.
30//
31// This optimization is only applied to integer constants in instructions and
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000032// simple (this means not nested) constant cast expressions. For example:
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000033// %0 = load i64* inttoptr (i64 big_constant to i64*)
34//===----------------------------------------------------------------------===//
35
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000036#include "llvm/Transforms/Scalar.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000037#include "llvm/ADT/SmallSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000038#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000039#include "llvm/ADT/Statistic.h"
40#include "llvm/Analysis/TargetTransformInfo.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/Dominators.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/Pass.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000045#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Support/raw_ostream.h"
NAKAMURA Takumi99aa6e12014-04-30 06:44:50 +000047#include <tuple>
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000048
49using namespace llvm;
50
Chandler Carruth964daaa2014-04-22 02:55:47 +000051#define DEBUG_TYPE "consthoist"
52
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000053STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
54STATISTIC(NumConstantsRebased, "Number of constants rebased");
55
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000056namespace {
Juergen Ributzka5429c062014-03-21 06:04:36 +000057struct ConstantUser;
58struct RebasedConstantInfo;
59
60typedef SmallVector<ConstantUser, 8> ConstantUseListType;
61typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
62
63/// \brief Keeps track of the user of a constant and the operand index where the
64/// constant is used.
65struct ConstantUser {
66 Instruction *Inst;
67 unsigned OpndIdx;
68
69 ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
70};
71
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000072/// \brief Keeps track of a constant candidate and its uses.
Juergen Ributzka6dab5202014-03-20 19:55:52 +000073struct ConstantCandidate {
Juergen Ributzka6dab5202014-03-20 19:55:52 +000074 ConstantUseListType Uses;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000075 ConstantInt *ConstInt;
76 unsigned CumulativeCost;
77
78 ConstantCandidate(ConstantInt *ConstInt)
79 : ConstInt(ConstInt), CumulativeCost(0) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000080
81 /// \brief Add the user to the use list and update the cost.
82 void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
83 CumulativeCost += Cost;
84 Uses.push_back(ConstantUser(Inst, Idx));
85 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +000086};
87
Juergen Ributzka5429c062014-03-21 06:04:36 +000088/// \brief This represents a constant that has been rebased with respect to a
89/// base constant. The difference to the base constant is recorded in Offset.
90struct RebasedConstantInfo {
91 ConstantUseListType Uses;
92 Constant *Offset;
93
94 RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +000095 : Uses(std::move(Uses)), Offset(Offset) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000096};
97
98/// \brief A base constant and all its rebased constants.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000099struct ConstantInfo {
100 ConstantInt *BaseConstant;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000101 RebasedConstantListType RebasedConstants;
102};
103
Juergen Ributzka5429c062014-03-21 06:04:36 +0000104/// \brief The constant hoisting pass.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000105class ConstantHoisting : public FunctionPass {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000106 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
107 typedef std::vector<ConstantCandidate> ConstCandVecType;
108
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000109 const TargetTransformInfo *TTI;
110 DominatorTree *DT;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000111 BasicBlock *Entry;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000112
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000113 /// Keeps track of constant candidates found in the function.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000114 ConstCandVecType ConstCandVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000115
Juergen Ributzka5429c062014-03-21 06:04:36 +0000116 /// Keep track of cast instructions we already cloned.
117 SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
118
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000119 /// These are the final constants we decided to hoist.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000120 SmallVector<ConstantInfo, 8> ConstantVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000121public:
122 static char ID; // Pass identification, replacement for typeid
Craig Topperf40110f2014-04-25 05:29:35 +0000123 ConstantHoisting() : FunctionPass(ID), TTI(nullptr), DT(nullptr),
124 Entry(nullptr) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000125 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
126 }
127
Juergen Ributzka5429c062014-03-21 06:04:36 +0000128 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000129
Craig Topper3e4c6972014-03-05 09:10:37 +0000130 const char *getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000131
Craig Topper3e4c6972014-03-05 09:10:37 +0000132 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000133 AU.setPreservesCFG();
134 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000135 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000136 }
137
138private:
Juergen Ributzka5429c062014-03-21 06:04:36 +0000139 /// \brief Initialize the pass.
140 void setup(Function &Fn) {
141 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000142 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000143 Entry = &Fn.getEntryBlock();
144 }
145
146 /// \brief Cleanup.
147 void cleanup() {
148 ConstantVec.clear();
149 ClonedCastMap.clear();
150 ConstCandVec.clear();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000151
152 TTI = nullptr;
153 DT = nullptr;
154 Entry = nullptr;
155 }
156
157 Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
158 Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000159 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
160 Instruction *Inst, unsigned Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000161 ConstantInt *ConstInt);
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000162 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
163 Instruction *Inst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000164 void collectConstantCandidates(Function &Fn);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000165 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000166 ConstCandVecType::iterator E);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000167 void findBaseConstants();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000168 void emitBaseConstants(Instruction *Base, Constant *Offset,
169 const ConstantUser &ConstUser);
170 bool emitBaseConstants();
171 void deleteDeadCastInst() const;
172 bool optimizeConstants(Function &Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000173};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000174}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000175
176char ConstantHoisting::ID = 0;
177INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
178 false, false)
179INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000180INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000181INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
182 false, false)
183
184FunctionPass *llvm::createConstantHoistingPass() {
185 return new ConstantHoisting();
186}
187
188/// \brief Perform the constant hoisting optimization for the given function.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000189bool ConstantHoisting::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000190 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000191 return false;
192
Juergen Ributzka5429c062014-03-21 06:04:36 +0000193 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
194 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000195
Juergen Ributzka5429c062014-03-21 06:04:36 +0000196 setup(Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000197
Juergen Ributzka5429c062014-03-21 06:04:36 +0000198 bool MadeChange = optimizeConstants(Fn);
199
200 if (MadeChange) {
201 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
202 << Fn.getName() << '\n');
203 DEBUG(dbgs() << Fn);
204 }
205 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
206
207 cleanup();
208
209 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000210}
211
Juergen Ributzka5429c062014-03-21 06:04:36 +0000212
213/// \brief Find the constant materialization insertion point.
214Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
215 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000216 // If the operand is a cast instruction, then we have to materialize the
217 // constant before the cast instruction.
218 if (Idx != ~0U) {
219 Value *Opnd = Inst->getOperand(Idx);
220 if (auto CastInst = dyn_cast<Instruction>(Opnd))
221 if (CastInst->isCast())
222 return CastInst;
223 }
224
225 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000226 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000227 return Inst;
228
David Majnemerba275f92015-08-19 19:54:02 +0000229 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000230 // the terminator of the incoming or dominating block.
231 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
232 if (Idx != ~0U && isa<PHINode>(Inst))
233 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
234
235 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
236 return IDom->getTerminator();
237}
238
239/// \brief Find an insertion point that dominates all uses.
240Instruction *ConstantHoisting::
241findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
242 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000243 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000244 SmallPtrSet<BasicBlock *, 8> BBs;
245 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000246 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000247 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000248
249 if (BBs.count(Entry))
250 return &Entry->front();
251
252 while (BBs.size() >= 2) {
253 BasicBlock *BB, *BB1, *BB2;
254 BB1 = *BBs.begin();
255 BB2 = *std::next(BBs.begin());
256 BB = DT->findNearestCommonDominator(BB1, BB2);
257 if (BB == Entry)
258 return &Entry->front();
259 BBs.erase(BB1);
260 BBs.erase(BB2);
261 BBs.insert(BB);
262 }
263 assert((BBs.size() == 1) && "Expected only one element.");
264 Instruction &FirstInst = (*BBs.begin())->front();
265 return findMatInsertPt(&FirstInst);
266}
267
268
269/// \brief Record constant integer ConstInt for instruction Inst at operand
270/// index Idx.
271///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000272/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000273/// could also be a cast instruction or a constant expression that uses the
274// constant integer.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000275void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
276 Instruction *Inst,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000277 unsigned Idx,
278 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000279 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000280 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000281 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000282 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000283 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000284 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000285 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000286 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000287 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000288
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000289 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000290 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000291 ConstCandMapType::iterator Itr;
292 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000293 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000294 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000295 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000296 Itr->second = ConstCandVec.size() - 1;
297 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000298 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
299 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
300 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
301 << " with cost " << Cost << '\n';
302 else
303 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
304 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
305 << Cost << '\n';
306 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000307 }
308}
309
Juergen Ributzka5429c062014-03-21 06:04:36 +0000310/// \brief Scan the instruction for expensive integer constants and record them
311/// in the constant candidate vector.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000312void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
313 Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000314 // Skip all cast instructions. They are visited indirectly later on.
315 if (Inst->isCast())
316 return;
317
318 // Can't handle inline asm. Skip it.
319 if (auto Call = dyn_cast<CallInst>(Inst))
320 if (isa<InlineAsm>(Call->getCalledValue()))
321 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000322
Tim Northover5c02f9a2016-04-13 23:08:27 +0000323 // Switch cases must remain constant, and if the value being tested is
324 // constant the entire thing should disappear.
325 if (isa<SwitchInst>(Inst))
326 return;
327
328 // Static allocas (constant size in the entry block) are handled by
329 // prologue/epilogue insertion so they're free anyway. We definitely don't
330 // want to make them non-constant.
331 auto AI = dyn_cast<AllocaInst>(Inst);
332 if (AI && AI->isStaticAlloca())
333 return;
334
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000335 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000336 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
337 Value *Opnd = Inst->getOperand(Idx);
338
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000339 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000340 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000341 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000342 continue;
343 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000344
345 // Visit cast instructions that have constant integers.
346 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
347 // Only visit cast instructions, which have been skipped. All other
348 // instructions should have already been visited.
349 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000350 continue;
351
Juergen Ributzka5429c062014-03-21 06:04:36 +0000352 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
353 // Pretend the constant is directly used by the instruction and ignore
354 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000355 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000356 continue;
357 }
358 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000359
360 // Visit constant expressions that have constant integers.
361 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
362 // Only visit constant cast expressions.
363 if (!ConstExpr->isCast())
364 continue;
365
366 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
367 // Pretend the constant is directly used by the instruction and ignore
368 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000369 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000370 continue;
371 }
372 }
373 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000374}
375
376/// \brief Collect all integer constants in the function that cannot be folded
377/// into an instruction itself.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000378void ConstantHoisting::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000379 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000380 for (BasicBlock &BB : Fn)
381 for (Instruction &Inst : BB)
382 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000383}
384
385/// \brief Find the base constant within the given range and rebase all other
386/// constants with respect to the base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000387void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000388 ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000389 auto MaxCostItr = S;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000390 unsigned NumUses = 0;
391 // Use the constant that has the maximum cost as base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000392 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
393 NumUses += ConstCand->Uses.size();
394 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
395 MaxCostItr = ConstCand;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000396 }
397
398 // Don't hoist constants that have only one use.
399 if (NumUses <= 1)
400 return;
401
Juergen Ributzka5429c062014-03-21 06:04:36 +0000402 ConstantInfo ConstInfo;
403 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
404 Type *Ty = ConstInfo.BaseConstant->getType();
405
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000406 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000407 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
408 APInt Diff = ConstCand->ConstInt->getValue() -
409 ConstInfo.BaseConstant->getValue();
410 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
411 ConstInfo.RebasedConstants.push_back(
412 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000413 }
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000414 ConstantVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000415}
416
Juergen Ributzka5429c062014-03-21 06:04:36 +0000417/// \brief Finds and combines constant candidates that can be easily
418/// rematerialized with an add from a common base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000419void ConstantHoisting::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000420 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000421 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
422 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
423 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
424 return LHS.ConstInt->getType()->getBitWidth() <
425 RHS.ConstInt->getType()->getBitWidth();
426 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000427 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000428
Juergen Ributzka5429c062014-03-21 06:04:36 +0000429 // Simple linear scan through the sorted constant candidate vector for viable
430 // merge candidates.
431 auto MinValItr = ConstCandVec.begin();
432 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
433 CC != E; ++CC) {
434 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000435 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000436 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000437 if ((Diff.getBitWidth() <= 64) &&
438 TTI->isLegalAddImmediate(Diff.getSExtValue()))
439 continue;
440 }
441 // We either have now a different constant type or the constant is not in
442 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000443 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000444 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000445 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000446 }
447 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000448 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000449}
450
Juergen Ributzkae802d502014-03-22 01:49:27 +0000451/// \brief Updates the operand at Idx in instruction Inst with the result of
452/// instruction Mat. If the instruction is a PHI node then special
453/// handling for duplicate values form the same incomming basic block is
454/// required.
455/// \return The update will always succeed, but the return value indicated if
456/// Mat was used for the update or not.
457static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
458 if (auto PHI = dyn_cast<PHINode>(Inst)) {
459 // Check if any previous operand of the PHI node has the same incoming basic
460 // block. This is a very odd case that happens when the incoming basic block
461 // has a switch statement. In this case use the same value as the previous
462 // operand(s), otherwise we will fail verification due to different values.
463 // The values are actually the same, but the variable names are different
464 // and the verifier doesn't like that.
465 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
466 for (unsigned i = 0; i < Idx; ++i) {
467 if (PHI->getIncomingBlock(i) == IncomingBB) {
468 Value *IncomingVal = PHI->getIncomingValue(i);
469 Inst->setOperand(Idx, IncomingVal);
470 return false;
471 }
472 }
473 }
474
475 Inst->setOperand(Idx, Mat);
476 return true;
477}
478
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000479/// \brief Emit materialization code for all rebased constants and update their
480/// users.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000481void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
482 const ConstantUser &ConstUser) {
483 Instruction *Mat = Base;
484 if (Offset) {
485 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
486 ConstUser.OpndIdx);
487 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
488 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000489
Juergen Ributzka5429c062014-03-21 06:04:36 +0000490 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
491 << " + " << *Offset << ") in BB "
492 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
493 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
494 }
495 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000496
Juergen Ributzka5429c062014-03-21 06:04:36 +0000497 // Visit constant integer.
498 if (isa<ConstantInt>(Opnd)) {
499 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000500 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
501 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000502 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000503 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000504 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000505
Juergen Ributzka5429c062014-03-21 06:04:36 +0000506 // Visit cast instruction.
507 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
508 assert(CastInst->isCast() && "Expected an cast instruction!");
509 // Check if we already have visited this cast instruction before to avoid
510 // unnecessary cloning.
511 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
512 if (!ClonedCastInst) {
513 ClonedCastInst = CastInst->clone();
514 ClonedCastInst->setOperand(0, Mat);
515 ClonedCastInst->insertAfter(CastInst);
516 // Use the same debug location as the original cast instruction.
517 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Juergen Ributzkaa1444b32014-04-22 18:06:51 +0000518 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
519 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000520 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000521
522 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000523 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000524 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
525 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000526 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000527
528 // Visit constant expression.
529 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
530 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
531 ConstExprInst->setOperand(0, Mat);
532 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
533 ConstUser.OpndIdx));
534
535 // Use the same debug location as the instruction we are about to update.
536 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
537
538 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
539 << "From : " << *ConstExpr << '\n');
540 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000541 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
542 ConstExprInst->eraseFromParent();
543 if (Offset)
544 Mat->eraseFromParent();
545 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000546 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
547 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000548 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000549}
550
551/// \brief Hoist and hide the base constant behind a bitcast and emit
552/// materialization code for derived constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000553bool ConstantHoisting::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000554 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000555 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000556 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000557 Instruction *IP = findConstantInsertionPoint(ConstInfo);
558 IntegerType *Ty = ConstInfo.BaseConstant->getType();
559 Instruction *Base =
560 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
561 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
562 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000563 NumConstantsHoisted++;
564
565 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000566 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000567 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000568 for (auto const &U : RCI.Uses)
569 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000570 }
571
572 // Use the same debug location as the last user of the constant.
573 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000574 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000575 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000576 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000577
578 // Correct for base constant, which we counted above too.
579 NumConstantsRebased--;
580 MadeChange = true;
581 }
582 return MadeChange;
583}
584
Juergen Ributzka5429c062014-03-21 06:04:36 +0000585/// \brief Check all cast instructions we made a copy of and remove them if they
586/// have no more users.
587void ConstantHoisting::deleteDeadCastInst() const {
588 for (auto const &I : ClonedCastMap)
589 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000590 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000591}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000592
Juergen Ributzka5429c062014-03-21 06:04:36 +0000593/// \brief Optimize expensive integer constants in the given function.
594bool ConstantHoisting::optimizeConstants(Function &Fn) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000595 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000596 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000597
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000598 // There are no constant candidates to worry about.
599 if (ConstCandVec.empty())
600 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000601
602 // Combine constants that can be easily materialized with an add from a common
603 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000604 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000605
Juergen Ributzka5429c062014-03-21 06:04:36 +0000606 // There are no constants to emit.
607 if (ConstantVec.empty())
608 return false;
609
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000610 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000611 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000612 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000613
Juergen Ributzka5429c062014-03-21 06:04:36 +0000614 // Cleanup dead instructions.
615 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000616
617 return MadeChange;
618}