blob: 57a15214e65324cacbfa54f25c1b2712f822edbd [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
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 Ributzka5429c062014-03-21 06:04:36 +000054struct ConstantUser;
55struct RebasedConstantInfo;
56
57typedef SmallVector<ConstantUser, 8> ConstantUseListType;
58typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
59
60/// \brief Keeps track of the user of a constant and the operand index where the
61/// constant is used.
62struct ConstantUser {
63 Instruction *Inst;
64 unsigned OpndIdx;
65
66 ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
67};
68
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000069/// \brief Keeps track of a constant candidate and its uses.
Juergen Ributzka6dab5202014-03-20 19:55:52 +000070struct ConstantCandidate {
Juergen Ributzka6dab5202014-03-20 19:55:52 +000071 ConstantUseListType Uses;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000072 ConstantInt *ConstInt;
73 unsigned CumulativeCost;
74
75 ConstantCandidate(ConstantInt *ConstInt)
76 : ConstInt(ConstInt), CumulativeCost(0) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000077
78 /// \brief Add the user to the use list and update the cost.
79 void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
80 CumulativeCost += Cost;
81 Uses.push_back(ConstantUser(Inst, Idx));
82 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +000083};
84
Juergen Ributzka5429c062014-03-21 06:04:36 +000085/// \brief This represents a constant that has been rebased with respect to a
86/// base constant. The difference to the base constant is recorded in Offset.
87struct RebasedConstantInfo {
88 ConstantUseListType Uses;
89 Constant *Offset;
90
91 RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
Juergen Ributzkac81000b2014-04-03 01:38:47 +000092 : Uses(Uses), Offset(Offset) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000093};
94
95/// \brief A base constant and all its rebased constants.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000096struct ConstantInfo {
97 ConstantInt *BaseConstant;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000098 RebasedConstantListType RebasedConstants;
99};
100
Juergen Ributzka5429c062014-03-21 06:04:36 +0000101/// \brief The constant hoisting pass.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000102class ConstantHoisting : public FunctionPass {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000103 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
104 typedef std::vector<ConstantCandidate> ConstCandVecType;
105
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000106 const TargetTransformInfo *TTI;
107 DominatorTree *DT;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000108 BasicBlock *Entry;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000109
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000110 /// Keeps track of constant candidates found in the function.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000111 ConstCandVecType ConstCandVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000112
Juergen Ributzka5429c062014-03-21 06:04:36 +0000113 /// Keep track of cast instructions we already cloned.
114 SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
115
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000116 /// These are the final constants we decided to hoist.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000117 SmallVector<ConstantInfo, 8> ConstantVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000118public:
119 static char ID; // Pass identification, replacement for typeid
Juergen Ributzka5429c062014-03-21 06:04:36 +0000120 ConstantHoisting() : FunctionPass(ID), TTI(0), DT(0), Entry(0) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000121 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
122 }
123
Juergen Ributzka5429c062014-03-21 06:04:36 +0000124 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000125
Craig Topper3e4c6972014-03-05 09:10:37 +0000126 const char *getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000127
Craig Topper3e4c6972014-03-05 09:10:37 +0000128 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000129 AU.setPreservesCFG();
130 AU.addRequired<DominatorTreeWrapperPass>();
131 AU.addRequired<TargetTransformInfo>();
132 }
133
134private:
Juergen Ributzka5429c062014-03-21 06:04:36 +0000135 /// \brief Initialize the pass.
136 void setup(Function &Fn) {
137 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
138 TTI = &getAnalysis<TargetTransformInfo>();
139 Entry = &Fn.getEntryBlock();
140 }
141
142 /// \brief Cleanup.
143 void cleanup() {
144 ConstantVec.clear();
145 ClonedCastMap.clear();
146 ConstCandVec.clear();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000147
148 TTI = nullptr;
149 DT = nullptr;
150 Entry = nullptr;
151 }
152
153 Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
154 Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000155 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
156 Instruction *Inst, unsigned Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000157 ConstantInt *ConstInt);
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000158 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
159 Instruction *Inst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000160 void collectConstantCandidates(Function &Fn);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000161 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000162 ConstCandVecType::iterator E);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000163 void findBaseConstants();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000164 void emitBaseConstants(Instruction *Base, Constant *Offset,
165 const ConstantUser &ConstUser);
166 bool emitBaseConstants();
167 void deleteDeadCastInst() const;
168 bool optimizeConstants(Function &Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000169};
170}
171
172char ConstantHoisting::ID = 0;
173INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
174 false, false)
175INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
176INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
177INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
178 false, false)
179
180FunctionPass *llvm::createConstantHoistingPass() {
181 return new ConstantHoisting();
182}
183
184/// \brief Perform the constant hoisting optimization for the given function.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000185bool ConstantHoisting::runOnFunction(Function &Fn) {
186 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
187 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000188
Juergen Ributzka5429c062014-03-21 06:04:36 +0000189 setup(Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000190
Juergen Ributzka5429c062014-03-21 06:04:36 +0000191 bool MadeChange = optimizeConstants(Fn);
192
193 if (MadeChange) {
194 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
195 << Fn.getName() << '\n');
196 DEBUG(dbgs() << Fn);
197 }
198 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
199
200 cleanup();
201
202 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000203}
204
Juergen Ributzka5429c062014-03-21 06:04:36 +0000205
206/// \brief Find the constant materialization insertion point.
207Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
208 unsigned Idx) const {
209 // The simple and common case.
210 if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
211 return Inst;
212
213 // We can't insert directly before a phi node or landing pad. Insert before
214 // the terminator of the incoming or dominating block.
215 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
216 if (Idx != ~0U && isa<PHINode>(Inst))
217 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
218
219 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
220 return IDom->getTerminator();
221}
222
223/// \brief Find an insertion point that dominates all uses.
224Instruction *ConstantHoisting::
225findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
226 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000227 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000228 SmallPtrSet<BasicBlock *, 8> BBs;
229 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000230 for (auto const &U : RCI.Uses)
231 BBs.insert(U.Inst->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000232
233 if (BBs.count(Entry))
234 return &Entry->front();
235
236 while (BBs.size() >= 2) {
237 BasicBlock *BB, *BB1, *BB2;
238 BB1 = *BBs.begin();
239 BB2 = *std::next(BBs.begin());
240 BB = DT->findNearestCommonDominator(BB1, BB2);
241 if (BB == Entry)
242 return &Entry->front();
243 BBs.erase(BB1);
244 BBs.erase(BB2);
245 BBs.insert(BB);
246 }
247 assert((BBs.size() == 1) && "Expected only one element.");
248 Instruction &FirstInst = (*BBs.begin())->front();
249 return findMatInsertPt(&FirstInst);
250}
251
252
253/// \brief Record constant integer ConstInt for instruction Inst at operand
254/// index Idx.
255///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000256/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000257/// could also be a cast instruction or a constant expression that uses the
258// constant integer.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000259void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
260 Instruction *Inst,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000261 unsigned Idx,
262 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000263 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000264 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000265 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000266 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000267 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000268 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000269 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000270 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000271 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000272
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000273 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000274 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000275 ConstCandMapType::iterator Itr;
276 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000277 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000278 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000279 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000280 Itr->second = ConstCandVec.size() - 1;
281 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000282 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
283 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
284 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
285 << " with cost " << Cost << '\n';
286 else
287 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
288 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
289 << Cost << '\n';
290 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000291 }
292}
293
Juergen Ributzka5429c062014-03-21 06:04:36 +0000294/// \brief Scan the instruction for expensive integer constants and record them
295/// in the constant candidate vector.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000296void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
297 Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000298 // Skip all cast instructions. They are visited indirectly later on.
299 if (Inst->isCast())
300 return;
301
302 // Can't handle inline asm. Skip it.
303 if (auto Call = dyn_cast<CallInst>(Inst))
304 if (isa<InlineAsm>(Call->getCalledValue()))
305 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000306
307 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000308 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
309 Value *Opnd = Inst->getOperand(Idx);
310
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000311 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000312 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000313 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000314 continue;
315 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000316
317 // Visit cast instructions that have constant integers.
318 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
319 // Only visit cast instructions, which have been skipped. All other
320 // instructions should have already been visited.
321 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000322 continue;
323
Juergen Ributzka5429c062014-03-21 06:04:36 +0000324 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
325 // Pretend the constant is directly used by the instruction and ignore
326 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000327 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000328 continue;
329 }
330 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000331
332 // Visit constant expressions that have constant integers.
333 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
334 // Only visit constant cast expressions.
335 if (!ConstExpr->isCast())
336 continue;
337
338 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
339 // Pretend the constant is directly used by the instruction and ignore
340 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000341 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000342 continue;
343 }
344 }
345 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000346}
347
348/// \brief Collect all integer constants in the function that cannot be folded
349/// into an instruction itself.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000350void ConstantHoisting::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000351 ConstCandMapType ConstCandMap;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000352 for (Function::iterator BB : Fn)
353 for (BasicBlock::iterator Inst : *BB)
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000354 collectConstantCandidates(ConstCandMap, Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000355}
356
357/// \brief Find the base constant within the given range and rebase all other
358/// constants with respect to the base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000359void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000360 ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000361 auto MaxCostItr = S;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000362 unsigned NumUses = 0;
363 // Use the constant that has the maximum cost as base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000364 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
365 NumUses += ConstCand->Uses.size();
366 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
367 MaxCostItr = ConstCand;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000368 }
369
370 // Don't hoist constants that have only one use.
371 if (NumUses <= 1)
372 return;
373
Juergen Ributzka5429c062014-03-21 06:04:36 +0000374 ConstantInfo ConstInfo;
375 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
376 Type *Ty = ConstInfo.BaseConstant->getType();
377
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000378 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000379 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
380 APInt Diff = ConstCand->ConstInt->getValue() -
381 ConstInfo.BaseConstant->getValue();
382 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
383 ConstInfo.RebasedConstants.push_back(
384 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000385 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000386 ConstantVec.push_back(ConstInfo);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000387}
388
Juergen Ributzka5429c062014-03-21 06:04:36 +0000389/// \brief Finds and combines constant candidates that can be easily
390/// rematerialized with an add from a common base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000391void ConstantHoisting::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000392 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000393 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
394 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
395 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
396 return LHS.ConstInt->getType()->getBitWidth() <
397 RHS.ConstInt->getType()->getBitWidth();
398 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000399 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000400
Juergen Ributzka5429c062014-03-21 06:04:36 +0000401 // Simple linear scan through the sorted constant candidate vector for viable
402 // merge candidates.
403 auto MinValItr = ConstCandVec.begin();
404 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
405 CC != E; ++CC) {
406 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000407 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000408 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000409 if ((Diff.getBitWidth() <= 64) &&
410 TTI->isLegalAddImmediate(Diff.getSExtValue()))
411 continue;
412 }
413 // We either have now a different constant type or the constant is not in
414 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000415 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000416 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000417 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000418 }
419 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000420 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000421}
422
Juergen Ributzkae802d502014-03-22 01:49:27 +0000423/// \brief Updates the operand at Idx in instruction Inst with the result of
424/// instruction Mat. If the instruction is a PHI node then special
425/// handling for duplicate values form the same incomming basic block is
426/// required.
427/// \return The update will always succeed, but the return value indicated if
428/// Mat was used for the update or not.
429static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
430 if (auto PHI = dyn_cast<PHINode>(Inst)) {
431 // Check if any previous operand of the PHI node has the same incoming basic
432 // block. This is a very odd case that happens when the incoming basic block
433 // has a switch statement. In this case use the same value as the previous
434 // operand(s), otherwise we will fail verification due to different values.
435 // The values are actually the same, but the variable names are different
436 // and the verifier doesn't like that.
437 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
438 for (unsigned i = 0; i < Idx; ++i) {
439 if (PHI->getIncomingBlock(i) == IncomingBB) {
440 Value *IncomingVal = PHI->getIncomingValue(i);
441 Inst->setOperand(Idx, IncomingVal);
442 return false;
443 }
444 }
445 }
446
447 Inst->setOperand(Idx, Mat);
448 return true;
449}
450
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000451/// \brief Emit materialization code for all rebased constants and update their
452/// users.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000453void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
454 const ConstantUser &ConstUser) {
455 Instruction *Mat = Base;
456 if (Offset) {
457 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
458 ConstUser.OpndIdx);
459 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
460 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000461
Juergen Ributzka5429c062014-03-21 06:04:36 +0000462 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
463 << " + " << *Offset << ") in BB "
464 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
465 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
466 }
467 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000468
Juergen Ributzka5429c062014-03-21 06:04:36 +0000469 // Visit constant integer.
470 if (isa<ConstantInt>(Opnd)) {
471 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000472 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
473 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000474 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000475 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000476 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000477
Juergen Ributzka5429c062014-03-21 06:04:36 +0000478 // Visit cast instruction.
479 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
480 assert(CastInst->isCast() && "Expected an cast instruction!");
481 // Check if we already have visited this cast instruction before to avoid
482 // unnecessary cloning.
483 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
484 if (!ClonedCastInst) {
485 ClonedCastInst = CastInst->clone();
486 ClonedCastInst->setOperand(0, Mat);
487 ClonedCastInst->insertAfter(CastInst);
488 // Use the same debug location as the original cast instruction.
489 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
490 DEBUG(dbgs() << "Clone instruction: " << *ClonedCastInst << '\n'
491 << "To : " << *CastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000492 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000493
494 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000495 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000496 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
497 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000498 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000499
500 // Visit constant expression.
501 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
502 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
503 ConstExprInst->setOperand(0, Mat);
504 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
505 ConstUser.OpndIdx));
506
507 // Use the same debug location as the instruction we are about to update.
508 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
509
510 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
511 << "From : " << *ConstExpr << '\n');
512 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000513 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
514 ConstExprInst->eraseFromParent();
515 if (Offset)
516 Mat->eraseFromParent();
517 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000518 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
519 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000520 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000521}
522
523/// \brief Hoist and hide the base constant behind a bitcast and emit
524/// materialization code for derived constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000525bool ConstantHoisting::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000526 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000527 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000528 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000529 Instruction *IP = findConstantInsertionPoint(ConstInfo);
530 IntegerType *Ty = ConstInfo.BaseConstant->getType();
531 Instruction *Base =
532 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
533 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
534 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000535 NumConstantsHoisted++;
536
537 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000538 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000539 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000540 for (auto const &U : RCI.Uses)
541 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000542 }
543
544 // Use the same debug location as the last user of the constant.
545 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000546 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000547 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000548 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000549
550 // Correct for base constant, which we counted above too.
551 NumConstantsRebased--;
552 MadeChange = true;
553 }
554 return MadeChange;
555}
556
Juergen Ributzka5429c062014-03-21 06:04:36 +0000557/// \brief Check all cast instructions we made a copy of and remove them if they
558/// have no more users.
559void ConstantHoisting::deleteDeadCastInst() const {
560 for (auto const &I : ClonedCastMap)
561 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000562 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000563}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000564
Juergen Ributzka5429c062014-03-21 06:04:36 +0000565/// \brief Optimize expensive integer constants in the given function.
566bool ConstantHoisting::optimizeConstants(Function &Fn) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000567 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000568 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000569
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000570 // There are no constant candidates to worry about.
571 if (ConstCandVec.empty())
572 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000573
574 // Combine constants that can be easily materialized with an add from a common
575 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000576 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000577
Juergen Ributzka5429c062014-03-21 06:04:36 +0000578 // There are no constants to emit.
579 if (ConstantVec.empty())
580 return false;
581
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000582 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000583 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000584 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000585
Juergen Ributzka5429c062014-03-21 06:04:36 +0000586 // Cleanup dead instructions.
587 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000588
589 return MadeChange;
590}