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 expressions. For example:
33 // %0 = load i64* inttoptr (i64 big_constant to i64*)
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
37 #include "llvm/ADT/APInt.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/None.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/Analysis/BlockFrequencyInfo.h"
45 #include "llvm/Analysis/TargetTransformInfo.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/IR/BasicBlock.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/BlockFrequency.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Transforms/Scalar.h"
72 using namespace consthoist;
74 #define DEBUG_TYPE "consthoist"
76 STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
77 STATISTIC(NumConstantsRebased, "Number of constants rebased");
79 static cl::opt<bool> ConstHoistWithBlockFrequency(
80 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
81 cl::desc("Enable the use of the block frequency analysis to reduce the "
82 "chance to execute const materialization more frequently than "
83 "without hoisting."));
87 /// The constant hoisting pass.
88 class ConstantHoistingLegacyPass : public FunctionPass {
90 static char ID; // Pass identification, replacement for typeid
92 ConstantHoistingLegacyPass() : FunctionPass(ID) {
93 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
96 bool runOnFunction(Function &Fn) override;
98 StringRef getPassName() const override { return "Constant Hoisting"; }
100 void getAnalysisUsage(AnalysisUsage &AU) const override {
101 AU.setPreservesCFG();
102 if (ConstHoistWithBlockFrequency)
103 AU.addRequired<BlockFrequencyInfoWrapperPass>();
104 AU.addRequired<DominatorTreeWrapperPass>();
105 AU.addRequired<TargetTransformInfoWrapperPass>();
108 void releaseMemory() override { Impl.releaseMemory(); }
111 ConstantHoistingPass Impl;
114 } // end anonymous namespace
116 char ConstantHoistingLegacyPass::ID = 0;
118 INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
119 "Constant Hoisting", false, false)
120 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
121 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
122 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
123 INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
124 "Constant Hoisting", false, false)
126 FunctionPass *llvm::createConstantHoistingPass() {
127 return new ConstantHoistingLegacyPass();
130 /// Perform the constant hoisting optimization for the given function.
131 bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
132 if (skipFunction(Fn))
135 LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
136 LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
139 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
140 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
141 ConstHoistWithBlockFrequency
142 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
147 LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
148 << Fn.getName() << '\n');
149 LLVM_DEBUG(dbgs() << Fn);
151 LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
156 /// Find the constant materialization insertion point.
157 Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
158 unsigned Idx) const {
159 // If the operand is a cast instruction, then we have to materialize the
160 // constant before the cast instruction.
162 Value *Opnd = Inst->getOperand(Idx);
163 if (auto CastInst = dyn_cast<Instruction>(Opnd))
164 if (CastInst->isCast())
168 // The simple and common case. This also includes constant expressions.
169 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
172 // We can't insert directly before a phi node or an eh pad. Insert before
173 // the terminator of the incoming or dominating block.
174 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
175 if (Idx != ~0U && isa<PHINode>(Inst))
176 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
178 // This must be an EH pad. Iterate over immediate dominators until we find a
179 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
181 auto IDom = DT->getNode(Inst->getParent())->getIDom();
182 while (IDom->getBlock()->isEHPad()) {
183 assert(Entry != IDom->getBlock() && "eh pad in entry block");
184 IDom = IDom->getIDom();
187 return IDom->getBlock()->getTerminator();
190 /// Given \p BBs as input, find another set of BBs which collectively
191 /// dominates \p BBs and have the minimal sum of frequencies. Return the BB
192 /// set found in \p BBs.
193 static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
195 SmallPtrSet<BasicBlock *, 8> &BBs) {
196 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
197 // Nodes on the current path to the root.
198 SmallPtrSet<BasicBlock *, 8> Path;
199 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
200 // dominated by any other blocks in set 'BBs', and all nodes in the path
201 // in the dominator tree from Entry to 'BB'.
202 SmallPtrSet<BasicBlock *, 16> Candidates;
203 for (auto BB : BBs) {
205 // Walk up the dominator tree until Entry or another BB in BBs
206 // is reached. Insert the nodes on the way to the Path.
207 BasicBlock *Node = BB;
208 // The "Path" is a candidate path to be added into Candidates set.
209 bool isCandidate = false;
212 if (Node == Entry || Candidates.count(Node)) {
216 assert(DT.getNode(Node)->getIDom() &&
217 "Entry doens't dominate current Node");
218 Node = DT.getNode(Node)->getIDom()->getBlock();
219 } while (!BBs.count(Node));
221 // If isCandidate is false, Node is another Block in BBs dominating
222 // current 'BB'. Drop the nodes on the Path.
226 // Add nodes on the Path into Candidates.
227 Candidates.insert(Path.begin(), Path.end());
230 // Sort the nodes in Candidates in top-down order and save the nodes
233 SmallVector<BasicBlock *, 16> Orders;
234 Orders.push_back(Entry);
235 while (Idx != Orders.size()) {
236 BasicBlock *Node = Orders[Idx++];
237 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
238 if (Candidates.count(ChildDomNode->getBlock()))
239 Orders.push_back(ChildDomNode->getBlock());
243 // Visit Orders in bottom-up order.
244 using InsertPtsCostPair =
245 std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
247 // InsertPtsMap is a map from a BB to the best insertion points for the
248 // subtree of BB (subtree not including the BB itself).
249 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
250 InsertPtsMap.reserve(Orders.size() + 1);
251 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
252 BasicBlock *Node = *RIt;
253 bool NodeInBBs = BBs.count(Node);
254 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
255 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
257 // Return the optimal insert points in BBs.
260 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
261 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
264 BBs.insert(InsertPts.begin(), InsertPts.end());
268 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
269 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
270 // will update its parent's ParentInsertPts and ParentPtsFreq.
271 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
272 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
273 // Choose to insert in Node or in subtree of Node.
274 // Don't hoist to EHPad because we may not find a proper place to insert
276 // If the total frequency of InsertPts is the same as the frequency of the
277 // target Node, and InsertPts contains more than one nodes, choose hoisting
278 // to reduce code size.
281 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
282 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
283 ParentInsertPts.insert(Node);
284 ParentPtsFreq += BFI.getBlockFreq(Node);
286 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
287 ParentPtsFreq += InsertPtsFreq;
292 /// Find an insertion point that dominates all uses.
293 SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
294 const ConstantInfo &ConstInfo) const {
295 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
296 // Collect all basic blocks.
297 SmallPtrSet<BasicBlock *, 8> BBs;
298 SmallPtrSet<Instruction *, 8> InsertPts;
299 for (auto const &RCI : ConstInfo.RebasedConstants)
300 for (auto const &U : RCI.Uses)
301 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
303 if (BBs.count(Entry)) {
304 InsertPts.insert(&Entry->front());
309 findBestInsertionSet(*DT, *BFI, Entry, BBs);
310 for (auto BB : BBs) {
311 BasicBlock::iterator InsertPt = BB->begin();
312 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
314 InsertPts.insert(&*InsertPt);
319 while (BBs.size() >= 2) {
320 BasicBlock *BB, *BB1, *BB2;
322 BB2 = *std::next(BBs.begin());
323 BB = DT->findNearestCommonDominator(BB1, BB2);
325 InsertPts.insert(&Entry->front());
332 assert((BBs.size() == 1) && "Expected only one element.");
333 Instruction &FirstInst = (*BBs.begin())->front();
334 InsertPts.insert(findMatInsertPt(&FirstInst));
338 /// Record constant integer ConstInt for instruction Inst at operand
341 /// The operand at index Idx is not necessarily the constant integer itself. It
342 /// could also be a cast instruction or a constant expression that uses the
344 void ConstantHoistingPass::collectConstantCandidates(
345 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
346 ConstantInt *ConstInt) {
348 // Ask the target about the cost of materializing the constant for the given
349 // instruction and operand index.
350 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
351 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
352 ConstInt->getValue(), ConstInt->getType());
354 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
355 ConstInt->getType());
357 // Ignore cheap integer constants.
358 if (Cost > TargetTransformInfo::TCC_Basic) {
359 ConstCandMapType::iterator Itr;
361 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
363 ConstCandVec.push_back(ConstantCandidate(ConstInt));
364 Itr->second = ConstCandVec.size() - 1;
366 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
367 LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
368 << "Collect constant " << *ConstInt << " from " << *Inst
369 << " with cost " << Cost << '\n';
370 else dbgs() << "Collect constant " << *ConstInt
371 << " indirectly from " << *Inst << " via "
372 << *Inst->getOperand(Idx) << " with cost " << Cost
377 /// Check the operand for instruction Inst at index Idx.
378 void ConstantHoistingPass::collectConstantCandidates(
379 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
380 Value *Opnd = Inst->getOperand(Idx);
382 // Visit constant integers.
383 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
384 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
388 // Visit cast instructions that have constant integers.
389 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
390 // Only visit cast instructions, which have been skipped. All other
391 // instructions should have already been visited.
392 if (!CastInst->isCast())
395 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
396 // Pretend the constant is directly used by the instruction and ignore
397 // the cast instruction.
398 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
403 // Visit constant expressions that have constant integers.
404 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
405 // Only visit constant cast expressions.
406 if (!ConstExpr->isCast())
409 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
410 // Pretend the constant is directly used by the instruction and ignore
411 // the constant expression.
412 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
418 /// Scan the instruction for expensive integer constants and record them
419 /// in the constant candidate vector.
420 void ConstantHoistingPass::collectConstantCandidates(
421 ConstCandMapType &ConstCandMap, Instruction *Inst) {
422 // Skip all cast instructions. They are visited indirectly later on.
426 // Scan all operands.
427 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
428 // The cost of materializing the constants (defined in
429 // `TargetTransformInfo::getIntImmCost`) for instructions which only take
430 // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
431 // it's safe for us to collect constant candidates from all IntrinsicInsts.
432 if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
433 collectConstantCandidates(ConstCandMap, Inst, Idx);
435 } // end of for all operands
438 /// Collect all integer constants in the function that cannot be folded
439 /// into an instruction itself.
440 void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
441 ConstCandMapType ConstCandMap;
442 for (BasicBlock &BB : Fn)
443 for (Instruction &Inst : BB)
444 collectConstantCandidates(ConstCandMap, &Inst);
447 // This helper function is necessary to deal with values that have different
448 // bit widths (APInt Operator- does not like that). If the value cannot be
449 // represented in uint64 we return an "empty" APInt. This is then interpreted
450 // as the value is not in range.
451 static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
452 Optional<APInt> Res = None;
453 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
454 V1.getBitWidth() : V2.getBitWidth();
455 uint64_t LimVal1 = V1.getLimitedValue();
456 uint64_t LimVal2 = V2.getLimitedValue();
458 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
461 uint64_t Diff = LimVal1 - LimVal2;
462 return APInt(BW, Diff, true);
465 // From a list of constants, one needs to picked as the base and the other
466 // constants will be transformed into an offset from that base constant. The
467 // question is which we can pick best? For example, consider these constants
468 // and their number of uses:
470 // Constants| 2 | 4 | 12 | 42 |
471 // NumUses | 3 | 2 | 8 | 7 |
473 // Selecting constant 12 because it has the most uses will generate negative
474 // offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
475 // offsets lead to less optimal code generation, then there might be better
476 // solutions. Suppose immediates in the range of 0..35 are most optimally
477 // supported by the architecture, then selecting constant 2 is most optimal
478 // because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
479 // range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
480 // have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
481 // selecting the base constant the range of the offsets is a very important
482 // factor too that we take into account here. This algorithm calculates a total
483 // costs for selecting a constant as the base and substract the costs if
484 // immediates are out of range. It has quadratic complexity, so we call this
485 // function only when we're optimising for size and there are less than 100
486 // constants, we fall back to the straightforward algorithm otherwise
487 // which does not do all the offset calculations.
489 ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
490 ConstCandVecType::iterator E,
491 ConstCandVecType::iterator &MaxCostItr) {
492 unsigned NumUses = 0;
494 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
495 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
496 NumUses += ConstCand->Uses.size();
497 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
498 MaxCostItr = ConstCand;
503 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
505 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
506 auto Value = ConstCand->ConstInt->getValue();
507 Type *Ty = ConstCand->ConstInt->getType();
509 NumUses += ConstCand->Uses.size();
510 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
513 for (auto User : ConstCand->Uses) {
514 unsigned Opcode = User.Inst->getOpcode();
515 unsigned OpndIdx = User.OpndIdx;
516 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
517 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
519 for (auto C2 = S; C2 != E; ++C2) {
520 Optional<APInt> Diff = calculateOffsetDiff(
521 C2->ConstInt->getValue(),
522 ConstCand->ConstInt->getValue());
525 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
527 LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
528 << "has penalty: " << ImmCosts << "\n"
529 << "Adjusted cost: " << Cost << "\n");
533 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
534 if (Cost > MaxCost) {
536 MaxCostItr = ConstCand;
537 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
544 /// Find the base constant within the given range and rebase all other
545 /// constants with respect to the base constant.
546 void ConstantHoistingPass::findAndMakeBaseConstant(
547 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
549 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
551 // Don't hoist constants that have only one use.
555 ConstantInfo ConstInfo;
556 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
557 Type *Ty = ConstInfo.BaseConstant->getType();
559 // Rebase the constants with respect to the base constant.
560 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
561 APInt Diff = ConstCand->ConstInt->getValue() -
562 ConstInfo.BaseConstant->getValue();
563 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
564 ConstInfo.RebasedConstants.push_back(
565 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
567 ConstantVec.push_back(std::move(ConstInfo));
570 /// Finds and combines constant candidates that can be easily
571 /// rematerialized with an add from a common base constant.
572 void ConstantHoistingPass::findBaseConstants() {
573 // Sort the constants by value and type. This invalidates the mapping!
574 llvm::sort(ConstCandVec.begin(), ConstCandVec.end(),
575 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
576 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
577 return LHS.ConstInt->getType()->getBitWidth() <
578 RHS.ConstInt->getType()->getBitWidth();
579 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
582 // Simple linear scan through the sorted constant candidate vector for viable
584 auto MinValItr = ConstCandVec.begin();
585 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
587 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
588 // Check if the constant is in range of an add with immediate.
589 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
590 if ((Diff.getBitWidth() <= 64) &&
591 TTI->isLegalAddImmediate(Diff.getSExtValue()))
594 // We either have now a different constant type or the constant is not in
595 // range of an add with immediate anymore.
596 findAndMakeBaseConstant(MinValItr, CC);
597 // Start a new base constant search.
600 // Finalize the last base constant search.
601 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
604 /// Updates the operand at Idx in instruction Inst with the result of
605 /// instruction Mat. If the instruction is a PHI node then special
606 /// handling for duplicate values form the same incoming basic block is
608 /// \return The update will always succeed, but the return value indicated if
609 /// Mat was used for the update or not.
610 static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
611 if (auto PHI = dyn_cast<PHINode>(Inst)) {
612 // Check if any previous operand of the PHI node has the same incoming basic
613 // block. This is a very odd case that happens when the incoming basic block
614 // has a switch statement. In this case use the same value as the previous
615 // operand(s), otherwise we will fail verification due to different values.
616 // The values are actually the same, but the variable names are different
617 // and the verifier doesn't like that.
618 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
619 for (unsigned i = 0; i < Idx; ++i) {
620 if (PHI->getIncomingBlock(i) == IncomingBB) {
621 Value *IncomingVal = PHI->getIncomingValue(i);
622 Inst->setOperand(Idx, IncomingVal);
628 Inst->setOperand(Idx, Mat);
632 /// Emit materialization code for all rebased constants and update their
634 void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
636 const ConstantUser &ConstUser) {
637 Instruction *Mat = Base;
639 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
641 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
642 "const_mat", InsertionPt);
644 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
645 << " + " << *Offset << ") in BB "
646 << Mat->getParent()->getName() << '\n'
648 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
650 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
652 // Visit constant integer.
653 if (isa<ConstantInt>(Opnd)) {
654 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
655 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
656 Mat->eraseFromParent();
657 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
661 // Visit cast instruction.
662 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
663 assert(CastInst->isCast() && "Expected an cast instruction!");
664 // Check if we already have visited this cast instruction before to avoid
665 // unnecessary cloning.
666 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
667 if (!ClonedCastInst) {
668 ClonedCastInst = CastInst->clone();
669 ClonedCastInst->setOperand(0, Mat);
670 ClonedCastInst->insertAfter(CastInst);
671 // Use the same debug location as the original cast instruction.
672 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
673 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
674 << "To : " << *ClonedCastInst << '\n');
677 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
678 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
679 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
683 // Visit constant expression.
684 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
685 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
686 ConstExprInst->setOperand(0, Mat);
687 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
690 // Use the same debug location as the instruction we are about to update.
691 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
693 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
694 << "From : " << *ConstExpr << '\n');
695 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
696 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
697 ConstExprInst->eraseFromParent();
699 Mat->eraseFromParent();
701 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
706 /// Hoist and hide the base constant behind a bitcast and emit
707 /// materialization code for derived constants.
708 bool ConstantHoistingPass::emitBaseConstants() {
709 bool MadeChange = false;
710 for (auto const &ConstInfo : ConstantVec) {
711 // Hoist and hide the base constant behind a bitcast.
712 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
713 assert(!IPSet.empty() && "IPSet is empty");
715 unsigned UsesNum = 0;
716 unsigned ReBasesNum = 0;
717 for (Instruction *IP : IPSet) {
718 IntegerType *Ty = ConstInfo.BaseConstant->getType();
720 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
722 Base->setDebugLoc(IP->getDebugLoc());
724 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant
725 << ") to BB " << IP->getParent()->getName() << '\n'
728 // Emit materialization code for all rebased constants.
730 for (auto const &RCI : ConstInfo.RebasedConstants) {
731 for (auto const &U : RCI.Uses) {
733 BasicBlock *OrigMatInsertBB =
734 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
735 // If Base constant is to be inserted in multiple places,
736 // generate rebase for U using the Base dominating U.
737 if (IPSet.size() == 1 ||
738 DT->dominates(Base->getParent(), OrigMatInsertBB)) {
739 emitBaseConstants(Base, RCI.Offset, U);
743 Base->setDebugLoc(DILocation::getMergedLocation(Base->getDebugLoc(), U.Inst->getDebugLoc()));
748 // Use the same debug location as the last user of the constant.
749 assert(!Base->use_empty() && "The use list is empty!?");
750 assert(isa<Instruction>(Base->user_back()) &&
751 "All uses should be instructions.");
755 // Expect all uses are rebased after rebase is done.
756 assert(UsesNum == ReBasesNum && "Not all uses are rebased");
758 NumConstantsHoisted++;
760 // Base constant is also included in ConstInfo.RebasedConstants, so
761 // deduct 1 from ConstInfo.RebasedConstants.size().
762 NumConstantsRebased = ConstInfo.RebasedConstants.size() - 1;
769 /// Check all cast instructions we made a copy of and remove them if they
770 /// have no more users.
771 void ConstantHoistingPass::deleteDeadCastInst() const {
772 for (auto const &I : ClonedCastMap)
773 if (I.first->use_empty())
774 I.first->eraseFromParent();
777 /// Optimize expensive integer constants in the given function.
778 bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
779 DominatorTree &DT, BlockFrequencyInfo *BFI,
784 this->Entry = &Entry;
785 // Collect all constant candidates.
786 collectConstantCandidates(Fn);
788 // There are no constant candidates to worry about.
789 if (ConstCandVec.empty())
792 // Combine constants that can be easily materialized with an add from a common
796 // There are no constants to emit.
797 if (ConstantVec.empty())
800 // Finally hoist the base constant and emit materialization code for dependent
802 bool MadeChange = emitBaseConstants();
804 // Cleanup dead instructions.
805 deleteDeadCastInst();
810 PreservedAnalyses ConstantHoistingPass::run(Function &F,
811 FunctionAnalysisManager &AM) {
812 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
813 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
814 auto BFI = ConstHoistWithBlockFrequency
815 ? &AM.getResult<BlockFrequencyAnalysis>(F)
817 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
818 return PreservedAnalyses::all();
820 PreservedAnalyses PA;
821 PA.preserveSet<CFGAnalyses>();