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