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