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/SmallSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/GetElementPtrTypeIterator.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Utils/Local.h"
51 using namespace consthoist;
53 #define DEBUG_TYPE "consthoist"
55 STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
56 STATISTIC(NumConstantsRebased, "Number of constants rebased");
58 static cl::opt<bool> ConstHoistWithBlockFrequency(
59 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
60 cl::desc("Enable the use of the block frequency analysis to reduce the "
61 "chance to execute const materialization more frequently than "
62 "without hoisting."));
65 /// \brief The constant hoisting pass.
66 class ConstantHoistingLegacyPass : public FunctionPass {
68 static char ID; // Pass identification, replacement for typeid
69 ConstantHoistingLegacyPass() : FunctionPass(ID) {
70 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
73 bool runOnFunction(Function &Fn) override;
75 StringRef getPassName() const override { return "Constant Hoisting"; }
77 void getAnalysisUsage(AnalysisUsage &AU) const override {
79 if (ConstHoistWithBlockFrequency)
80 AU.addRequired<BlockFrequencyInfoWrapperPass>();
81 AU.addRequired<DominatorTreeWrapperPass>();
82 AU.addRequired<TargetTransformInfoWrapperPass>();
85 void releaseMemory() override { Impl.releaseMemory(); }
88 ConstantHoistingPass Impl;
92 char ConstantHoistingLegacyPass::ID = 0;
93 INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
94 "Constant Hoisting", false, false)
95 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
96 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
97 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
98 INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
99 "Constant Hoisting", false, false)
101 FunctionPass *llvm::createConstantHoistingPass() {
102 return new ConstantHoistingLegacyPass();
105 /// \brief Perform the constant hoisting optimization for the given function.
106 bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
107 if (skipFunction(Fn))
110 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
111 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
114 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
115 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
116 ConstHoistWithBlockFrequency
117 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
122 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
123 << Fn.getName() << '\n');
126 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
132 /// \brief Find the constant materialization insertion point.
133 Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
134 unsigned Idx) const {
135 // If the operand is a cast instruction, then we have to materialize the
136 // constant before the cast instruction.
138 Value *Opnd = Inst->getOperand(Idx);
139 if (auto CastInst = dyn_cast<Instruction>(Opnd))
140 if (CastInst->isCast())
144 // The simple and common case. This also includes constant expressions.
145 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
148 // We can't insert directly before a phi node or an eh pad. Insert before
149 // the terminator of the incoming or dominating block.
150 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
151 if (Idx != ~0U && isa<PHINode>(Inst))
152 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
154 // This must be an EH pad. Iterate over immediate dominators until we find a
155 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
157 auto IDom = DT->getNode(Inst->getParent())->getIDom();
158 while (IDom->getBlock()->isEHPad()) {
159 assert(Entry != IDom->getBlock() && "eh pad in entry block");
160 IDom = IDom->getIDom();
163 return IDom->getBlock()->getTerminator();
166 /// \brief Given \p BBs as input, find another set of BBs which collectively
167 /// dominates \p BBs and have the minimal sum of frequencies. Return the BB
168 /// set found in \p BBs.
169 static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
171 SmallPtrSet<BasicBlock *, 8> &BBs) {
172 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
173 // Nodes on the current path to the root.
174 SmallPtrSet<BasicBlock *, 8> Path;
175 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
176 // dominated by any other blocks in set 'BBs', and all nodes in the path
177 // in the dominator tree from Entry to 'BB'.
178 SmallPtrSet<BasicBlock *, 16> Candidates;
179 for (auto BB : BBs) {
181 // Walk up the dominator tree until Entry or another BB in BBs
182 // is reached. Insert the nodes on the way to the Path.
183 BasicBlock *Node = BB;
184 // The "Path" is a candidate path to be added into Candidates set.
185 bool isCandidate = false;
188 if (Node == Entry || Candidates.count(Node)) {
192 assert(DT.getNode(Node)->getIDom() &&
193 "Entry doens't dominate current Node");
194 Node = DT.getNode(Node)->getIDom()->getBlock();
195 } while (!BBs.count(Node));
197 // If isCandidate is false, Node is another Block in BBs dominating
198 // current 'BB'. Drop the nodes on the Path.
202 // Add nodes on the Path into Candidates.
203 Candidates.insert(Path.begin(), Path.end());
206 // Sort the nodes in Candidates in top-down order and save the nodes
209 SmallVector<BasicBlock *, 16> Orders;
210 Orders.push_back(Entry);
211 while (Idx != Orders.size()) {
212 BasicBlock *Node = Orders[Idx++];
213 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
214 if (Candidates.count(ChildDomNode->getBlock()))
215 Orders.push_back(ChildDomNode->getBlock());
219 // Visit Orders in bottom-up order.
220 typedef std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>
222 // InsertPtsMap is a map from a BB to the best insertion points for the
223 // subtree of BB (subtree not including the BB itself).
224 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
225 InsertPtsMap.reserve(Orders.size() + 1);
226 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
227 BasicBlock *Node = *RIt;
228 bool NodeInBBs = BBs.count(Node);
229 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
230 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
232 // Return the optimal insert points in BBs.
235 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
236 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
239 BBs.insert(InsertPts.begin(), InsertPts.end());
243 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
244 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
245 // will update its parent's ParentInsertPts and ParentPtsFreq.
246 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
247 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
248 // Choose to insert in Node or in subtree of Node.
249 // Don't hoist to EHPad because we may not find a proper place to insert
251 // If the total frequency of InsertPts is the same as the frequency of the
252 // target Node, and InsertPts contains more than one nodes, choose hoisting
253 // to reduce code size.
256 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
257 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
258 ParentInsertPts.insert(Node);
259 ParentPtsFreq += BFI.getBlockFreq(Node);
261 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
262 ParentPtsFreq += InsertPtsFreq;
267 /// \brief Find an insertion point that dominates all uses.
268 SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
269 const ConstantInfo &ConstInfo) const {
270 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
271 // Collect all basic blocks.
272 SmallPtrSet<BasicBlock *, 8> BBs;
273 SmallPtrSet<Instruction *, 8> InsertPts;
274 for (auto const &RCI : ConstInfo.RebasedConstants)
275 for (auto const &U : RCI.Uses)
276 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
278 if (BBs.count(Entry)) {
279 InsertPts.insert(&Entry->front());
284 findBestInsertionSet(*DT, *BFI, Entry, BBs);
285 for (auto BB : BBs) {
286 BasicBlock::iterator InsertPt = BB->begin();
287 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
289 InsertPts.insert(&*InsertPt);
294 while (BBs.size() >= 2) {
295 BasicBlock *BB, *BB1, *BB2;
297 BB2 = *std::next(BBs.begin());
298 BB = DT->findNearestCommonDominator(BB1, BB2);
300 InsertPts.insert(&Entry->front());
307 assert((BBs.size() == 1) && "Expected only one element.");
308 Instruction &FirstInst = (*BBs.begin())->front();
309 InsertPts.insert(findMatInsertPt(&FirstInst));
314 /// \brief Record constant integer ConstInt for instruction Inst at operand
317 /// The operand at index Idx is not necessarily the constant integer itself. It
318 /// could also be a cast instruction or a constant expression that uses the
320 void ConstantHoistingPass::collectConstantCandidates(
321 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
322 ConstantInt *ConstInt) {
324 // Ask the target about the cost of materializing the constant for the given
325 // instruction and operand index.
326 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
327 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
328 ConstInt->getValue(), ConstInt->getType());
330 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
331 ConstInt->getType());
333 // Ignore cheap integer constants.
334 if (Cost > TargetTransformInfo::TCC_Basic) {
335 ConstCandMapType::iterator Itr;
337 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
339 ConstCandVec.push_back(ConstantCandidate(ConstInt));
340 Itr->second = ConstCandVec.size() - 1;
342 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
343 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
344 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
345 << " with cost " << Cost << '\n';
347 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
348 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
355 /// \brief Check the operand for instruction Inst at index Idx.
356 void ConstantHoistingPass::collectConstantCandidates(
357 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
358 Value *Opnd = Inst->getOperand(Idx);
360 // Visit constant integers.
361 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
362 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
366 // Visit cast instructions that have constant integers.
367 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
368 // Only visit cast instructions, which have been skipped. All other
369 // instructions should have already been visited.
370 if (!CastInst->isCast())
373 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
374 // Pretend the constant is directly used by the instruction and ignore
375 // the cast instruction.
376 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
381 // Visit constant expressions that have constant integers.
382 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
383 // Only visit constant cast expressions.
384 if (!ConstExpr->isCast())
387 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
388 // Pretend the constant is directly used by the instruction and ignore
389 // the constant expression.
390 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
397 /// \brief Scan the instruction for expensive integer constants and record them
398 /// in the constant candidate vector.
399 void ConstantHoistingPass::collectConstantCandidates(
400 ConstCandMapType &ConstCandMap, Instruction *Inst) {
401 // Skip all cast instructions. They are visited indirectly later on.
405 // Scan all operands.
406 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
407 // The cost of materializing the constants (defined in
408 // `TargetTransformInfo::getIntImmCost`) for instructions which only take
409 // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
410 // it's safe for us to collect constant candidates from all IntrinsicInsts.
411 if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
412 collectConstantCandidates(ConstCandMap, Inst, Idx);
414 } // end of for all operands
417 /// \brief Collect all integer constants in the function that cannot be folded
418 /// into an instruction itself.
419 void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
420 ConstCandMapType ConstCandMap;
421 for (BasicBlock &BB : Fn)
422 for (Instruction &Inst : BB)
423 collectConstantCandidates(ConstCandMap, &Inst);
426 // This helper function is necessary to deal with values that have different
427 // bit widths (APInt Operator- does not like that). If the value cannot be
428 // represented in uint64 we return an "empty" APInt. This is then interpreted
429 // as the value is not in range.
430 static llvm::Optional<APInt> calculateOffsetDiff(const APInt &V1,
432 llvm::Optional<APInt> Res = None;
433 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
434 V1.getBitWidth() : V2.getBitWidth();
435 uint64_t LimVal1 = V1.getLimitedValue();
436 uint64_t LimVal2 = V2.getLimitedValue();
438 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
441 uint64_t Diff = LimVal1 - LimVal2;
442 return APInt(BW, Diff, true);
445 // From a list of constants, one needs to picked as the base and the other
446 // constants will be transformed into an offset from that base constant. The
447 // question is which we can pick best? For example, consider these constants
448 // and their number of uses:
450 // Constants| 2 | 4 | 12 | 42 |
451 // NumUses | 3 | 2 | 8 | 7 |
453 // Selecting constant 12 because it has the most uses will generate negative
454 // offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
455 // offsets lead to less optimal code generation, then there might be better
456 // solutions. Suppose immediates in the range of 0..35 are most optimally
457 // supported by the architecture, then selecting constant 2 is most optimal
458 // because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
459 // range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
460 // have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
461 // selecting the base constant the range of the offsets is a very important
462 // factor too that we take into account here. This algorithm calculates a total
463 // costs for selecting a constant as the base and substract the costs if
464 // immediates are out of range. It has quadratic complexity, so we call this
465 // function only when we're optimising for size and there are less than 100
466 // constants, we fall back to the straightforward algorithm otherwise
467 // which does not do all the offset calculations.
469 ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
470 ConstCandVecType::iterator E,
471 ConstCandVecType::iterator &MaxCostItr) {
472 unsigned NumUses = 0;
474 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
475 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
476 NumUses += ConstCand->Uses.size();
477 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
478 MaxCostItr = ConstCand;
483 DEBUG(dbgs() << "== Maximize constants in range ==\n");
485 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
486 auto Value = ConstCand->ConstInt->getValue();
487 Type *Ty = ConstCand->ConstInt->getType();
489 NumUses += ConstCand->Uses.size();
490 DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue() << "\n");
492 for (auto User : ConstCand->Uses) {
493 unsigned Opcode = User.Inst->getOpcode();
494 unsigned OpndIdx = User.OpndIdx;
495 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
496 DEBUG(dbgs() << "Cost: " << Cost << "\n");
498 for (auto C2 = S; C2 != E; ++C2) {
499 llvm::Optional<APInt> Diff = calculateOffsetDiff(
500 C2->ConstInt->getValue(),
501 ConstCand->ConstInt->getValue());
504 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
506 DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
507 << "has penalty: " << ImmCosts << "\n"
508 << "Adjusted cost: " << Cost << "\n");
512 DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
513 if (Cost > MaxCost) {
515 MaxCostItr = ConstCand;
516 DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
523 /// \brief Find the base constant within the given range and rebase all other
524 /// constants with respect to the base constant.
525 void ConstantHoistingPass::findAndMakeBaseConstant(
526 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
528 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
530 // Don't hoist constants that have only one use.
534 ConstantInfo ConstInfo;
535 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
536 Type *Ty = ConstInfo.BaseConstant->getType();
538 // Rebase the constants with respect to the base constant.
539 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
540 APInt Diff = ConstCand->ConstInt->getValue() -
541 ConstInfo.BaseConstant->getValue();
542 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
543 ConstInfo.RebasedConstants.push_back(
544 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
546 ConstantVec.push_back(std::move(ConstInfo));
549 /// \brief Finds and combines constant candidates that can be easily
550 /// rematerialized with an add from a common base constant.
551 void ConstantHoistingPass::findBaseConstants() {
552 // Sort the constants by value and type. This invalidates the mapping!
553 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
554 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
555 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
556 return LHS.ConstInt->getType()->getBitWidth() <
557 RHS.ConstInt->getType()->getBitWidth();
558 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
561 // Simple linear scan through the sorted constant candidate vector for viable
563 auto MinValItr = ConstCandVec.begin();
564 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
566 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
567 // Check if the constant is in range of an add with immediate.
568 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
569 if ((Diff.getBitWidth() <= 64) &&
570 TTI->isLegalAddImmediate(Diff.getSExtValue()))
573 // We either have now a different constant type or the constant is not in
574 // range of an add with immediate anymore.
575 findAndMakeBaseConstant(MinValItr, CC);
576 // Start a new base constant search.
579 // Finalize the last base constant search.
580 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
583 /// \brief Updates the operand at Idx in instruction Inst with the result of
584 /// instruction Mat. If the instruction is a PHI node then special
585 /// handling for duplicate values form the same incoming basic block is
587 /// \return The update will always succeed, but the return value indicated if
588 /// Mat was used for the update or not.
589 static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
590 if (auto PHI = dyn_cast<PHINode>(Inst)) {
591 // Check if any previous operand of the PHI node has the same incoming basic
592 // block. This is a very odd case that happens when the incoming basic block
593 // has a switch statement. In this case use the same value as the previous
594 // operand(s), otherwise we will fail verification due to different values.
595 // The values are actually the same, but the variable names are different
596 // and the verifier doesn't like that.
597 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
598 for (unsigned i = 0; i < Idx; ++i) {
599 if (PHI->getIncomingBlock(i) == IncomingBB) {
600 Value *IncomingVal = PHI->getIncomingValue(i);
601 Inst->setOperand(Idx, IncomingVal);
607 Inst->setOperand(Idx, Mat);
611 /// \brief Emit materialization code for all rebased constants and update their
613 void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
615 const ConstantUser &ConstUser) {
616 Instruction *Mat = Base;
618 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
620 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
621 "const_mat", InsertionPt);
623 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
624 << " + " << *Offset << ") in BB "
625 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
626 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
628 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
630 // Visit constant integer.
631 if (isa<ConstantInt>(Opnd)) {
632 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
633 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
634 Mat->eraseFromParent();
635 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
639 // Visit cast instruction.
640 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
641 assert(CastInst->isCast() && "Expected an cast instruction!");
642 // Check if we already have visited this cast instruction before to avoid
643 // unnecessary cloning.
644 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
645 if (!ClonedCastInst) {
646 ClonedCastInst = CastInst->clone();
647 ClonedCastInst->setOperand(0, Mat);
648 ClonedCastInst->insertAfter(CastInst);
649 // Use the same debug location as the original cast instruction.
650 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
651 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
652 << "To : " << *ClonedCastInst << '\n');
655 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
656 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
657 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
661 // Visit constant expression.
662 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
663 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
664 ConstExprInst->setOperand(0, Mat);
665 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
668 // Use the same debug location as the instruction we are about to update.
669 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
671 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
672 << "From : " << *ConstExpr << '\n');
673 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
674 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
675 ConstExprInst->eraseFromParent();
677 Mat->eraseFromParent();
679 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
684 /// \brief Hoist and hide the base constant behind a bitcast and emit
685 /// materialization code for derived constants.
686 bool ConstantHoistingPass::emitBaseConstants() {
687 bool MadeChange = false;
688 for (auto const &ConstInfo : ConstantVec) {
689 // Hoist and hide the base constant behind a bitcast.
690 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
691 assert(!IPSet.empty() && "IPSet is empty");
693 unsigned UsesNum = 0;
694 unsigned ReBasesNum = 0;
695 for (Instruction *IP : IPSet) {
696 IntegerType *Ty = ConstInfo.BaseConstant->getType();
698 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
699 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant
700 << ") to BB " << IP->getParent()->getName() << '\n'
703 // Emit materialization code for all rebased constants.
705 for (auto const &RCI : ConstInfo.RebasedConstants) {
706 for (auto const &U : RCI.Uses) {
708 BasicBlock *OrigMatInsertBB =
709 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
710 // If Base constant is to be inserted in multiple places,
711 // generate rebase for U using the Base dominating U.
712 if (IPSet.size() == 1 ||
713 DT->dominates(Base->getParent(), OrigMatInsertBB)) {
714 emitBaseConstants(Base, RCI.Offset, U);
721 // Use the same debug location as the last user of the constant.
722 assert(!Base->use_empty() && "The use list is empty!?");
723 assert(isa<Instruction>(Base->user_back()) &&
724 "All uses should be instructions.");
725 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
729 // Expect all uses are rebased after rebase is done.
730 assert(UsesNum == ReBasesNum && "Not all uses are rebased");
732 NumConstantsHoisted++;
734 // Base constant is also included in ConstInfo.RebasedConstants, so
735 // deduct 1 from ConstInfo.RebasedConstants.size().
736 NumConstantsRebased = ConstInfo.RebasedConstants.size() - 1;
743 /// \brief Check all cast instructions we made a copy of and remove them if they
744 /// have no more users.
745 void ConstantHoistingPass::deleteDeadCastInst() const {
746 for (auto const &I : ClonedCastMap)
747 if (I.first->use_empty())
748 I.first->eraseFromParent();
751 /// \brief Optimize expensive integer constants in the given function.
752 bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
753 DominatorTree &DT, BlockFrequencyInfo *BFI,
758 this->Entry = &Entry;
759 // Collect all constant candidates.
760 collectConstantCandidates(Fn);
762 // There are no constant candidates to worry about.
763 if (ConstCandVec.empty())
766 // Combine constants that can be easily materialized with an add from a common
770 // There are no constants to emit.
771 if (ConstantVec.empty())
774 // Finally hoist the base constant and emit materialization code for dependent
776 bool MadeChange = emitBaseConstants();
778 // Cleanup dead instructions.
779 deleteDeadCastInst();
784 PreservedAnalyses ConstantHoistingPass::run(Function &F,
785 FunctionAnalysisManager &AM) {
786 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
787 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
788 auto BFI = ConstHoistWithBlockFrequency
789 ? &AM.getResult<BlockFrequencyAnalysis>(F)
791 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
792 return PreservedAnalyses::all();
794 PreservedAnalyses PA;
795 PA.preserveSet<CFGAnalyses>();