blob: e3aab4b40a06b82eaeaf7c3e8d41fd13408f5868 [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"
NAKAMURA Takumi99aa6e12014-04-30 06:44:50 +000046#include <tuple>
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000047
48using namespace llvm;
49
Chandler Carruth964daaa2014-04-22 02:55:47 +000050#define DEBUG_TYPE "consthoist"
51
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000052STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
53STATISTIC(NumConstantsRebased, "Number of constants rebased");
54
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000055namespace {
Juergen Ributzka5429c062014-03-21 06:04:36 +000056struct ConstantUser;
57struct RebasedConstantInfo;
58
59typedef SmallVector<ConstantUser, 8> ConstantUseListType;
60typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
61
62/// \brief Keeps track of the user of a constant and the operand index where the
63/// constant is used.
64struct ConstantUser {
65 Instruction *Inst;
66 unsigned OpndIdx;
67
68 ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
69};
70
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000071/// \brief Keeps track of a constant candidate and its uses.
Juergen Ributzka6dab5202014-03-20 19:55:52 +000072struct ConstantCandidate {
Juergen Ributzka6dab5202014-03-20 19:55:52 +000073 ConstantUseListType Uses;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000074 ConstantInt *ConstInt;
75 unsigned CumulativeCost;
76
77 ConstantCandidate(ConstantInt *ConstInt)
78 : ConstInt(ConstInt), CumulativeCost(0) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000079
80 /// \brief Add the user to the use list and update the cost.
81 void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
82 CumulativeCost += Cost;
83 Uses.push_back(ConstantUser(Inst, Idx));
84 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +000085};
86
Juergen Ributzka5429c062014-03-21 06:04:36 +000087/// \brief This represents a constant that has been rebased with respect to a
88/// base constant. The difference to the base constant is recorded in Offset.
89struct RebasedConstantInfo {
90 ConstantUseListType Uses;
91 Constant *Offset;
92
93 RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +000094 : Uses(std::move(Uses)), Offset(Offset) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000095};
96
97/// \brief A base constant and all its rebased constants.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000098struct ConstantInfo {
99 ConstantInt *BaseConstant;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000100 RebasedConstantListType RebasedConstants;
101};
102
Juergen Ributzka5429c062014-03-21 06:04:36 +0000103/// \brief The constant hoisting pass.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000104class ConstantHoisting : public FunctionPass {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000105 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
106 typedef std::vector<ConstantCandidate> ConstCandVecType;
107
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000108 const TargetTransformInfo *TTI;
109 DominatorTree *DT;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000110 BasicBlock *Entry;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000111
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000112 /// Keeps track of constant candidates found in the function.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000113 ConstCandVecType ConstCandVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000114
Juergen Ributzka5429c062014-03-21 06:04:36 +0000115 /// Keep track of cast instructions we already cloned.
116 SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
117
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000118 /// These are the final constants we decided to hoist.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000119 SmallVector<ConstantInfo, 8> ConstantVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000120public:
121 static char ID; // Pass identification, replacement for typeid
Craig Topperf40110f2014-04-25 05:29:35 +0000122 ConstantHoisting() : FunctionPass(ID), TTI(nullptr), DT(nullptr),
123 Entry(nullptr) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000124 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
125 }
126
Juergen Ributzka5429c062014-03-21 06:04:36 +0000127 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000128
Craig Topper3e4c6972014-03-05 09:10:37 +0000129 const char *getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000130
Craig Topper3e4c6972014-03-05 09:10:37 +0000131 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000132 AU.setPreservesCFG();
133 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000134 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000135 }
136
137private:
Juergen Ributzka5429c062014-03-21 06:04:36 +0000138 /// \brief Initialize the pass.
139 void setup(Function &Fn) {
140 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000141 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000142 Entry = &Fn.getEntryBlock();
143 }
144
145 /// \brief Cleanup.
146 void cleanup() {
147 ConstantVec.clear();
148 ClonedCastMap.clear();
149 ConstCandVec.clear();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000150
151 TTI = nullptr;
152 DT = nullptr;
153 Entry = nullptr;
154 }
155
156 Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
157 Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000158 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
159 Instruction *Inst, unsigned Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000160 ConstantInt *ConstInt);
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000161 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
162 Instruction *Inst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000163 void collectConstantCandidates(Function &Fn);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000164 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000165 ConstCandVecType::iterator E);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000166 void findBaseConstants();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000167 void emitBaseConstants(Instruction *Base, Constant *Offset,
168 const ConstantUser &ConstUser);
169 bool emitBaseConstants();
170 void deleteDeadCastInst() const;
171 bool optimizeConstants(Function &Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000172};
173}
174
175char ConstantHoisting::ID = 0;
176INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
177 false, false)
178INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000179INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000180INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
181 false, false)
182
183FunctionPass *llvm::createConstantHoistingPass() {
184 return new ConstantHoisting();
185}
186
187/// \brief Perform the constant hoisting optimization for the given function.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000188bool ConstantHoisting::runOnFunction(Function &Fn) {
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000189 if (skipOptnoneFunction(Fn))
190 return false;
191
Juergen Ributzka5429c062014-03-21 06:04:36 +0000192 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
193 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000194
Juergen Ributzka5429c062014-03-21 06:04:36 +0000195 setup(Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000196
Juergen Ributzka5429c062014-03-21 06:04:36 +0000197 bool MadeChange = optimizeConstants(Fn);
198
199 if (MadeChange) {
200 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
201 << Fn.getName() << '\n');
202 DEBUG(dbgs() << Fn);
203 }
204 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
205
206 cleanup();
207
208 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000209}
210
Juergen Ributzka5429c062014-03-21 06:04:36 +0000211
212/// \brief Find the constant materialization insertion point.
213Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
214 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000215 // If the operand is a cast instruction, then we have to materialize the
216 // constant before the cast instruction.
217 if (Idx != ~0U) {
218 Value *Opnd = Inst->getOperand(Idx);
219 if (auto CastInst = dyn_cast<Instruction>(Opnd))
220 if (CastInst->isCast())
221 return CastInst;
222 }
223
224 // The simple and common case. This also includes constant expressions.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000225 if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
226 return Inst;
227
228 // We can't insert directly before a phi node or landing pad. Insert before
229 // the terminator of the incoming or dominating block.
230 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
231 if (Idx != ~0U && isa<PHINode>(Inst))
232 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
233
234 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
235 return IDom->getTerminator();
236}
237
238/// \brief Find an insertion point that dominates all uses.
239Instruction *ConstantHoisting::
240findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
241 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000242 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000243 SmallPtrSet<BasicBlock *, 8> BBs;
244 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000245 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000246 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000247
248 if (BBs.count(Entry))
249 return &Entry->front();
250
251 while (BBs.size() >= 2) {
252 BasicBlock *BB, *BB1, *BB2;
253 BB1 = *BBs.begin();
254 BB2 = *std::next(BBs.begin());
255 BB = DT->findNearestCommonDominator(BB1, BB2);
256 if (BB == Entry)
257 return &Entry->front();
258 BBs.erase(BB1);
259 BBs.erase(BB2);
260 BBs.insert(BB);
261 }
262 assert((BBs.size() == 1) && "Expected only one element.");
263 Instruction &FirstInst = (*BBs.begin())->front();
264 return findMatInsertPt(&FirstInst);
265}
266
267
268/// \brief Record constant integer ConstInt for instruction Inst at operand
269/// index Idx.
270///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000271/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000272/// could also be a cast instruction or a constant expression that uses the
273// constant integer.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000274void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
275 Instruction *Inst,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000276 unsigned Idx,
277 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000278 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000279 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000280 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000281 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000282 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000283 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000284 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000285 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000286 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000287
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000288 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000289 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000290 ConstCandMapType::iterator Itr;
291 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000292 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000293 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000294 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000295 Itr->second = ConstCandVec.size() - 1;
296 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000297 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
298 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
299 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
300 << " with cost " << Cost << '\n';
301 else
302 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
303 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
304 << Cost << '\n';
305 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000306 }
307}
308
Juergen Ributzka5429c062014-03-21 06:04:36 +0000309/// \brief Scan the instruction for expensive integer constants and record them
310/// in the constant candidate vector.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000311void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
312 Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000313 // Skip all cast instructions. They are visited indirectly later on.
314 if (Inst->isCast())
315 return;
316
317 // Can't handle inline asm. Skip it.
318 if (auto Call = dyn_cast<CallInst>(Inst))
319 if (isa<InlineAsm>(Call->getCalledValue()))
320 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000321
322 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000323 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
324 Value *Opnd = Inst->getOperand(Idx);
325
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000326 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000327 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000328 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000329 continue;
330 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000331
332 // Visit cast instructions that have constant integers.
333 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
334 // Only visit cast instructions, which have been skipped. All other
335 // instructions should have already been visited.
336 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000337 continue;
338
Juergen Ributzka5429c062014-03-21 06:04:36 +0000339 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
340 // Pretend the constant is directly used by the instruction and ignore
341 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000342 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000343 continue;
344 }
345 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000346
347 // Visit constant expressions that have constant integers.
348 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
349 // Only visit constant cast expressions.
350 if (!ConstExpr->isCast())
351 continue;
352
353 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
354 // Pretend the constant is directly used by the instruction and ignore
355 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000356 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000357 continue;
358 }
359 }
360 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000361}
362
363/// \brief Collect all integer constants in the function that cannot be folded
364/// into an instruction itself.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000365void ConstantHoisting::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000366 ConstCandMapType ConstCandMap;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000367 for (Function::iterator BB : Fn)
368 for (BasicBlock::iterator Inst : *BB)
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000369 collectConstantCandidates(ConstCandMap, Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000370}
371
372/// \brief Find the base constant within the given range and rebase all other
373/// constants with respect to the base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000374void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000375 ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000376 auto MaxCostItr = S;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000377 unsigned NumUses = 0;
378 // Use the constant that has the maximum cost as base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000379 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
380 NumUses += ConstCand->Uses.size();
381 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
382 MaxCostItr = ConstCand;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000383 }
384
385 // Don't hoist constants that have only one use.
386 if (NumUses <= 1)
387 return;
388
Juergen Ributzka5429c062014-03-21 06:04:36 +0000389 ConstantInfo ConstInfo;
390 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
391 Type *Ty = ConstInfo.BaseConstant->getType();
392
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000393 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000394 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
395 APInt Diff = ConstCand->ConstInt->getValue() -
396 ConstInfo.BaseConstant->getValue();
397 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
398 ConstInfo.RebasedConstants.push_back(
399 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000400 }
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000401 ConstantVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000402}
403
Juergen Ributzka5429c062014-03-21 06:04:36 +0000404/// \brief Finds and combines constant candidates that can be easily
405/// rematerialized with an add from a common base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000406void ConstantHoisting::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000407 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000408 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
409 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
410 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
411 return LHS.ConstInt->getType()->getBitWidth() <
412 RHS.ConstInt->getType()->getBitWidth();
413 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000414 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000415
Juergen Ributzka5429c062014-03-21 06:04:36 +0000416 // Simple linear scan through the sorted constant candidate vector for viable
417 // merge candidates.
418 auto MinValItr = ConstCandVec.begin();
419 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
420 CC != E; ++CC) {
421 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000422 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000423 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000424 if ((Diff.getBitWidth() <= 64) &&
425 TTI->isLegalAddImmediate(Diff.getSExtValue()))
426 continue;
427 }
428 // We either have now a different constant type or the constant is not in
429 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000430 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000431 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000432 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000433 }
434 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000435 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000436}
437
Juergen Ributzkae802d502014-03-22 01:49:27 +0000438/// \brief Updates the operand at Idx in instruction Inst with the result of
439/// instruction Mat. If the instruction is a PHI node then special
440/// handling for duplicate values form the same incomming basic block is
441/// required.
442/// \return The update will always succeed, but the return value indicated if
443/// Mat was used for the update or not.
444static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
445 if (auto PHI = dyn_cast<PHINode>(Inst)) {
446 // Check if any previous operand of the PHI node has the same incoming basic
447 // block. This is a very odd case that happens when the incoming basic block
448 // has a switch statement. In this case use the same value as the previous
449 // operand(s), otherwise we will fail verification due to different values.
450 // The values are actually the same, but the variable names are different
451 // and the verifier doesn't like that.
452 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
453 for (unsigned i = 0; i < Idx; ++i) {
454 if (PHI->getIncomingBlock(i) == IncomingBB) {
455 Value *IncomingVal = PHI->getIncomingValue(i);
456 Inst->setOperand(Idx, IncomingVal);
457 return false;
458 }
459 }
460 }
461
462 Inst->setOperand(Idx, Mat);
463 return true;
464}
465
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000466/// \brief Emit materialization code for all rebased constants and update their
467/// users.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000468void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
469 const ConstantUser &ConstUser) {
470 Instruction *Mat = Base;
471 if (Offset) {
472 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
473 ConstUser.OpndIdx);
474 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
475 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000476
Juergen Ributzka5429c062014-03-21 06:04:36 +0000477 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
478 << " + " << *Offset << ") in BB "
479 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
480 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
481 }
482 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000483
Juergen Ributzka5429c062014-03-21 06:04:36 +0000484 // Visit constant integer.
485 if (isa<ConstantInt>(Opnd)) {
486 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000487 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
488 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000489 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000490 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000491 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000492
Juergen Ributzka5429c062014-03-21 06:04:36 +0000493 // Visit cast instruction.
494 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
495 assert(CastInst->isCast() && "Expected an cast instruction!");
496 // Check if we already have visited this cast instruction before to avoid
497 // unnecessary cloning.
498 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
499 if (!ClonedCastInst) {
500 ClonedCastInst = CastInst->clone();
501 ClonedCastInst->setOperand(0, Mat);
502 ClonedCastInst->insertAfter(CastInst);
503 // Use the same debug location as the original cast instruction.
504 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Juergen Ributzkaa1444b32014-04-22 18:06:51 +0000505 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
506 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000507 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000508
509 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000510 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000511 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
512 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000513 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000514
515 // Visit constant expression.
516 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
517 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
518 ConstExprInst->setOperand(0, Mat);
519 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
520 ConstUser.OpndIdx));
521
522 // Use the same debug location as the instruction we are about to update.
523 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
524
525 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
526 << "From : " << *ConstExpr << '\n');
527 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000528 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
529 ConstExprInst->eraseFromParent();
530 if (Offset)
531 Mat->eraseFromParent();
532 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000533 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
534 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000535 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000536}
537
538/// \brief Hoist and hide the base constant behind a bitcast and emit
539/// materialization code for derived constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000540bool ConstantHoisting::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000541 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000542 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000543 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000544 Instruction *IP = findConstantInsertionPoint(ConstInfo);
545 IntegerType *Ty = ConstInfo.BaseConstant->getType();
546 Instruction *Base =
547 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
548 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
549 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000550 NumConstantsHoisted++;
551
552 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000553 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000554 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000555 for (auto const &U : RCI.Uses)
556 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000557 }
558
559 // Use the same debug location as the last user of the constant.
560 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000561 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000562 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000563 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000564
565 // Correct for base constant, which we counted above too.
566 NumConstantsRebased--;
567 MadeChange = true;
568 }
569 return MadeChange;
570}
571
Juergen Ributzka5429c062014-03-21 06:04:36 +0000572/// \brief Check all cast instructions we made a copy of and remove them if they
573/// have no more users.
574void ConstantHoisting::deleteDeadCastInst() const {
575 for (auto const &I : ClonedCastMap)
576 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000577 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000578}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000579
Juergen Ributzka5429c062014-03-21 06:04:36 +0000580/// \brief Optimize expensive integer constants in the given function.
581bool ConstantHoisting::optimizeConstants(Function &Fn) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000582 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000583 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000584
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000585 // There are no constant candidates to worry about.
586 if (ConstCandVec.empty())
587 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000588
589 // Combine constants that can be easily materialized with an add from a common
590 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000591 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000592
Juergen Ributzka5429c062014-03-21 06:04:36 +0000593 // There are no constants to emit.
594 if (ConstantVec.empty())
595 return false;
596
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000597 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000598 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000599 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000600
Juergen Ributzka5429c062014-03-21 06:04:36 +0000601 // Cleanup dead instructions.
602 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000603
604 return MadeChange;
605}