1 //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass identifies expensive constants to hoist and coalesces them to
10 // better prepare it for SelectionDAG-based code generation. This works around
11 // the limitations of the basic-block-at-a-time approach.
12 //
13 // First it scans all instructions for integer constants and calculates its
14 // cost. If the constant can be folded into the instruction (the cost is
15 // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
16 // consider it expensive and leave it alone. This is the default behavior and
17 // the default implementation of getIntImmCost will always return TCC_Free.
18 //
19 // If the cost is more than TCC_BASIC, then the integer constant can't be folded
20 // into the instruction and it might be beneficial to hoist the constant.
21 // Similar constants are coalesced to reduce register pressure and
22 // materialization code.
23 //
24 // When a constant is hoisted, it is also hidden behind a bitcast to force it to
25 // be live-out of the basic block. Otherwise the constant would be just
26 // duplicated and each basic block would have its own copy in the SelectionDAG.
27 // The SelectionDAG recognizes such constants as opaque and doesn't perform
28 // certain transformations on them, which would create a new expensive constant.
29 //
30 // This optimization is only applied to integer constants in instructions and
31 // simple (this means not nested) constant cast expressions. For example:
32 // %0 = load i64* inttoptr (i64 big_constant to i64*)
33 //===----------------------------------------------------------------------===//
34 
35 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
36 #include "llvm/ADT/APInt.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/None.h"
39 #include "llvm/ADT/Optional.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/Analysis/BlockFrequencyInfo.h"
44 #include "llvm/Analysis/TargetTransformInfo.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/IR/BasicBlock.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DebugInfoMetadata.h"
49 #include "llvm/IR/Dominators.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/InstrTypes.h"
52 #include "llvm/IR/Instruction.h"
53 #include "llvm/IR/Instructions.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/BlockFrequency.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Transforms/Scalar.h"
63 #include <algorithm>
64 #include <cassert>
65 #include <cstdint>
66 #include <iterator>
67 #include <tuple>
68 #include <utility>
69 
70 using namespace llvm;
71 using namespace consthoist;
72 
73 #define DEBUG_TYPE "consthoist"
74 
75 STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
76 STATISTIC(NumConstantsRebased, "Number of constants rebased");
77 
78 static cl::opt<bool> ConstHoistWithBlockFrequency(
79     "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
80     cl::desc("Enable the use of the block frequency analysis to reduce the "
81              "chance to execute const materialization more frequently than "
82              "without hoisting."));
83 
84 static cl::opt<bool> ConstHoistGEP(
85     "consthoist-gep", cl::init(false), cl::Hidden,
86     cl::desc("Try hoisting constant gep expressions"));
87 
88 static cl::opt<unsigned>
89 MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
90     cl::desc("Do not rebase if number of dependent constants of a Base is less "
91              "than this number."),
92     cl::init(0), cl::Hidden);
93 
94 namespace {
95 
96 /// The constant hoisting pass.
97 class ConstantHoistingLegacyPass : public FunctionPass {
98 public:
99   static char ID; // Pass identification, replacement for typeid
100 
101   ConstantHoistingLegacyPass() : FunctionPass(ID) {
102     initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
103   }
104 
105   bool runOnFunction(Function &Fn) override;
106 
107   StringRef getPassName() const override { return "Constant Hoisting"; }
108 
109   void getAnalysisUsage(AnalysisUsage &AU) const override {
110     AU.setPreservesCFG();
111     if (ConstHoistWithBlockFrequency)
112       AU.addRequired<BlockFrequencyInfoWrapperPass>();
113     AU.addRequired<DominatorTreeWrapperPass>();
114     AU.addRequired<TargetTransformInfoWrapperPass>();
115   }
116 
117   void releaseMemory() override { Impl.releaseMemory(); }
118 
119 private:
120   ConstantHoistingPass Impl;
121 };
122 
123 } // end anonymous namespace
124 
125 char ConstantHoistingLegacyPass::ID = 0;
126 
127 INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
128                       "Constant Hoisting", false, false)
129 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
130 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
131 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
132 INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
133                     "Constant Hoisting", false, false)
134 
135 FunctionPass *llvm::createConstantHoistingPass() {
136   return new ConstantHoistingLegacyPass();
137 }
138 
139 /// Perform the constant hoisting optimization for the given function.
140 bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
141   if (skipFunction(Fn))
142     return false;
143 
144   LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
145   LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
146 
147   bool MadeChange =
148       Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
149                    getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
150                    ConstHoistWithBlockFrequency
151                        ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
152                        : nullptr,
153                    Fn.getEntryBlock());
154 
155   if (MadeChange) {
156     LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
157                       << Fn.getName() << '\n');
158     LLVM_DEBUG(dbgs() << Fn);
159   }
160   LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
161 
162   return MadeChange;
163 }
164 
165 /// Find the constant materialization insertion point.
166 Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
167                                                    unsigned Idx) const {
168   // If the operand is a cast instruction, then we have to materialize the
169   // constant before the cast instruction.
170   if (Idx != ~0U) {
171     Value *Opnd = Inst->getOperand(Idx);
172     if (auto CastInst = dyn_cast<Instruction>(Opnd))
173       if (CastInst->isCast())
174         return CastInst;
175   }
176 
177   // The simple and common case. This also includes constant expressions.
178   if (!isa<PHINode>(Inst) && !Inst->isEHPad())
179     return Inst;
180 
181   // We can't insert directly before a phi node or an eh pad. Insert before
182   // the terminator of the incoming or dominating block.
183   assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
184   if (Idx != ~0U && isa<PHINode>(Inst))
185     return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
186 
187   // This must be an EH pad. Iterate over immediate dominators until we find a
188   // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
189   // and terminators.
190   auto IDom = DT->getNode(Inst->getParent())->getIDom();
191   while (IDom->getBlock()->isEHPad()) {
192     assert(Entry != IDom->getBlock() && "eh pad in entry block");
193     IDom = IDom->getIDom();
194   }
195 
196   return IDom->getBlock()->getTerminator();
197 }
198 
199 /// Given \p BBs as input, find another set of BBs which collectively
200 /// dominates \p BBs and have the minimal sum of frequencies. Return the BB
201 /// set found in \p BBs.
202 static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
203                                  BasicBlock *Entry,
204                                  SmallPtrSet<BasicBlock *, 8> &BBs) {
205   assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
206   // Nodes on the current path to the root.
207   SmallPtrSet<BasicBlock *, 8> Path;
208   // Candidates includes any block 'BB' in set 'BBs' that is not strictly
209   // dominated by any other blocks in set 'BBs', and all nodes in the path
210   // in the dominator tree from Entry to 'BB'.
211   SmallPtrSet<BasicBlock *, 16> Candidates;
212   for (auto BB : BBs) {
213     Path.clear();
214     // Walk up the dominator tree until Entry or another BB in BBs
215     // is reached. Insert the nodes on the way to the Path.
216     BasicBlock *Node = BB;
217     // The "Path" is a candidate path to be added into Candidates set.
218     bool isCandidate = false;
219     do {
220       Path.insert(Node);
221       if (Node == Entry || Candidates.count(Node)) {
222         isCandidate = true;
223         break;
224       }
225       assert(DT.getNode(Node)->getIDom() &&
226              "Entry doens't dominate current Node");
227       Node = DT.getNode(Node)->getIDom()->getBlock();
228     } while (!BBs.count(Node));
229 
230     // If isCandidate is false, Node is another Block in BBs dominating
231     // current 'BB'. Drop the nodes on the Path.
232     if (!isCandidate)
233       continue;
234 
235     // Add nodes on the Path into Candidates.
236     Candidates.insert(Path.begin(), Path.end());
237   }
238 
239   // Sort the nodes in Candidates in top-down order and save the nodes
240   // in Orders.
241   unsigned Idx = 0;
242   SmallVector<BasicBlock *, 16> Orders;
243   Orders.push_back(Entry);
244   while (Idx != Orders.size()) {
245     BasicBlock *Node = Orders[Idx++];
246     for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
247       if (Candidates.count(ChildDomNode->getBlock()))
248         Orders.push_back(ChildDomNode->getBlock());
249     }
250   }
251 
252   // Visit Orders in bottom-up order.
253   using InsertPtsCostPair =
254       std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
255 
256   // InsertPtsMap is a map from a BB to the best insertion points for the
257   // subtree of BB (subtree not including the BB itself).
258   DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
259   InsertPtsMap.reserve(Orders.size() + 1);
260   for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
261     BasicBlock *Node = *RIt;
262     bool NodeInBBs = BBs.count(Node);
263     SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
264     BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
265 
266     // Return the optimal insert points in BBs.
267     if (Node == Entry) {
268       BBs.clear();
269       if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
270           (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
271         BBs.insert(Entry);
272       else
273         BBs.insert(InsertPts.begin(), InsertPts.end());
274       break;
275     }
276 
277     BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
278     // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
279     // will update its parent's ParentInsertPts and ParentPtsFreq.
280     SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
281     BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
282     // Choose to insert in Node or in subtree of Node.
283     // Don't hoist to EHPad because we may not find a proper place to insert
284     // in EHPad.
285     // If the total frequency of InsertPts is the same as the frequency of the
286     // target Node, and InsertPts contains more than one nodes, choose hoisting
287     // to reduce code size.
288     if (NodeInBBs ||
289         (!Node->isEHPad() &&
290          (InsertPtsFreq > BFI.getBlockFreq(Node) ||
291           (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
292       ParentInsertPts.insert(Node);
293       ParentPtsFreq += BFI.getBlockFreq(Node);
294     } else {
295       ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
296       ParentPtsFreq += InsertPtsFreq;
297     }
298   }
299 }
300 
301 /// Find an insertion point that dominates all uses.
302 SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
303     const ConstantInfo &ConstInfo) const {
304   assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
305   // Collect all basic blocks.
306   SmallPtrSet<BasicBlock *, 8> BBs;
307   SmallPtrSet<Instruction *, 8> InsertPts;
308   for (auto const &RCI : ConstInfo.RebasedConstants)
309     for (auto const &U : RCI.Uses)
310       BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
311 
312   if (BBs.count(Entry)) {
313     InsertPts.insert(&Entry->front());
314     return InsertPts;
315   }
316 
317   if (BFI) {
318     findBestInsertionSet(*DT, *BFI, Entry, BBs);
319     for (auto BB : BBs) {
320       BasicBlock::iterator InsertPt = BB->begin();
321       for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
322         ;
323       InsertPts.insert(&*InsertPt);
324     }
325     return InsertPts;
326   }
327 
328   while (BBs.size() >= 2) {
329     BasicBlock *BB, *BB1, *BB2;
330     BB1 = *BBs.begin();
331     BB2 = *std::next(BBs.begin());
332     BB = DT->findNearestCommonDominator(BB1, BB2);
333     if (BB == Entry) {
334       InsertPts.insert(&Entry->front());
335       return InsertPts;
336     }
337     BBs.erase(BB1);
338     BBs.erase(BB2);
339     BBs.insert(BB);
340   }
341   assert((BBs.size() == 1) && "Expected only one element.");
342   Instruction &FirstInst = (*BBs.begin())->front();
343   InsertPts.insert(findMatInsertPt(&FirstInst));
344   return InsertPts;
345 }
346 
347 /// Record constant integer ConstInt for instruction Inst at operand
348 /// index Idx.
349 ///
350 /// The operand at index Idx is not necessarily the constant integer itself. It
351 /// could also be a cast instruction or a constant expression that uses the
352 /// constant integer.
353 void ConstantHoistingPass::collectConstantCandidates(
354     ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
355     ConstantInt *ConstInt) {
356   unsigned Cost;
357   // Ask the target about the cost of materializing the constant for the given
358   // instruction and operand index.
359   if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
360     Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
361                               ConstInt->getValue(), ConstInt->getType());
362   else
363     Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
364                               ConstInt->getType());
365 
366   // Ignore cheap integer constants.
367   if (Cost > TargetTransformInfo::TCC_Basic) {
368     ConstCandMapType::iterator Itr;
369     bool Inserted;
370     ConstPtrUnionType Cand = ConstInt;
371     std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
372     if (Inserted) {
373       ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
374       Itr->second = ConstIntCandVec.size() - 1;
375     }
376     ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost);
377     LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
378                    << "Collect constant " << *ConstInt << " from " << *Inst
379                    << " with cost " << Cost << '\n';
380                else dbgs() << "Collect constant " << *ConstInt
381                            << " indirectly from " << *Inst << " via "
382                            << *Inst->getOperand(Idx) << " with cost " << Cost
383                            << '\n';);
384   }
385 }
386 
387 /// Record constant GEP expression for instruction Inst at operand index Idx.
388 void ConstantHoistingPass::collectConstantCandidates(
389     ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
390     ConstantExpr *ConstExpr) {
391   // TODO: Handle vector GEPs
392   if (ConstExpr->getType()->isVectorTy())
393     return;
394 
395   GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
396   if (!BaseGV)
397     return;
398 
399   // Get offset from the base GV.
400   PointerType *GVPtrTy = dyn_cast<PointerType>(BaseGV->getType());
401   IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
402   APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
403   auto *GEPO = cast<GEPOperator>(ConstExpr);
404   if (!GEPO->accumulateConstantOffset(*DL, Offset))
405     return;
406 
407   if (!Offset.isIntN(32))
408     return;
409 
410   // A constant GEP expression that has a GlobalVariable as base pointer is
411   // usually lowered to a load from constant pool. Such operation is unlikely
412   // to be cheaper than compute it by <Base + Offset>, which can be lowered to
413   // an ADD instruction or folded into Load/Store instruction.
414   int Cost = TTI->getIntImmCost(Instruction::Add, 1, Offset, PtrIntTy);
415   ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
416   ConstCandMapType::iterator Itr;
417   bool Inserted;
418   ConstPtrUnionType Cand = ConstExpr;
419   std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
420   if (Inserted) {
421     ExprCandVec.push_back(ConstantCandidate(
422         ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
423         ConstExpr));
424     Itr->second = ExprCandVec.size() - 1;
425   }
426   ExprCandVec[Itr->second].addUser(Inst, Idx, Cost);
427 }
428 
429 /// Check the operand for instruction Inst at index Idx.
430 void ConstantHoistingPass::collectConstantCandidates(
431     ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
432   Value *Opnd = Inst->getOperand(Idx);
433 
434   // Visit constant integers.
435   if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
436     collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
437     return;
438   }
439 
440   // Visit cast instructions that have constant integers.
441   if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
442     // Only visit cast instructions, which have been skipped. All other
443     // instructions should have already been visited.
444     if (!CastInst->isCast())
445       return;
446 
447     if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
448       // Pretend the constant is directly used by the instruction and ignore
449       // the cast instruction.
450       collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
451       return;
452     }
453   }
454 
455   // Visit constant expressions that have constant integers.
456   if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
457     // Handle constant gep expressions.
458     if (ConstHoistGEP && ConstExpr->isGEPWithNoNotionalOverIndexing())
459       collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
460 
461     // Only visit constant cast expressions.
462     if (!ConstExpr->isCast())
463       return;
464 
465     if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
466       // Pretend the constant is directly used by the instruction and ignore
467       // the constant expression.
468       collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
469       return;
470     }
471   }
472 }
473 
474 /// Scan the instruction for expensive integer constants and record them
475 /// in the constant candidate vector.
476 void ConstantHoistingPass::collectConstantCandidates(
477     ConstCandMapType &ConstCandMap, Instruction *Inst) {
478   // Skip all cast instructions. They are visited indirectly later on.
479   if (Inst->isCast())
480     return;
481 
482   // Scan all operands.
483   for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
484     // The cost of materializing the constants (defined in
485     // `TargetTransformInfo::getIntImmCost`) for instructions which only take
486     // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
487     // it's safe for us to collect constant candidates from all IntrinsicInsts.
488     if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
489       collectConstantCandidates(ConstCandMap, Inst, Idx);
490     }
491   } // end of for all operands
492 }
493 
494 /// Collect all integer constants in the function that cannot be folded
495 /// into an instruction itself.
496 void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
497   ConstCandMapType ConstCandMap;
498   for (BasicBlock &BB : Fn)
499     for (Instruction &Inst : BB)
500       collectConstantCandidates(ConstCandMap, &Inst);
501 }
502 
503 // This helper function is necessary to deal with values that have different
504 // bit widths (APInt Operator- does not like that). If the value cannot be
505 // represented in uint64 we return an "empty" APInt. This is then interpreted
506 // as the value is not in range.
507 static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
508   Optional<APInt> Res = None;
509   unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
510                 V1.getBitWidth() : V2.getBitWidth();
511   uint64_t LimVal1 = V1.getLimitedValue();
512   uint64_t LimVal2 = V2.getLimitedValue();
513 
514   if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
515     return Res;
516 
517   uint64_t Diff = LimVal1 - LimVal2;
518   return APInt(BW, Diff, true);
519 }
520 
521 // From a list of constants, one needs to picked as the base and the other
522 // constants will be transformed into an offset from that base constant. The
523 // question is which we can pick best? For example, consider these constants
524 // and their number of uses:
525 //
526 //  Constants| 2 | 4 | 12 | 42 |
527 //  NumUses  | 3 | 2 |  8 |  7 |
528 //
529 // Selecting constant 12 because it has the most uses will generate negative
530 // offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
531 // offsets lead to less optimal code generation, then there might be better
532 // solutions. Suppose immediates in the range of 0..35 are most optimally
533 // supported by the architecture, then selecting constant 2 is most optimal
534 // because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
535 // range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
536 // have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
537 // selecting the base constant the range of the offsets is a very important
538 // factor too that we take into account here. This algorithm calculates a total
539 // costs for selecting a constant as the base and substract the costs if
540 // immediates are out of range. It has quadratic complexity, so we call this
541 // function only when we're optimising for size and there are less than 100
542 // constants, we fall back to the straightforward algorithm otherwise
543 // which does not do all the offset calculations.
544 unsigned
545 ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
546                                            ConstCandVecType::iterator E,
547                                            ConstCandVecType::iterator &MaxCostItr) {
548   unsigned NumUses = 0;
549 
550   if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
551     for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
552       NumUses += ConstCand->Uses.size();
553       if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
554         MaxCostItr = ConstCand;
555     }
556     return NumUses;
557   }
558 
559   LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
560   int MaxCost = -1;
561   for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
562     auto Value = ConstCand->ConstInt->getValue();
563     Type *Ty = ConstCand->ConstInt->getType();
564     int Cost = 0;
565     NumUses += ConstCand->Uses.size();
566     LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
567                       << "\n");
568 
569     for (auto User : ConstCand->Uses) {
570       unsigned Opcode = User.Inst->getOpcode();
571       unsigned OpndIdx = User.OpndIdx;
572       Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
573       LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
574 
575       for (auto C2 = S; C2 != E; ++C2) {
576         Optional<APInt> Diff = calculateOffsetDiff(
577                                    C2->ConstInt->getValue(),
578                                    ConstCand->ConstInt->getValue());
579         if (Diff) {
580           const int ImmCosts =
581             TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
582           Cost -= ImmCosts;
583           LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
584                             << "has penalty: " << ImmCosts << "\n"
585                             << "Adjusted cost: " << Cost << "\n");
586         }
587       }
588     }
589     LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
590     if (Cost > MaxCost) {
591       MaxCost = Cost;
592       MaxCostItr = ConstCand;
593       LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
594                         << "\n");
595     }
596   }
597   return NumUses;
598 }
599 
600 /// Find the base constant within the given range and rebase all other
601 /// constants with respect to the base constant.
602 void ConstantHoistingPass::findAndMakeBaseConstant(
603     ConstCandVecType::iterator S, ConstCandVecType::iterator E,
604     SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
605   auto MaxCostItr = S;
606   unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
607 
608   // Don't hoist constants that have only one use.
609   if (NumUses <= 1)
610     return;
611 
612   ConstantInt *ConstInt = MaxCostItr->ConstInt;
613   ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
614   ConstantInfo ConstInfo;
615   ConstInfo.BaseInt = ConstInt;
616   ConstInfo.BaseExpr = ConstExpr;
617   Type *Ty = ConstInt->getType();
618 
619   // Rebase the constants with respect to the base constant.
620   for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
621     APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
622     Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
623     Type *ConstTy =
624         ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
625     ConstInfo.RebasedConstants.push_back(
626       RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
627   }
628   ConstInfoVec.push_back(std::move(ConstInfo));
629 }
630 
631 /// Finds and combines constant candidates that can be easily
632 /// rematerialized with an add from a common base constant.
633 void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
634   // If BaseGV is nullptr, find base among candidate constant integers;
635   // Otherwise find base among constant GEPs that share the same BaseGV.
636   ConstCandVecType &ConstCandVec = BaseGV ?
637       ConstGEPCandMap[BaseGV] : ConstIntCandVec;
638   ConstInfoVecType &ConstInfoVec = BaseGV ?
639       ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
640 
641   // Sort the constants by value and type. This invalidates the mapping!
642   std::stable_sort(ConstCandVec.begin(), ConstCandVec.end(),
643              [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
644     if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
645       return LHS.ConstInt->getType()->getBitWidth() <
646              RHS.ConstInt->getType()->getBitWidth();
647     return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
648   });
649 
650   // Simple linear scan through the sorted constant candidate vector for viable
651   // merge candidates.
652   auto MinValItr = ConstCandVec.begin();
653   for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
654        CC != E; ++CC) {
655     if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
656       Type *MemUseValTy = nullptr;
657       for (auto &U : CC->Uses) {
658         auto *UI = U.Inst;
659         if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
660           MemUseValTy = LI->getType();
661           break;
662         } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
663           // Make sure the constant is used as pointer operand of the StoreInst.
664           if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
665             MemUseValTy = SI->getValueOperand()->getType();
666             break;
667           }
668         }
669       }
670 
671       // Check if the constant is in range of an add with immediate.
672       APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
673       if ((Diff.getBitWidth() <= 64) &&
674           TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
675           // Check if Diff can be used as offset in addressing mode of the user
676           // memory instruction.
677           (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
678            /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
679            /*HasBaseReg*/true, /*Scale*/0)))
680         continue;
681     }
682     // We either have now a different constant type or the constant is not in
683     // range of an add with immediate anymore.
684     findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
685     // Start a new base constant search.
686     MinValItr = CC;
687   }
688   // Finalize the last base constant search.
689   findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
690 }
691 
692 /// Updates the operand at Idx in instruction Inst with the result of
693 ///        instruction Mat. If the instruction is a PHI node then special
694 ///        handling for duplicate values form the same incoming basic block is
695 ///        required.
696 /// \return The update will always succeed, but the return value indicated if
697 ///         Mat was used for the update or not.
698 static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
699   if (auto PHI = dyn_cast<PHINode>(Inst)) {
700     // Check if any previous operand of the PHI node has the same incoming basic
701     // block. This is a very odd case that happens when the incoming basic block
702     // has a switch statement. In this case use the same value as the previous
703     // operand(s), otherwise we will fail verification due to different values.
704     // The values are actually the same, but the variable names are different
705     // and the verifier doesn't like that.
706     BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
707     for (unsigned i = 0; i < Idx; ++i) {
708       if (PHI->getIncomingBlock(i) == IncomingBB) {
709         Value *IncomingVal = PHI->getIncomingValue(i);
710         Inst->setOperand(Idx, IncomingVal);
711         return false;
712       }
713     }
714   }
715 
716   Inst->setOperand(Idx, Mat);
717   return true;
718 }
719 
720 /// Emit materialization code for all rebased constants and update their
721 /// users.
722 void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
723                                              Constant *Offset,
724                                              Type *Ty,
725                                              const ConstantUser &ConstUser) {
726   Instruction *Mat = Base;
727 
728   // The same offset can be dereferenced to different types in nested struct.
729   if (!Offset && Ty && Ty != Base->getType())
730     Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
731 
732   if (Offset) {
733     Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
734                                                ConstUser.OpndIdx);
735     if (Ty) {
736       // Constant being rebased is a ConstantExpr.
737       PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
738           cast<PointerType>(Ty)->getAddressSpace());
739       Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
740       Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base,
741           Offset, "mat_gep", InsertionPt);
742       Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
743     } else
744       // Constant being rebased is a ConstantInt.
745       Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
746                                  "const_mat", InsertionPt);
747 
748     LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
749                       << " + " << *Offset << ") in BB "
750                       << Mat->getParent()->getName() << '\n'
751                       << *Mat << '\n');
752     Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
753   }
754   Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
755 
756   // Visit constant integer.
757   if (isa<ConstantInt>(Opnd)) {
758     LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
759     if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
760       Mat->eraseFromParent();
761     LLVM_DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
762     return;
763   }
764 
765   // Visit cast instruction.
766   if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
767     assert(CastInst->isCast() && "Expected an cast instruction!");
768     // Check if we already have visited this cast instruction before to avoid
769     // unnecessary cloning.
770     Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
771     if (!ClonedCastInst) {
772       ClonedCastInst = CastInst->clone();
773       ClonedCastInst->setOperand(0, Mat);
774       ClonedCastInst->insertAfter(CastInst);
775       // Use the same debug location as the original cast instruction.
776       ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
777       LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
778                         << "To               : " << *ClonedCastInst << '\n');
779     }
780 
781     LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
782     updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
783     LLVM_DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
784     return;
785   }
786 
787   // Visit constant expression.
788   if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
789     if (ConstExpr->isGEPWithNoNotionalOverIndexing()) {
790       // Operand is a ConstantGEP, replace it.
791       updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
792       return;
793     }
794 
795     // Aside from constant GEPs, only constant cast expressions are collected.
796     assert(ConstExpr->isCast() && "ConstExpr should be a cast");
797     Instruction *ConstExprInst = ConstExpr->getAsInstruction();
798     ConstExprInst->setOperand(0, Mat);
799     ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
800                                                 ConstUser.OpndIdx));
801 
802     // Use the same debug location as the instruction we are about to update.
803     ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
804 
805     LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
806                       << "From              : " << *ConstExpr << '\n');
807     LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
808     if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
809       ConstExprInst->eraseFromParent();
810       if (Offset)
811         Mat->eraseFromParent();
812     }
813     LLVM_DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
814     return;
815   }
816 }
817 
818 /// Hoist and hide the base constant behind a bitcast and emit
819 /// materialization code for derived constants.
820 bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
821   bool MadeChange = false;
822   SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
823       BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
824   for (auto const &ConstInfo : ConstInfoVec) {
825     SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
826     assert(!IPSet.empty() && "IPSet is empty");
827 
828     unsigned UsesNum = 0;
829     unsigned ReBasesNum = 0;
830     unsigned NotRebasedNum = 0;
831     for (Instruction *IP : IPSet) {
832       // First, collect constants depending on this IP of the base.
833       unsigned Uses = 0;
834       using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
835       SmallVector<RebasedUse, 4> ToBeRebased;
836       for (auto const &RCI : ConstInfo.RebasedConstants) {
837         for (auto const &U : RCI.Uses) {
838           Uses++;
839           BasicBlock *OrigMatInsertBB =
840               findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
841           // If Base constant is to be inserted in multiple places,
842           // generate rebase for U using the Base dominating U.
843           if (IPSet.size() == 1 ||
844               DT->dominates(IP->getParent(), OrigMatInsertBB))
845             ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
846         }
847       }
848       UsesNum = Uses;
849 
850       // If only few constants depend on this IP of base, skip rebasing,
851       // assuming the base and the rebased have the same materialization cost.
852       if (ToBeRebased.size() < MinNumOfDependentToRebase) {
853         NotRebasedNum += ToBeRebased.size();
854         continue;
855       }
856 
857       // Emit an instance of the base at this IP.
858       Instruction *Base = nullptr;
859       // Hoist and hide the base constant behind a bitcast.
860       if (ConstInfo.BaseExpr) {
861         assert(BaseGV && "A base constant expression must have an base GV");
862         Type *Ty = ConstInfo.BaseExpr->getType();
863         Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
864       } else {
865         IntegerType *Ty = ConstInfo.BaseInt->getType();
866         Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
867       }
868 
869       Base->setDebugLoc(IP->getDebugLoc());
870 
871       LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
872                         << ") to BB " << IP->getParent()->getName() << '\n'
873                         << *Base << '\n');
874 
875       // Emit materialization code for rebased constants depending on this IP.
876       for (auto const &R : ToBeRebased) {
877         Constant *Off = std::get<0>(R);
878         Type *Ty = std::get<1>(R);
879         ConstantUser U = std::get<2>(R);
880         emitBaseConstants(Base, Off, Ty, U);
881         ReBasesNum++;
882         // Use the same debug location as the last user of the constant.
883         Base->setDebugLoc(DILocation::getMergedLocation(
884             Base->getDebugLoc(), U.Inst->getDebugLoc()));
885       }
886       assert(!Base->use_empty() && "The use list is empty!?");
887       assert(isa<Instruction>(Base->user_back()) &&
888              "All uses should be instructions.");
889     }
890     (void)UsesNum;
891     (void)ReBasesNum;
892     (void)NotRebasedNum;
893     // Expect all uses are rebased after rebase is done.
894     assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
895            "Not all uses are rebased");
896 
897     NumConstantsHoisted++;
898 
899     // Base constant is also included in ConstInfo.RebasedConstants, so
900     // deduct 1 from ConstInfo.RebasedConstants.size().
901     NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
902 
903     MadeChange = true;
904   }
905   return MadeChange;
906 }
907 
908 /// Check all cast instructions we made a copy of and remove them if they
909 /// have no more users.
910 void ConstantHoistingPass::deleteDeadCastInst() const {
911   for (auto const &I : ClonedCastMap)
912     if (I.first->use_empty())
913       I.first->eraseFromParent();
914 }
915 
916 /// Optimize expensive integer constants in the given function.
917 bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
918                                    DominatorTree &DT, BlockFrequencyInfo *BFI,
919                                    BasicBlock &Entry) {
920   this->TTI = &TTI;
921   this->DT = &DT;
922   this->BFI = BFI;
923   this->DL = &Fn.getParent()->getDataLayout();
924   this->Ctx = &Fn.getContext();
925   this->Entry = &Entry;
926   // Collect all constant candidates.
927   collectConstantCandidates(Fn);
928 
929   // Combine constants that can be easily materialized with an add from a common
930   // base constant.
931   if (!ConstIntCandVec.empty())
932     findBaseConstants(nullptr);
933   for (auto &MapEntry : ConstGEPCandMap)
934     if (!MapEntry.second.empty())
935       findBaseConstants(MapEntry.first);
936 
937   // Finally hoist the base constant and emit materialization code for dependent
938   // constants.
939   bool MadeChange = false;
940   if (!ConstIntInfoVec.empty())
941     MadeChange = emitBaseConstants(nullptr);
942   for (auto MapEntry : ConstGEPInfoMap)
943     if (!MapEntry.second.empty())
944       MadeChange |= emitBaseConstants(MapEntry.first);
945 
946 
947   // Cleanup dead instructions.
948   deleteDeadCastInst();
949 
950   return MadeChange;
951 }
952 
953 PreservedAnalyses ConstantHoistingPass::run(Function &F,
954                                             FunctionAnalysisManager &AM) {
955   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
956   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
957   auto BFI = ConstHoistWithBlockFrequency
958                  ? &AM.getResult<BlockFrequencyAnalysis>(F)
959                  : nullptr;
960   if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
961     return PreservedAnalyses::all();
962 
963   PreservedAnalyses PA;
964   PA.preserveSet<CFGAnalyses>();
965   return PA;
966 }
967