1 //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
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.
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 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "consthoist"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #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"
46 #include "llvm/Support/Debug.h"
50 STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
51 STATISTIC(NumConstantsRebased, "Number of constants rebased");
55 struct RebasedConstantInfo;
57 typedef SmallVector<ConstantUser, 8> ConstantUseListType;
58 typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
60 /// \brief Keeps track of the user of a constant and the operand index where the
66 ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
69 /// \brief Keeps track of a constant candidate and its usees.
70 struct ConstantCandidate {
71 ConstantUseListType Uses;
72 ConstantInt *ConstInt;
73 unsigned CumulativeCost;
75 ConstantCandidate(ConstantInt *ConstInt)
76 : ConstInt(ConstInt), CumulativeCost(0) { }
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));
85 /// \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.
87 struct RebasedConstantInfo {
88 ConstantUseListType Uses;
91 RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
92 : Uses(Uses), Offset(Offset) { }
95 /// \brief A base constant and all its rebased constants.
97 ConstantInt *BaseConstant;
98 RebasedConstantListType RebasedConstants;
101 /// \brief The constant hoisting pass.
102 class ConstantHoisting : public FunctionPass {
103 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
104 typedef std::vector<ConstantCandidate> ConstCandVecType;
106 const TargetTransformInfo *TTI;
110 /// Keeps track of constant candidates found in the function.
111 ConstCandMapType ConstCandMap;
112 ConstCandVecType ConstCandVec;
114 /// Keep track of cast instructions we already cloned.
115 SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
117 /// These are the final constants we decided to hoist.
118 SmallVector<ConstantInfo, 8> ConstantVec;
120 static char ID; // Pass identification, replacement for typeid
121 ConstantHoisting() : FunctionPass(ID), TTI(0), DT(0), Entry(0) {
122 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
125 bool runOnFunction(Function &Fn) override;
127 const char *getPassName() const override { return "Constant Hoisting"; }
129 void getAnalysisUsage(AnalysisUsage &AU) const override {
130 AU.setPreservesCFG();
131 AU.addRequired<DominatorTreeWrapperPass>();
132 AU.addRequired<TargetTransformInfo>();
136 /// \brief Initialize the pass.
137 void setup(Function &Fn) {
138 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
139 TTI = &getAnalysis<TargetTransformInfo>();
140 Entry = &Fn.getEntryBlock();
146 ClonedCastMap.clear();
147 ConstCandVec.clear();
148 ConstCandMap.clear();
155 Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
156 Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
157 void collectConstantCandidates(Instruction *Inst, unsigned Idx,
158 ConstantInt *ConstInt);
159 void collectConstantCandidates(Instruction *Inst);
160 void collectConstantCandidates(Function &Fn);
161 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
162 ConstCandVecType::iterator E);
163 void findBaseConstants();
164 void emitBaseConstants(Instruction *Base, Constant *Offset,
165 const ConstantUser &ConstUser);
166 bool emitBaseConstants();
167 void deleteDeadCastInst() const;
168 bool optimizeConstants(Function &Fn);
172 char ConstantHoisting::ID = 0;
173 INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
175 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
176 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
177 INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
180 FunctionPass *llvm::createConstantHoistingPass() {
181 return new ConstantHoisting();
184 /// \brief Perform the constant hoisting optimization for the given function.
185 bool ConstantHoisting::runOnFunction(Function &Fn) {
186 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
187 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
191 bool MadeChange = optimizeConstants(Fn);
194 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
195 << Fn.getName() << '\n');
198 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
206 /// \brief Find the constant materialization insertion point.
207 Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
208 unsigned Idx) const {
209 // The simple and common case.
210 if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
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();
219 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
220 return IDom->getTerminator();
223 /// \brief Find an insertion point that dominates all uses.
224 Instruction *ConstantHoisting::
225 findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
226 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
227 // Collect all basic blocks.
228 SmallPtrSet<BasicBlock *, 8> BBs;
229 for (auto const &RCI : ConstInfo.RebasedConstants)
230 for (auto const &U : RCI.Uses)
231 BBs.insert(U.Inst->getParent());
233 if (BBs.count(Entry))
234 return &Entry->front();
236 while (BBs.size() >= 2) {
237 BasicBlock *BB, *BB1, *BB2;
239 BB2 = *std::next(BBs.begin());
240 BB = DT->findNearestCommonDominator(BB1, BB2);
242 return &Entry->front();
247 assert((BBs.size() == 1) && "Expected only one element.");
248 Instruction &FirstInst = (*BBs.begin())->front();
249 return findMatInsertPt(&FirstInst);
253 /// \brief Record constant integer ConstInt for instruction Inst at operand
256 /// The operand at index Idx is not necessarily the constant inetger itself. It
257 /// could also be a cast instruction or a constant expression that uses the
259 void ConstantHoisting::collectConstantCandidates(Instruction *Inst,
261 ConstantInt *ConstInt) {
263 // Ask the target about the cost of materializing the constant for the given
265 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
266 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(),
267 ConstInt->getValue(), ConstInt->getType());
269 Cost = TTI->getIntImmCost(Inst->getOpcode(), ConstInt->getValue(),
270 ConstInt->getType());
272 // Ignore cheap integer constants.
273 if (Cost > TargetTransformInfo::TCC_Basic) {
274 ConstCandMapType::iterator Itr;
276 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
278 ConstCandVec.push_back(ConstantCandidate(ConstInt));
279 Itr->second = ConstCandVec.size() - 1;
281 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
282 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
283 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
284 << " with cost " << Cost << '\n';
286 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
287 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
293 /// \brief Scan the instruction for expensive integer constants and record them
294 /// in the constant candidate vector.
295 void ConstantHoisting::collectConstantCandidates(Instruction *Inst) {
296 // Skip all cast instructions. They are visited indirectly later on.
300 // Can't handle inline asm. Skip it.
301 if (auto Call = dyn_cast<CallInst>(Inst))
302 if (isa<InlineAsm>(Call->getCalledValue()))
305 // Scan all operands.
306 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
307 Value *Opnd = Inst->getOperand(Idx);
309 // Vist constant integers.
310 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
311 collectConstantCandidates(Inst, Idx, ConstInt);
315 // Visit cast instructions that have constant integers.
316 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
317 // Only visit cast instructions, which have been skipped. All other
318 // instructions should have already been visited.
319 if (!CastInst->isCast())
322 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
323 // Pretend the constant is directly used by the instruction and ignore
324 // the cast instruction.
325 collectConstantCandidates(Inst, Idx, ConstInt);
330 // Visit constant expressions that have constant integers.
331 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
332 // Only visit constant cast expressions.
333 if (!ConstExpr->isCast())
336 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
337 // Pretend the constant is directly used by the instruction and ignore
338 // the constant expression.
339 collectConstantCandidates(Inst, Idx, ConstInt);
343 } // end of for all operands
346 /// \brief Collect all integer constants in the function that cannot be folded
347 /// into an instruction itself.
348 void ConstantHoisting::collectConstantCandidates(Function &Fn) {
349 for (Function::iterator BB : Fn)
350 for (BasicBlock::iterator Inst : *BB)
351 collectConstantCandidates(Inst);
354 /// \brief Find the base constant within the given range and rebase all other
355 /// constants with respect to the base constant.
356 void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
357 ConstCandVecType::iterator E) {
359 unsigned NumUses = 0;
360 // Use the constant that has the maximum cost as base constant.
361 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
362 NumUses += ConstCand->Uses.size();
363 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
364 MaxCostItr = ConstCand;
367 // Don't hoist constants that have only one use.
371 ConstantInfo ConstInfo;
372 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
373 Type *Ty = ConstInfo.BaseConstant->getType();
375 // Rebase the constants with respect to the base constant.
376 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
377 APInt Diff = ConstCand->ConstInt->getValue() -
378 ConstInfo.BaseConstant->getValue();
379 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
380 ConstInfo.RebasedConstants.push_back(
381 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
383 ConstantVec.push_back(ConstInfo);
386 /// \brief Finds and combines constant candidates that can be easily
387 /// rematerialized with an add from a common base constant.
388 void ConstantHoisting::findBaseConstants() {
389 // Sort the constants by value and type. This invalidates the mapping!
390 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
391 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
392 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
393 return LHS.ConstInt->getType()->getBitWidth() <
394 RHS.ConstInt->getType()->getBitWidth();
395 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
398 // Simple linear scan through the sorted constant candidate vector for viable
400 auto MinValItr = ConstCandVec.begin();
401 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
403 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
404 // Check if the constant is in range of an add with immediate.
405 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
406 if ((Diff.getBitWidth() <= 64) &&
407 TTI->isLegalAddImmediate(Diff.getSExtValue()))
410 // We either have now a different constant type or the constant is not in
411 // range of an add with immediate anymore.
412 findAndMakeBaseConstant(MinValItr, CC);
413 // Start a new base constant search.
416 // Finalize the last base constant search.
417 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
420 /// \brief Emit materialization code for all rebased constants and update their
422 void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
423 const ConstantUser &ConstUser) {
424 Instruction *Mat = Base;
426 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
428 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
429 "const_mat", InsertionPt);
431 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
432 << " + " << *Offset << ") in BB "
433 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
434 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
436 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
438 // Visit constant integer.
439 if (isa<ConstantInt>(Opnd)) {
440 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
441 ConstUser.Inst->setOperand(ConstUser.OpndIdx, Mat);
442 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
446 // Visit cast instruction.
447 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
448 assert(CastInst->isCast() && "Expected an cast instruction!");
449 // Check if we already have visited this cast instruction before to avoid
450 // unnecessary cloning.
451 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
452 if (!ClonedCastInst) {
453 ClonedCastInst = CastInst->clone();
454 ClonedCastInst->setOperand(0, Mat);
455 ClonedCastInst->insertAfter(CastInst);
456 // Use the same debug location as the original cast instruction.
457 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
458 DEBUG(dbgs() << "Clone instruction: " << *ClonedCastInst << '\n'
459 << "To : " << *CastInst << '\n');
462 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
463 ConstUser.Inst->setOperand(ConstUser.OpndIdx, ClonedCastInst);
464 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
468 // Visit constant expression.
469 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
470 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
471 ConstExprInst->setOperand(0, Mat);
472 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
475 // Use the same debug location as the instruction we are about to update.
476 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
478 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
479 << "From : " << *ConstExpr << '\n');
480 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
481 ConstUser.Inst->setOperand(ConstUser.OpndIdx, ConstExprInst);
482 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
487 /// \brief Hoist and hide the base constant behind a bitcast and emit
488 /// materialization code for derived constants.
489 bool ConstantHoisting::emitBaseConstants() {
490 bool MadeChange = false;
491 for (auto const &ConstInfo : ConstantVec) {
492 // Hoist and hide the base constant behind a bitcast.
493 Instruction *IP = findConstantInsertionPoint(ConstInfo);
494 IntegerType *Ty = ConstInfo.BaseConstant->getType();
496 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
497 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
498 << IP->getParent()->getName() << '\n' << *Base << '\n');
499 NumConstantsHoisted++;
501 // Emit materialization code for all rebased constants.
502 for (auto const &RCI : ConstInfo.RebasedConstants) {
503 NumConstantsRebased++;
504 for (auto const &U : RCI.Uses)
505 emitBaseConstants(Base, RCI.Offset, U);
508 // Use the same debug location as the last user of the constant.
509 assert(!Base->use_empty() && "The use list is empty!?");
510 assert(isa<Instruction>(Base->user_back()) &&
511 "All uses should be instructions.");
512 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
514 // Correct for base constant, which we counted above too.
515 NumConstantsRebased--;
521 /// \brief Check all cast instructions we made a copy of and remove them if they
522 /// have no more users.
523 void ConstantHoisting::deleteDeadCastInst() const {
524 for (auto const &I : ClonedCastMap)
525 if (I.first->use_empty())
526 I.first->removeFromParent();
529 /// \brief Optimize expensive integer constants in the given function.
530 bool ConstantHoisting::optimizeConstants(Function &Fn) {
531 // Collect all constant candidates.
532 collectConstantCandidates(Fn);
534 // There are no constant candidates to worry about.
535 if (ConstCandVec.empty())
538 // Combine constants that can be easily materialized with an add from a common
542 // There are no constants to emit.
543 if (ConstantVec.empty())
546 // Finally hoist the base constant and emit materializating code for dependent
548 bool MadeChange = emitBaseConstants();
550 // Cleanup dead instructions.
551 deleteDeadCastInst();