blob: 6e46e8b6529fcc1670db5b2a5c0a7d8144366bec [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
32// simple (this means not nested) constant cast experessions. For example:
33// %0 = load i64* inttoptr (i64 big_constant to i64*)
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "consthoist"
37#include "llvm/Transforms/Scalar.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000038#include "llvm/ADT/SmallSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000039#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000040#include "llvm/ADT/Statistic.h"
41#include "llvm/Analysis/TargetTransformInfo.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/Dominators.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/Pass.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000046#include "llvm/Support/Debug.h"
47
48using namespace llvm;
49
50STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
51STATISTIC(NumConstantsRebased, "Number of constants rebased");
52
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000053namespace {
Juergen Ributzka46357932014-03-20 20:17:13 +000054typedef SmallVector<User *, 4> ConstantUseListType;
Juergen Ributzka6dab5202014-03-20 19:55:52 +000055struct ConstantCandidate {
Juergen Ributzka6dab5202014-03-20 19:55:52 +000056 ConstantUseListType Uses;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000057 ConstantInt *ConstInt;
58 unsigned CumulativeCost;
59
60 ConstantCandidate(ConstantInt *ConstInt)
61 : ConstInt(ConstInt), CumulativeCost(0) { }
Juergen Ributzka6dab5202014-03-20 19:55:52 +000062};
63
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000064struct ConstantInfo {
65 ConstantInt *BaseConstant;
Juergen Ributzka46357932014-03-20 20:17:13 +000066 struct RebasedConstantInfo {
67 ConstantInt *OriginalConstant;
68 Constant *Offset;
69 ConstantUseListType Uses;
70 };
71 typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000072 RebasedConstantListType RebasedConstants;
73};
74
75class ConstantHoisting : public FunctionPass {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000076 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
77 typedef std::vector<ConstantCandidate> ConstCandVecType;
78
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000079 const TargetTransformInfo *TTI;
80 DominatorTree *DT;
81
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000082 /// Keeps track of constant candidates found in the function.
83 ConstCandMapType ConstCandMap;
84 ConstCandVecType ConstCandVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000085
86 /// These are the final constants we decided to hoist.
Juergen Ributzka46357932014-03-20 20:17:13 +000087 SmallVector<ConstantInfo, 4> Constants;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000088public:
89 static char ID; // Pass identification, replacement for typeid
Juergen Ributzka46357932014-03-20 20:17:13 +000090 ConstantHoisting() : FunctionPass(ID), TTI(0) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000091 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
92 }
93
Juergen Ributzka46357932014-03-20 20:17:13 +000094 bool runOnFunction(Function &F) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000095
Craig Topper3e4c6972014-03-05 09:10:37 +000096 const char *getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000097
Craig Topper3e4c6972014-03-05 09:10:37 +000098 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000099 AU.setPreservesCFG();
100 AU.addRequired<DominatorTreeWrapperPass>();
101 AU.addRequired<TargetTransformInfo>();
102 }
103
104private:
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000105 void collectConstantCandidates(User *U, unsigned Opcode, Intrinsic::ID IID,
106 ConstantInt *C);
107 void collectConstantCandidates(Instruction *I);
108 void collectConstantCandidates(Function &F);
109 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000110 ConstCandVecType::iterator E);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000111 void findBaseConstants();
112 Instruction *findConstantInsertionPoint(Function &F,
Juergen Ributzka46357932014-03-20 20:17:13 +0000113 const ConstantInfo &CI) const;
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000114 void emitBaseConstants(Function &F, User *U, Instruction *Base,
Juergen Ributzka46357932014-03-20 20:17:13 +0000115 Constant *Offset, ConstantInt *OriginalConstant);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000116 bool emitBaseConstants(Function &F);
117 bool optimizeConstants(Function &F);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000118};
119}
120
121char ConstantHoisting::ID = 0;
122INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
123 false, false)
124INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
125INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
126INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
127 false, false)
128
129FunctionPass *llvm::createConstantHoistingPass() {
130 return new ConstantHoisting();
131}
132
133/// \brief Perform the constant hoisting optimization for the given function.
Juergen Ributzka46357932014-03-20 20:17:13 +0000134bool ConstantHoisting::runOnFunction(Function &F) {
135 DEBUG(dbgs() << "********** Constant Hoisting **********\n");
136 DEBUG(dbgs() << "********** Function: " << F.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000137
Juergen Ributzka46357932014-03-20 20:17:13 +0000138 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
139 TTI = &getAnalysis<TargetTransformInfo>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000140
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000141 return optimizeConstants(F);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000142}
143
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000144void ConstantHoisting::collectConstantCandidates(User * U, unsigned Opcode,
145 Intrinsic::ID IID,
146 ConstantInt *C) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000147 unsigned Cost;
Juergen Ributzka46357932014-03-20 20:17:13 +0000148 if (Opcode)
149 Cost = TTI->getIntImmCost(Opcode, C->getValue(), C->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000150 else
Juergen Ributzka46357932014-03-20 20:17:13 +0000151 Cost = TTI->getIntImmCost(IID, C->getValue(), C->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000152
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000153 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000154 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000155 ConstCandMapType::iterator Itr;
156 bool Inserted;
157 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(C, 0));
158 if (Inserted) {
159 ConstCandVec.push_back(ConstantCandidate(C));
160 Itr->second = ConstCandVec.size() - 1;
161 }
162 ConstantCandidate &CC = ConstCandVec[Itr->second];
Juergen Ributzka46357932014-03-20 20:17:13 +0000163 CC.CumulativeCost += Cost;
164 CC.Uses.push_back(U);
165 DEBUG(dbgs() << "Collect constant " << *C << " with cost " << Cost
166 << " from " << *U << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000167 }
168}
169
Juergen Ributzka46357932014-03-20 20:17:13 +0000170/// \brief Scan the instruction or constant expression for expensive integer
171/// constants and record them in the constant map.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000172void ConstantHoisting::collectConstantCandidates(Instruction *I) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000173 unsigned Opcode = 0;
174 Intrinsic::ID IID = Intrinsic::not_intrinsic;
175 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
176 IID = II->getIntrinsicID();
177 else
178 Opcode = I->getOpcode();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000179
180 // Scan all operands.
Juergen Ributzka46357932014-03-20 20:17:13 +0000181 for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O) {
182 if (ConstantInt *C = dyn_cast<ConstantInt>(O)) {
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000183 collectConstantCandidates(I, Opcode, IID, C);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000184 continue;
185 }
Juergen Ributzka46357932014-03-20 20:17:13 +0000186 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(O)) {
187 // We only handle constant cast expressions.
188 if (!CE->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000189 continue;
190
Juergen Ributzka46357932014-03-20 20:17:13 +0000191 if (ConstantInt *C = dyn_cast<ConstantInt>(CE->getOperand(0))) {
192 // Ignore the cast expression and use the opcode of the instruction.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000193 collectConstantCandidates(CE, Opcode, IID, C);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000194 continue;
195 }
196 }
Juergen Ributzka46357932014-03-20 20:17:13 +0000197 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000198}
199
200/// \brief Collect all integer constants in the function that cannot be folded
201/// into an instruction itself.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000202void ConstantHoisting::collectConstantCandidates(Function &F) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000203 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
204 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000205 collectConstantCandidates(I);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000206}
207
208/// \brief Find the base constant within the given range and rebase all other
209/// constants with respect to the base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000210void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000211 ConstCandVecType::iterator E) {
212 ConstCandVecType::iterator MaxCostItr = S;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000213 unsigned NumUses = 0;
214 // Use the constant that has the maximum cost as base constant.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000215 for (ConstCandVecType::iterator I = S; I != E; ++I) {
216 NumUses += I->Uses.size();
217 if (I->CumulativeCost > MaxCostItr->CumulativeCost)
Juergen Ributzka46357932014-03-20 20:17:13 +0000218 MaxCostItr = I;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000219 }
220
221 // Don't hoist constants that have only one use.
222 if (NumUses <= 1)
223 return;
224
Juergen Ributzka46357932014-03-20 20:17:13 +0000225 ConstantInfo CI;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000226 CI.BaseConstant = MaxCostItr->ConstInt;
Juergen Ributzka46357932014-03-20 20:17:13 +0000227 Type *Ty = CI.BaseConstant->getType();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000228 // Rebase the constants with respect to the base constant.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000229 for (ConstCandVecType::iterator I = S; I != E; ++I) {
230 APInt Diff = I->ConstInt->getValue() - CI.BaseConstant->getValue();
Juergen Ributzka46357932014-03-20 20:17:13 +0000231 ConstantInfo::RebasedConstantInfo RCI;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000232 RCI.OriginalConstant = I->ConstInt;
Juergen Ributzka46357932014-03-20 20:17:13 +0000233 RCI.Offset = ConstantInt::get(Ty, Diff);
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000234 RCI.Uses = std::move(I->Uses);
Juergen Ributzka46357932014-03-20 20:17:13 +0000235 CI.RebasedConstants.push_back(RCI);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000236 }
Juergen Ributzka46357932014-03-20 20:17:13 +0000237 Constants.push_back(CI);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000238}
239
Juergen Ributzka46357932014-03-20 20:17:13 +0000240/// \brief Finds and combines constants that can be easily rematerialized with
241/// an add from a common base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000242void ConstantHoisting::findBaseConstants() {
Juergen Ributzka46357932014-03-20 20:17:13 +0000243 // Sort the constants by value and type. This invalidates the mapping.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000244 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
245 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
246 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
247 return LHS.ConstInt->getType()->getBitWidth() <
248 RHS.ConstInt->getType()->getBitWidth();
249 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000250 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000251
Juergen Ributzka46357932014-03-20 20:17:13 +0000252 // Simple linear scan through the sorted constant map for viable merge
253 // candidates.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000254 ConstCandVecType::iterator MinValItr = ConstCandVec.begin();
255 for (ConstCandVecType::iterator I = std::next(ConstCandVec.begin()),
256 E = ConstCandVec.end(); I != E; ++I) {
257 if (MinValItr->ConstInt->getType() == I->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000258 // Check if the constant is in range of an add with immediate.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000259 APInt Diff = I->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000260 if ((Diff.getBitWidth() <= 64) &&
261 TTI->isLegalAddImmediate(Diff.getSExtValue()))
262 continue;
263 }
264 // We either have now a different constant type or the constant is not in
265 // range of an add with immediate anymore.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000266 findAndMakeBaseConstant(MinValItr, I);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000267 // Start a new base constant search.
Juergen Ributzka46357932014-03-20 20:17:13 +0000268 MinValItr = I;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000269 }
270 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000271 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000272}
273
274/// \brief Records the basic block of the instruction or all basic blocks of the
275/// users of the constant expression.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000276static void collectBasicBlocks(SmallPtrSet<BasicBlock *, 4> &BBs, Function &F,
Juergen Ributzka46357932014-03-20 20:17:13 +0000277 User *U) {
278 if (Instruction *I = dyn_cast<Instruction>(U))
279 BBs.insert(I->getParent());
280 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
281 // Find all users of this constant expression.
282 for (User *UU : CE->users())
283 // Only record users that are instructions. We don't want to go down a
284 // nested constant expression chain. Also check if the instruction is even
285 // in the current function.
286 if (Instruction *I = dyn_cast<Instruction>(UU))
287 if(I->getParent()->getParent() == &F)
288 BBs.insert(I->getParent());
289}
290
291/// \brief Find the instruction we should insert the constant materialization
292/// before.
293static Instruction *getMatInsertPt(Instruction *I, const DominatorTree *DT) {
294 if (!isa<PHINode>(I) && !isa<LandingPadInst>(I)) // Simple case.
295 return I;
296
297 // We can't insert directly before a phi node or landing pad. Insert before
298 // the terminator of the dominating block.
299 assert(&I->getParent()->getParent()->getEntryBlock() != I->getParent() &&
300 "PHI or landing pad in entry block!");
301 BasicBlock *IDom = DT->getNode(I->getParent())->getIDom()->getBlock();
302 return IDom->getTerminator();
303}
304
305/// \brief Find an insertion point that dominates all uses.
306Instruction *ConstantHoisting::
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000307findConstantInsertionPoint(Function &F, const ConstantInfo &CI) const {
Juergen Ributzka46357932014-03-20 20:17:13 +0000308 BasicBlock *Entry = &F.getEntryBlock();
309
310 // Collect all basic blocks.
311 SmallPtrSet<BasicBlock *, 4> BBs;
312 ConstantInfo::RebasedConstantListType::const_iterator RCI, RCE;
313 for (RCI = CI.RebasedConstants.begin(), RCE = CI.RebasedConstants.end();
314 RCI != RCE; ++RCI)
315 for (SmallVectorImpl<User *>::const_iterator U = RCI->Uses.begin(),
316 E = RCI->Uses.end(); U != E; ++U)
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000317 collectBasicBlocks(BBs, F, *U);
Juergen Ributzka46357932014-03-20 20:17:13 +0000318
319 if (BBs.count(Entry))
320 return getMatInsertPt(&Entry->front(), DT);
321
322 while (BBs.size() >= 2) {
323 BasicBlock *BB, *BB1, *BB2;
324 BB1 = *BBs.begin();
325 BB2 = *std::next(BBs.begin());
326 BB = DT->findNearestCommonDominator(BB1, BB2);
327 if (BB == Entry)
328 return getMatInsertPt(&Entry->front(), DT);
329 BBs.erase(BB1);
330 BBs.erase(BB2);
331 BBs.insert(BB);
332 }
333 assert((BBs.size() == 1) && "Expected only one element.");
334 Instruction &FirstInst = (*BBs.begin())->front();
335 return getMatInsertPt(&FirstInst, DT);
Juergen Ributzka9479b312014-02-08 00:20:49 +0000336}
337
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000338/// \brief Emit materialization code for all rebased constants and update their
339/// users.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000340void ConstantHoisting::emitBaseConstants(Function &F, User *U,
Juergen Ributzka46357932014-03-20 20:17:13 +0000341 Instruction *Base, Constant *Offset,
342 ConstantInt *OriginalConstant) {
343 if (Instruction *I = dyn_cast<Instruction>(U)) {
344 Instruction *Mat = Base;
345 if (!Offset->isNullValue()) {
346 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
347 "const_mat", getMatInsertPt(I, DT));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000348
Juergen Ributzka46357932014-03-20 20:17:13 +0000349 // Use the same debug location as the instruction we are about to update.
350 Mat->setDebugLoc(I->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000351
Juergen Ributzka46357932014-03-20 20:17:13 +0000352 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
353 << " + " << *Offset << ") in BB "
354 << I->getParent()->getName() << '\n' << *Mat << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000355 }
Juergen Ributzka46357932014-03-20 20:17:13 +0000356 DEBUG(dbgs() << "Update: " << *I << '\n');
357 I->replaceUsesOfWith(OriginalConstant, Mat);
358 DEBUG(dbgs() << "To: " << *I << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000359 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000360 }
Juergen Ributzka46357932014-03-20 20:17:13 +0000361 assert(isa<ConstantExpr>(U) && "Expected a ConstantExpr.");
362 ConstantExpr *CE = cast<ConstantExpr>(U);
363 SmallVector<std::pair<Instruction *, Instruction *>, 8> WorkList;
364 DEBUG(dbgs() << "Visit ConstantExpr " << *CE << '\n');
365 for (User *UU : CE->users()) {
366 DEBUG(dbgs() << "Check user "; UU->print(dbgs()); dbgs() << '\n');
367 // We only handel instructions here and won't walk down a ConstantExpr chain
368 // to replace all ConstExpr with instructions.
369 if (Instruction *I = dyn_cast<Instruction>(UU)) {
370 // Only update constant expressions in the current function.
371 if (I->getParent()->getParent() != &F) {
372 DEBUG(dbgs() << "Not in the same function - skip.\n");
373 continue;
374 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000375
Juergen Ributzka46357932014-03-20 20:17:13 +0000376 Instruction *Mat = Base;
377 Instruction *InsertBefore = getMatInsertPt(I, DT);
378 if (!Offset->isNullValue()) {
379 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
380 "const_mat", InsertBefore);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000381
Juergen Ributzka46357932014-03-20 20:17:13 +0000382 // Use the same debug location as the instruction we are about to
383 // update.
384 Mat->setDebugLoc(I->getDebugLoc());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000385
Juergen Ributzka46357932014-03-20 20:17:13 +0000386 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
387 << " + " << *Offset << ") in BB "
388 << I->getParent()->getName() << '\n' << *Mat << '\n');
389 }
390 Instruction *ICE = CE->getAsInstruction();
391 ICE->replaceUsesOfWith(OriginalConstant, Mat);
392 ICE->insertBefore(InsertBefore);
393
394 // Use the same debug location as the instruction we are about to update.
395 ICE->setDebugLoc(I->getDebugLoc());
396
397 WorkList.push_back(std::make_pair(I, ICE));
398 } else {
399 DEBUG(dbgs() << "Not an instruction - skip.\n");
400 }
401 }
402 SmallVectorImpl<std::pair<Instruction *, Instruction *> >::iterator I, E;
403 for (I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
404 DEBUG(dbgs() << "Create instruction: " << *I->second << '\n');
405 DEBUG(dbgs() << "Update: " << *I->first << '\n');
406 I->first->replaceUsesOfWith(CE, I->second);
407 DEBUG(dbgs() << "To: " << *I->first << '\n');
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000408 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000409}
410
411/// \brief Hoist and hide the base constant behind a bitcast and emit
412/// materialization code for derived constants.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000413bool ConstantHoisting::emitBaseConstants(Function &F) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000414 bool MadeChange = false;
Juergen Ributzka46357932014-03-20 20:17:13 +0000415 SmallVectorImpl<ConstantInfo>::iterator CI, CE;
416 for (CI = Constants.begin(), CE = Constants.end(); CI != CE; ++CI) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000417 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000418 Instruction *IP = findConstantInsertionPoint(F, *CI);
Juergen Ributzka46357932014-03-20 20:17:13 +0000419 IntegerType *Ty = CI->BaseConstant->getType();
420 Instruction *Base = new BitCastInst(CI->BaseConstant, Ty, "const", IP);
421 DEBUG(dbgs() << "Hoist constant (" << *CI->BaseConstant << ") to BB "
422 << IP->getParent()->getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000423 NumConstantsHoisted++;
424
425 // Emit materialization code for all rebased constants.
Juergen Ributzka46357932014-03-20 20:17:13 +0000426 ConstantInfo::RebasedConstantListType::iterator RCI, RCE;
427 for (RCI = CI->RebasedConstants.begin(), RCE = CI->RebasedConstants.end();
428 RCI != RCE; ++RCI) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000429 NumConstantsRebased++;
Juergen Ributzka46357932014-03-20 20:17:13 +0000430 for (SmallVectorImpl<User *>::iterator U = RCI->Uses.begin(),
431 E = RCI->Uses.end(); U != E; ++U)
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000432 emitBaseConstants(F, *U, Base, RCI->Offset, RCI->OriginalConstant);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000433 }
434
435 // Use the same debug location as the last user of the constant.
436 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000437 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000438 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000439 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000440
441 // Correct for base constant, which we counted above too.
442 NumConstantsRebased--;
443 MadeChange = true;
444 }
445 return MadeChange;
446}
447
448/// \brief Optimize expensive integer constants in the given function.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000449bool ConstantHoisting::optimizeConstants(Function &F) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000450 bool MadeChange = false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000451
Juergen Ributzka46357932014-03-20 20:17:13 +0000452 // Collect all constant candidates.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000453 collectConstantCandidates(F);
Juergen Ributzka46357932014-03-20 20:17:13 +0000454
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000455 // There are no constant candidates to worry about.
456 if (ConstCandVec.empty())
457 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000458
459 // Combine constants that can be easily materialized with an add from a common
460 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000461 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000462
Alp Toker70b36992014-02-25 04:21:15 +0000463 // Finally hoist the base constant and emit materializating code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000464 // constants.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000465 MadeChange |= emitBaseConstants(F);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000466
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000467 ConstCandMap.clear();
468 ConstCandVec.clear();
Juergen Ributzka46357932014-03-20 20:17:13 +0000469 Constants.clear();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000470
471 return MadeChange;
472}