Revert "[Constant Hoisting] Lazily compute the idom and cache the result."
[oota-llvm.git] / lib / Transforms / Scalar / ConstantHoisting.cpp
1 //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass identifies expensive constants to hoist and coalesces them to
11 // better prepare it for SelectionDAG-based code generation. This works around
12 // the limitations of the basic-block-at-a-time approach.
13 //
14 // First it scans all instructions for integer constants and calculates its
15 // cost. If the constant can be folded into the instruction (the cost is
16 // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
17 // consider it expensive and leave it alone. This is the default behavior and
18 // the default implementation of getIntImmCost will always return TCC_Free.
19 //
20 // If the cost is more than TCC_BASIC, then the integer constant can't be folded
21 // into the instruction and it might be beneficial to hoist the constant.
22 // Similar constants are coalesced to reduce register pressure and
23 // materialization code.
24 //
25 // When a constant is hoisted, it is also hidden behind a bitcast to force it to
26 // be live-out of the basic block. Otherwise the constant would be just
27 // duplicated and each basic block would have its own copy in the SelectionDAG.
28 // The SelectionDAG recognizes such constants as opaque and doesn't perform
29 // certain transformations on them, which would create a new expensive constant.
30 //
31 // This optimization is only applied to integer constants in instructions and
32 // simple (this means not nested) constant cast expressions. For example:
33 // %0 = load i64* inttoptr (i64 big_constant to i64*)
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "consthoist"
37 #include "llvm/Transforms/Scalar.h"
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"
47
48 using namespace llvm;
49
50 STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
51 STATISTIC(NumConstantsRebased, "Number of constants rebased");
52
53 namespace {
54 struct ConstantUser;
55 struct RebasedConstantInfo;
56
57 typedef SmallVector<ConstantUser, 8> ConstantUseListType;
58 typedef 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.
62 struct ConstantUser {
63   Instruction *Inst;
64   unsigned OpndIdx;
65
66   ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
67 };
68
69 /// \brief Keeps track of a constant candidate and its uses.
70 struct ConstantCandidate {
71   ConstantUseListType Uses;
72   ConstantInt *ConstInt;
73   unsigned CumulativeCost;
74
75   ConstantCandidate(ConstantInt *ConstInt)
76     : ConstInt(ConstInt), CumulativeCost(0) { }
77
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   }
83 };
84
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;
89   Constant *Offset;
90
91   RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
92     : Uses(Uses), Offset(Offset) { }
93 };
94
95 /// \brief A base constant and all its rebased constants.
96 struct ConstantInfo {
97   ConstantInt *BaseConstant;
98   RebasedConstantListType RebasedConstants;
99 };
100
101 /// \brief The constant hoisting pass.
102 class ConstantHoisting : public FunctionPass {
103   typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
104   typedef std::vector<ConstantCandidate> ConstCandVecType;
105
106   const TargetTransformInfo *TTI;
107   DominatorTree *DT;
108   BasicBlock *Entry;
109
110   /// Keeps track of constant candidates found in the function.
111   ConstCandVecType ConstCandVec;
112
113   /// Keep track of cast instructions we already cloned.
114   SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
115
116   /// These are the final constants we decided to hoist.
117   SmallVector<ConstantInfo, 8> ConstantVec;
118 public:
119   static char ID; // Pass identification, replacement for typeid
120   ConstantHoisting() : FunctionPass(ID), TTI(0), DT(0), Entry(0) {
121     initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
122   }
123
124   bool runOnFunction(Function &Fn) override;
125
126   const char *getPassName() const override { return "Constant Hoisting"; }
127
128   void getAnalysisUsage(AnalysisUsage &AU) const override {
129     AU.setPreservesCFG();
130     AU.addRequired<DominatorTreeWrapperPass>();
131     AU.addRequired<TargetTransformInfo>();
132   }
133
134 private:
135   /// \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();
147
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;
155   void collectConstantCandidates(ConstCandMapType &ConstCandMap,
156                                  Instruction *Inst, unsigned Idx,
157                                  ConstantInt *ConstInt);
158   void collectConstantCandidates(ConstCandMapType &ConstCandMap,
159                                  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);
169 };
170 }
171
172 char ConstantHoisting::ID = 0;
173 INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
174                       false, false)
175 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
176 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
177 INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
178                     false, false)
179
180 FunctionPass *llvm::createConstantHoistingPass() {
181   return new ConstantHoisting();
182 }
183
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');
188
189   setup(Fn);
190
191   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;
203 }
204
205
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))
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.
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());
232
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 ///
256 /// The operand at index Idx is not necessarily the constant integer itself. It
257 /// could also be a cast instruction or a constant expression that uses the
258 // constant integer.
259 void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
260                                                  Instruction *Inst,
261                                                  unsigned Idx,
262                                                  ConstantInt *ConstInt) {
263   unsigned Cost;
264   // Ask the target about the cost of materializing the constant for the given
265   // instruction and operand index.
266   if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
267     Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
268                               ConstInt->getValue(), ConstInt->getType());
269   else
270     Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
271                               ConstInt->getType());
272
273   // Ignore cheap integer constants.
274   if (Cost > TargetTransformInfo::TCC_Basic) {
275     ConstCandMapType::iterator Itr;
276     bool Inserted;
277     std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
278     if (Inserted) {
279       ConstCandVec.push_back(ConstantCandidate(ConstInt));
280       Itr->second = ConstCandVec.size() - 1;
281     }
282     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     );
291   }
292 }
293
294 /// \brief Scan the instruction for expensive integer constants and record them
295 /// in the constant candidate vector.
296 void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
297                                                  Instruction *Inst) {
298   // 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;
306
307   // Scan all operands.
308   for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
309     Value *Opnd = Inst->getOperand(Idx);
310
311     // Visit constant integers.
312     if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
313       collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
314       continue;
315     }
316
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())
322         continue;
323
324       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.
327         collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
328         continue;
329       }
330     }
331
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.
341         collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
342         continue;
343       }
344     }
345   } // end of for all operands
346 }
347
348 /// \brief Collect all integer constants in the function that cannot be folded
349 /// into an instruction itself.
350 void ConstantHoisting::collectConstantCandidates(Function &Fn) {
351   ConstCandMapType ConstCandMap;
352   for (Function::iterator BB : Fn)
353     for (BasicBlock::iterator Inst : *BB)
354       collectConstantCandidates(ConstCandMap, Inst);
355 }
356
357 /// \brief Find the base constant within the given range and rebase all other
358 /// constants with respect to the base constant.
359 void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
360                                                ConstCandVecType::iterator E) {
361   auto MaxCostItr = S;
362   unsigned NumUses = 0;
363   // Use the constant that has the maximum cost as base constant.
364   for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
365     NumUses += ConstCand->Uses.size();
366     if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
367       MaxCostItr = ConstCand;
368   }
369
370   // Don't hoist constants that have only one use.
371   if (NumUses <= 1)
372     return;
373
374   ConstantInfo ConstInfo;
375   ConstInfo.BaseConstant = MaxCostItr->ConstInt;
376   Type *Ty = ConstInfo.BaseConstant->getType();
377
378   // Rebase the constants with respect to the base constant.
379   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));
385   }
386   ConstantVec.push_back(ConstInfo);
387 }
388
389 /// \brief Finds and combines constant candidates that can be easily
390 /// rematerialized with an add from a common base constant.
391 void ConstantHoisting::findBaseConstants() {
392   // Sort the constants by value and type. This invalidates the mapping!
393   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());
399   });
400
401   // 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()) {
407       // Check if the constant is in range of an add with immediate.
408       APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
409       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.
415     findAndMakeBaseConstant(MinValItr, CC);
416     // Start a new base constant search.
417     MinValItr = CC;
418   }
419   // Finalize the last base constant search.
420   findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
421 }
422
423 /// \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.
429 static 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
451 /// \brief Emit materialization code for all rebased constants and update their
452 /// users.
453 void 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);
461
462     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);
468
469   // Visit constant integer.
470   if (isa<ConstantInt>(Opnd)) {
471     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
472     if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
473       Mat->eraseFromParent();
474     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
475     return;
476   }
477
478   // 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');
492     }
493
494     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
495     updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
496     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
497     return;
498   }
499
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');
513     if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
514       ConstExprInst->eraseFromParent();
515       if (Offset)
516         Mat->eraseFromParent();
517     }
518     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
519     return;
520   }
521 }
522
523 /// \brief Hoist and hide the base constant behind a bitcast and emit
524 /// materialization code for derived constants.
525 bool ConstantHoisting::emitBaseConstants() {
526   bool MadeChange = false;
527   for (auto const &ConstInfo : ConstantVec) {
528     // Hoist and hide the base constant behind a bitcast.
529     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');
535     NumConstantsHoisted++;
536
537     // Emit materialization code for all rebased constants.
538     for (auto const &RCI : ConstInfo.RebasedConstants) {
539       NumConstantsRebased++;
540       for (auto const &U : RCI.Uses)
541         emitBaseConstants(Base, RCI.Offset, U);
542     }
543
544     // Use the same debug location as the last user of the constant.
545     assert(!Base->use_empty() && "The use list is empty!?");
546     assert(isa<Instruction>(Base->user_back()) &&
547            "All uses should be instructions.");
548     Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
549
550     // Correct for base constant, which we counted above too.
551     NumConstantsRebased--;
552     MadeChange = true;
553   }
554   return MadeChange;
555 }
556
557 /// \brief Check all cast instructions we made a copy of and remove them if they
558 /// have no more users.
559 void ConstantHoisting::deleteDeadCastInst() const {
560   for (auto const &I : ClonedCastMap)
561     if (I.first->use_empty())
562       I.first->eraseFromParent();
563 }
564
565 /// \brief Optimize expensive integer constants in the given function.
566 bool ConstantHoisting::optimizeConstants(Function &Fn) {
567   // Collect all constant candidates.
568   collectConstantCandidates(Fn);
569
570   // There are no constant candidates to worry about.
571   if (ConstCandVec.empty())
572     return false;
573
574   // Combine constants that can be easily materialized with an add from a common
575   // base constant.
576   findBaseConstants();
577
578   // There are no constants to emit.
579   if (ConstantVec.empty())
580     return false;
581
582   // Finally hoist the base constant and emit materialization code for dependent
583   // constants.
584   bool MadeChange = emitBaseConstants();
585
586   // Cleanup dead instructions.
587   deleteDeadCastInst();
588
589   return MadeChange;
590 }