xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass identifies expensive constants to hoist and coalesces them to
11*9880d681SAndroid Build Coastguard Worker // better prepare it for SelectionDAG-based code generation. This works around
12*9880d681SAndroid Build Coastguard Worker // the limitations of the basic-block-at-a-time approach.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker // First it scans all instructions for integer constants and calculates its
15*9880d681SAndroid Build Coastguard Worker // cost. If the constant can be folded into the instruction (the cost is
16*9880d681SAndroid Build Coastguard Worker // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
17*9880d681SAndroid Build Coastguard Worker // consider it expensive and leave it alone. This is the default behavior and
18*9880d681SAndroid Build Coastguard Worker // the default implementation of getIntImmCost will always return TCC_Free.
19*9880d681SAndroid Build Coastguard Worker //
20*9880d681SAndroid Build Coastguard Worker // If the cost is more than TCC_BASIC, then the integer constant can't be folded
21*9880d681SAndroid Build Coastguard Worker // into the instruction and it might be beneficial to hoist the constant.
22*9880d681SAndroid Build Coastguard Worker // Similar constants are coalesced to reduce register pressure and
23*9880d681SAndroid Build Coastguard Worker // materialization code.
24*9880d681SAndroid Build Coastguard Worker //
25*9880d681SAndroid Build Coastguard Worker // When a constant is hoisted, it is also hidden behind a bitcast to force it to
26*9880d681SAndroid Build Coastguard Worker // be live-out of the basic block. Otherwise the constant would be just
27*9880d681SAndroid Build Coastguard Worker // duplicated and each basic block would have its own copy in the SelectionDAG.
28*9880d681SAndroid Build Coastguard Worker // The SelectionDAG recognizes such constants as opaque and doesn't perform
29*9880d681SAndroid Build Coastguard Worker // certain transformations on them, which would create a new expensive constant.
30*9880d681SAndroid Build Coastguard Worker //
31*9880d681SAndroid Build Coastguard Worker // This optimization is only applied to integer constants in instructions and
32*9880d681SAndroid Build Coastguard Worker // simple (this means not nested) constant cast expressions. For example:
33*9880d681SAndroid Build Coastguard Worker // %0 = load i64* inttoptr (i64 big_constant to i64*)
34*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
35*9880d681SAndroid Build Coastguard Worker 
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/ConstantHoisting.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallSet.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallVector.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
46*9880d681SAndroid Build Coastguard Worker #include <tuple>
47*9880d681SAndroid Build Coastguard Worker 
48*9880d681SAndroid Build Coastguard Worker using namespace llvm;
49*9880d681SAndroid Build Coastguard Worker using namespace consthoist;
50*9880d681SAndroid Build Coastguard Worker 
51*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "consthoist"
52*9880d681SAndroid Build Coastguard Worker 
53*9880d681SAndroid Build Coastguard Worker STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
54*9880d681SAndroid Build Coastguard Worker STATISTIC(NumConstantsRebased, "Number of constants rebased");
55*9880d681SAndroid Build Coastguard Worker 
56*9880d681SAndroid Build Coastguard Worker namespace {
57*9880d681SAndroid Build Coastguard Worker /// \brief The constant hoisting pass.
58*9880d681SAndroid Build Coastguard Worker class ConstantHoistingLegacyPass : public FunctionPass {
59*9880d681SAndroid Build Coastguard Worker public:
60*9880d681SAndroid Build Coastguard Worker   static char ID; // Pass identification, replacement for typeid
ConstantHoistingLegacyPass()61*9880d681SAndroid Build Coastguard Worker   ConstantHoistingLegacyPass() : FunctionPass(ID) {
62*9880d681SAndroid Build Coastguard Worker     initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
63*9880d681SAndroid Build Coastguard Worker   }
64*9880d681SAndroid Build Coastguard Worker 
65*9880d681SAndroid Build Coastguard Worker   bool runOnFunction(Function &Fn) override;
66*9880d681SAndroid Build Coastguard Worker 
getPassName() const67*9880d681SAndroid Build Coastguard Worker   const char *getPassName() const override { return "Constant Hoisting"; }
68*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const69*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
70*9880d681SAndroid Build Coastguard Worker     AU.setPreservesCFG();
71*9880d681SAndroid Build Coastguard Worker     AU.addRequired<DominatorTreeWrapperPass>();
72*9880d681SAndroid Build Coastguard Worker     AU.addRequired<TargetTransformInfoWrapperPass>();
73*9880d681SAndroid Build Coastguard Worker   }
74*9880d681SAndroid Build Coastguard Worker 
releaseMemory()75*9880d681SAndroid Build Coastguard Worker   void releaseMemory() override { Impl.releaseMemory(); }
76*9880d681SAndroid Build Coastguard Worker 
77*9880d681SAndroid Build Coastguard Worker private:
78*9880d681SAndroid Build Coastguard Worker   ConstantHoistingPass Impl;
79*9880d681SAndroid Build Coastguard Worker };
80*9880d681SAndroid Build Coastguard Worker }
81*9880d681SAndroid Build Coastguard Worker 
82*9880d681SAndroid Build Coastguard Worker char ConstantHoistingLegacyPass::ID = 0;
83*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
84*9880d681SAndroid Build Coastguard Worker                       "Constant Hoisting", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)85*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
86*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
87*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
88*9880d681SAndroid Build Coastguard Worker                     "Constant Hoisting", false, false)
89*9880d681SAndroid Build Coastguard Worker 
90*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createConstantHoistingPass() {
91*9880d681SAndroid Build Coastguard Worker   return new ConstantHoistingLegacyPass();
92*9880d681SAndroid Build Coastguard Worker }
93*9880d681SAndroid Build Coastguard Worker 
94*9880d681SAndroid Build Coastguard Worker /// \brief Perform the constant hoisting optimization for the given function.
runOnFunction(Function & Fn)95*9880d681SAndroid Build Coastguard Worker bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
96*9880d681SAndroid Build Coastguard Worker   if (skipFunction(Fn))
97*9880d681SAndroid Build Coastguard Worker     return false;
98*9880d681SAndroid Build Coastguard Worker 
99*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
100*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
101*9880d681SAndroid Build Coastguard Worker 
102*9880d681SAndroid Build Coastguard Worker   bool MadeChange = Impl.runImpl(
103*9880d681SAndroid Build Coastguard Worker       Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
104*9880d681SAndroid Build Coastguard Worker       getAnalysis<DominatorTreeWrapperPass>().getDomTree(), Fn.getEntryBlock());
105*9880d681SAndroid Build Coastguard Worker 
106*9880d681SAndroid Build Coastguard Worker   if (MadeChange) {
107*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "********** Function after Constant Hoisting: "
108*9880d681SAndroid Build Coastguard Worker                  << Fn.getName() << '\n');
109*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << Fn);
110*9880d681SAndroid Build Coastguard Worker   }
111*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
112*9880d681SAndroid Build Coastguard Worker 
113*9880d681SAndroid Build Coastguard Worker   return MadeChange;
114*9880d681SAndroid Build Coastguard Worker }
115*9880d681SAndroid Build Coastguard Worker 
116*9880d681SAndroid Build Coastguard Worker 
117*9880d681SAndroid Build Coastguard Worker /// \brief Find the constant materialization insertion point.
findMatInsertPt(Instruction * Inst,unsigned Idx) const118*9880d681SAndroid Build Coastguard Worker Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
119*9880d681SAndroid Build Coastguard Worker                                                    unsigned Idx) const {
120*9880d681SAndroid Build Coastguard Worker   // If the operand is a cast instruction, then we have to materialize the
121*9880d681SAndroid Build Coastguard Worker   // constant before the cast instruction.
122*9880d681SAndroid Build Coastguard Worker   if (Idx != ~0U) {
123*9880d681SAndroid Build Coastguard Worker     Value *Opnd = Inst->getOperand(Idx);
124*9880d681SAndroid Build Coastguard Worker     if (auto CastInst = dyn_cast<Instruction>(Opnd))
125*9880d681SAndroid Build Coastguard Worker       if (CastInst->isCast())
126*9880d681SAndroid Build Coastguard Worker         return CastInst;
127*9880d681SAndroid Build Coastguard Worker   }
128*9880d681SAndroid Build Coastguard Worker 
129*9880d681SAndroid Build Coastguard Worker   // The simple and common case. This also includes constant expressions.
130*9880d681SAndroid Build Coastguard Worker   if (!isa<PHINode>(Inst) && !Inst->isEHPad())
131*9880d681SAndroid Build Coastguard Worker     return Inst;
132*9880d681SAndroid Build Coastguard Worker 
133*9880d681SAndroid Build Coastguard Worker   // We can't insert directly before a phi node or an eh pad. Insert before
134*9880d681SAndroid Build Coastguard Worker   // the terminator of the incoming or dominating block.
135*9880d681SAndroid Build Coastguard Worker   assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
136*9880d681SAndroid Build Coastguard Worker   if (Idx != ~0U && isa<PHINode>(Inst))
137*9880d681SAndroid Build Coastguard Worker     return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
138*9880d681SAndroid Build Coastguard Worker 
139*9880d681SAndroid Build Coastguard Worker   BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
140*9880d681SAndroid Build Coastguard Worker   return IDom->getTerminator();
141*9880d681SAndroid Build Coastguard Worker }
142*9880d681SAndroid Build Coastguard Worker 
143*9880d681SAndroid Build Coastguard Worker /// \brief Find an insertion point that dominates all uses.
findConstantInsertionPoint(const ConstantInfo & ConstInfo) const144*9880d681SAndroid Build Coastguard Worker Instruction *ConstantHoistingPass::findConstantInsertionPoint(
145*9880d681SAndroid Build Coastguard Worker     const ConstantInfo &ConstInfo) const {
146*9880d681SAndroid Build Coastguard Worker   assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
147*9880d681SAndroid Build Coastguard Worker   // Collect all basic blocks.
148*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<BasicBlock *, 8> BBs;
149*9880d681SAndroid Build Coastguard Worker   for (auto const &RCI : ConstInfo.RebasedConstants)
150*9880d681SAndroid Build Coastguard Worker     for (auto const &U : RCI.Uses)
151*9880d681SAndroid Build Coastguard Worker       BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
152*9880d681SAndroid Build Coastguard Worker 
153*9880d681SAndroid Build Coastguard Worker   if (BBs.count(Entry))
154*9880d681SAndroid Build Coastguard Worker     return &Entry->front();
155*9880d681SAndroid Build Coastguard Worker 
156*9880d681SAndroid Build Coastguard Worker   while (BBs.size() >= 2) {
157*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB, *BB1, *BB2;
158*9880d681SAndroid Build Coastguard Worker     BB1 = *BBs.begin();
159*9880d681SAndroid Build Coastguard Worker     BB2 = *std::next(BBs.begin());
160*9880d681SAndroid Build Coastguard Worker     BB = DT->findNearestCommonDominator(BB1, BB2);
161*9880d681SAndroid Build Coastguard Worker     if (BB == Entry)
162*9880d681SAndroid Build Coastguard Worker       return &Entry->front();
163*9880d681SAndroid Build Coastguard Worker     BBs.erase(BB1);
164*9880d681SAndroid Build Coastguard Worker     BBs.erase(BB2);
165*9880d681SAndroid Build Coastguard Worker     BBs.insert(BB);
166*9880d681SAndroid Build Coastguard Worker   }
167*9880d681SAndroid Build Coastguard Worker   assert((BBs.size() == 1) && "Expected only one element.");
168*9880d681SAndroid Build Coastguard Worker   Instruction &FirstInst = (*BBs.begin())->front();
169*9880d681SAndroid Build Coastguard Worker   return findMatInsertPt(&FirstInst);
170*9880d681SAndroid Build Coastguard Worker }
171*9880d681SAndroid Build Coastguard Worker 
172*9880d681SAndroid Build Coastguard Worker 
173*9880d681SAndroid Build Coastguard Worker /// \brief Record constant integer ConstInt for instruction Inst at operand
174*9880d681SAndroid Build Coastguard Worker /// index Idx.
175*9880d681SAndroid Build Coastguard Worker ///
176*9880d681SAndroid Build Coastguard Worker /// The operand at index Idx is not necessarily the constant integer itself. It
177*9880d681SAndroid Build Coastguard Worker /// could also be a cast instruction or a constant expression that uses the
178*9880d681SAndroid Build Coastguard Worker // constant integer.
collectConstantCandidates(ConstCandMapType & ConstCandMap,Instruction * Inst,unsigned Idx,ConstantInt * ConstInt)179*9880d681SAndroid Build Coastguard Worker void ConstantHoistingPass::collectConstantCandidates(
180*9880d681SAndroid Build Coastguard Worker     ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
181*9880d681SAndroid Build Coastguard Worker     ConstantInt *ConstInt) {
182*9880d681SAndroid Build Coastguard Worker   unsigned Cost;
183*9880d681SAndroid Build Coastguard Worker   // Ask the target about the cost of materializing the constant for the given
184*9880d681SAndroid Build Coastguard Worker   // instruction and operand index.
185*9880d681SAndroid Build Coastguard Worker   if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
186*9880d681SAndroid Build Coastguard Worker     Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
187*9880d681SAndroid Build Coastguard Worker                               ConstInt->getValue(), ConstInt->getType());
188*9880d681SAndroid Build Coastguard Worker   else
189*9880d681SAndroid Build Coastguard Worker     Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
190*9880d681SAndroid Build Coastguard Worker                               ConstInt->getType());
191*9880d681SAndroid Build Coastguard Worker 
192*9880d681SAndroid Build Coastguard Worker   // Ignore cheap integer constants.
193*9880d681SAndroid Build Coastguard Worker   if (Cost > TargetTransformInfo::TCC_Basic) {
194*9880d681SAndroid Build Coastguard Worker     ConstCandMapType::iterator Itr;
195*9880d681SAndroid Build Coastguard Worker     bool Inserted;
196*9880d681SAndroid Build Coastguard Worker     std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
197*9880d681SAndroid Build Coastguard Worker     if (Inserted) {
198*9880d681SAndroid Build Coastguard Worker       ConstCandVec.push_back(ConstantCandidate(ConstInt));
199*9880d681SAndroid Build Coastguard Worker       Itr->second = ConstCandVec.size() - 1;
200*9880d681SAndroid Build Coastguard Worker     }
201*9880d681SAndroid Build Coastguard Worker     ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
202*9880d681SAndroid Build Coastguard Worker     DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
203*9880d681SAndroid Build Coastguard Worker             dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
204*9880d681SAndroid Build Coastguard Worker                    << " with cost " << Cost << '\n';
205*9880d681SAndroid Build Coastguard Worker           else
206*9880d681SAndroid Build Coastguard Worker           dbgs() << "Collect constant " << *ConstInt << " indirectly from "
207*9880d681SAndroid Build Coastguard Worker                  << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
208*9880d681SAndroid Build Coastguard Worker                  << Cost << '\n';
209*9880d681SAndroid Build Coastguard Worker     );
210*9880d681SAndroid Build Coastguard Worker   }
211*9880d681SAndroid Build Coastguard Worker }
212*9880d681SAndroid Build Coastguard Worker 
213*9880d681SAndroid Build Coastguard Worker /// \brief Scan the instruction for expensive integer constants and record them
214*9880d681SAndroid Build Coastguard Worker /// in the constant candidate vector.
collectConstantCandidates(ConstCandMapType & ConstCandMap,Instruction * Inst)215*9880d681SAndroid Build Coastguard Worker void ConstantHoistingPass::collectConstantCandidates(
216*9880d681SAndroid Build Coastguard Worker     ConstCandMapType &ConstCandMap, Instruction *Inst) {
217*9880d681SAndroid Build Coastguard Worker   // Skip all cast instructions. They are visited indirectly later on.
218*9880d681SAndroid Build Coastguard Worker   if (Inst->isCast())
219*9880d681SAndroid Build Coastguard Worker     return;
220*9880d681SAndroid Build Coastguard Worker 
221*9880d681SAndroid Build Coastguard Worker   // Can't handle inline asm. Skip it.
222*9880d681SAndroid Build Coastguard Worker   if (auto Call = dyn_cast<CallInst>(Inst))
223*9880d681SAndroid Build Coastguard Worker     if (isa<InlineAsm>(Call->getCalledValue()))
224*9880d681SAndroid Build Coastguard Worker       return;
225*9880d681SAndroid Build Coastguard Worker 
226*9880d681SAndroid Build Coastguard Worker   // Switch cases must remain constant, and if the value being tested is
227*9880d681SAndroid Build Coastguard Worker   // constant the entire thing should disappear.
228*9880d681SAndroid Build Coastguard Worker   if (isa<SwitchInst>(Inst))
229*9880d681SAndroid Build Coastguard Worker     return;
230*9880d681SAndroid Build Coastguard Worker 
231*9880d681SAndroid Build Coastguard Worker   // Static allocas (constant size in the entry block) are handled by
232*9880d681SAndroid Build Coastguard Worker   // prologue/epilogue insertion so they're free anyway. We definitely don't
233*9880d681SAndroid Build Coastguard Worker   // want to make them non-constant.
234*9880d681SAndroid Build Coastguard Worker   auto AI = dyn_cast<AllocaInst>(Inst);
235*9880d681SAndroid Build Coastguard Worker   if (AI && AI->isStaticAlloca())
236*9880d681SAndroid Build Coastguard Worker     return;
237*9880d681SAndroid Build Coastguard Worker 
238*9880d681SAndroid Build Coastguard Worker   // Scan all operands.
239*9880d681SAndroid Build Coastguard Worker   for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
240*9880d681SAndroid Build Coastguard Worker     Value *Opnd = Inst->getOperand(Idx);
241*9880d681SAndroid Build Coastguard Worker 
242*9880d681SAndroid Build Coastguard Worker     // Visit constant integers.
243*9880d681SAndroid Build Coastguard Worker     if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
244*9880d681SAndroid Build Coastguard Worker       collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
245*9880d681SAndroid Build Coastguard Worker       continue;
246*9880d681SAndroid Build Coastguard Worker     }
247*9880d681SAndroid Build Coastguard Worker 
248*9880d681SAndroid Build Coastguard Worker     // Visit cast instructions that have constant integers.
249*9880d681SAndroid Build Coastguard Worker     if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
250*9880d681SAndroid Build Coastguard Worker       // Only visit cast instructions, which have been skipped. All other
251*9880d681SAndroid Build Coastguard Worker       // instructions should have already been visited.
252*9880d681SAndroid Build Coastguard Worker       if (!CastInst->isCast())
253*9880d681SAndroid Build Coastguard Worker         continue;
254*9880d681SAndroid Build Coastguard Worker 
255*9880d681SAndroid Build Coastguard Worker       if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
256*9880d681SAndroid Build Coastguard Worker         // Pretend the constant is directly used by the instruction and ignore
257*9880d681SAndroid Build Coastguard Worker         // the cast instruction.
258*9880d681SAndroid Build Coastguard Worker         collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
259*9880d681SAndroid Build Coastguard Worker         continue;
260*9880d681SAndroid Build Coastguard Worker       }
261*9880d681SAndroid Build Coastguard Worker     }
262*9880d681SAndroid Build Coastguard Worker 
263*9880d681SAndroid Build Coastguard Worker     // Visit constant expressions that have constant integers.
264*9880d681SAndroid Build Coastguard Worker     if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
265*9880d681SAndroid Build Coastguard Worker       // Only visit constant cast expressions.
266*9880d681SAndroid Build Coastguard Worker       if (!ConstExpr->isCast())
267*9880d681SAndroid Build Coastguard Worker         continue;
268*9880d681SAndroid Build Coastguard Worker 
269*9880d681SAndroid Build Coastguard Worker       if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
270*9880d681SAndroid Build Coastguard Worker         // Pretend the constant is directly used by the instruction and ignore
271*9880d681SAndroid Build Coastguard Worker         // the constant expression.
272*9880d681SAndroid Build Coastguard Worker         collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
273*9880d681SAndroid Build Coastguard Worker         continue;
274*9880d681SAndroid Build Coastguard Worker       }
275*9880d681SAndroid Build Coastguard Worker     }
276*9880d681SAndroid Build Coastguard Worker   } // end of for all operands
277*9880d681SAndroid Build Coastguard Worker }
278*9880d681SAndroid Build Coastguard Worker 
279*9880d681SAndroid Build Coastguard Worker /// \brief Collect all integer constants in the function that cannot be folded
280*9880d681SAndroid Build Coastguard Worker /// into an instruction itself.
collectConstantCandidates(Function & Fn)281*9880d681SAndroid Build Coastguard Worker void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
282*9880d681SAndroid Build Coastguard Worker   ConstCandMapType ConstCandMap;
283*9880d681SAndroid Build Coastguard Worker   for (BasicBlock &BB : Fn)
284*9880d681SAndroid Build Coastguard Worker     for (Instruction &Inst : BB)
285*9880d681SAndroid Build Coastguard Worker       collectConstantCandidates(ConstCandMap, &Inst);
286*9880d681SAndroid Build Coastguard Worker }
287*9880d681SAndroid Build Coastguard Worker 
288*9880d681SAndroid Build Coastguard Worker // This helper function is necessary to deal with values that have different
289*9880d681SAndroid Build Coastguard Worker // bit widths (APInt Operator- does not like that). If the value cannot be
290*9880d681SAndroid Build Coastguard Worker // represented in uint64 we return an "empty" APInt. This is then interpreted
291*9880d681SAndroid Build Coastguard Worker // as the value is not in range.
calculateOffsetDiff(APInt V1,APInt V2)292*9880d681SAndroid Build Coastguard Worker static llvm::Optional<APInt> calculateOffsetDiff(APInt V1, APInt V2)
293*9880d681SAndroid Build Coastguard Worker {
294*9880d681SAndroid Build Coastguard Worker   llvm::Optional<APInt> Res = None;
295*9880d681SAndroid Build Coastguard Worker   unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
296*9880d681SAndroid Build Coastguard Worker                 V1.getBitWidth() : V2.getBitWidth();
297*9880d681SAndroid Build Coastguard Worker   uint64_t LimVal1 = V1.getLimitedValue();
298*9880d681SAndroid Build Coastguard Worker   uint64_t LimVal2 = V2.getLimitedValue();
299*9880d681SAndroid Build Coastguard Worker 
300*9880d681SAndroid Build Coastguard Worker   if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
301*9880d681SAndroid Build Coastguard Worker     return Res;
302*9880d681SAndroid Build Coastguard Worker 
303*9880d681SAndroid Build Coastguard Worker   uint64_t Diff = LimVal1 - LimVal2;
304*9880d681SAndroid Build Coastguard Worker   return APInt(BW, Diff, true);
305*9880d681SAndroid Build Coastguard Worker }
306*9880d681SAndroid Build Coastguard Worker 
307*9880d681SAndroid Build Coastguard Worker // From a list of constants, one needs to picked as the base and the other
308*9880d681SAndroid Build Coastguard Worker // constants will be transformed into an offset from that base constant. The
309*9880d681SAndroid Build Coastguard Worker // question is which we can pick best? For example, consider these constants
310*9880d681SAndroid Build Coastguard Worker // and their number of uses:
311*9880d681SAndroid Build Coastguard Worker //
312*9880d681SAndroid Build Coastguard Worker //  Constants| 2 | 4 | 12 | 42 |
313*9880d681SAndroid Build Coastguard Worker //  NumUses  | 3 | 2 |  8 |  7 |
314*9880d681SAndroid Build Coastguard Worker //
315*9880d681SAndroid Build Coastguard Worker // Selecting constant 12 because it has the most uses will generate negative
316*9880d681SAndroid Build Coastguard Worker // offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
317*9880d681SAndroid Build Coastguard Worker // offsets lead to less optimal code generation, then there might be better
318*9880d681SAndroid Build Coastguard Worker // solutions. Suppose immediates in the range of 0..35 are most optimally
319*9880d681SAndroid Build Coastguard Worker // supported by the architecture, then selecting constant 2 is most optimal
320*9880d681SAndroid Build Coastguard Worker // because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
321*9880d681SAndroid Build Coastguard Worker // range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
322*9880d681SAndroid Build Coastguard Worker // have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
323*9880d681SAndroid Build Coastguard Worker // selecting the base constant the range of the offsets is a very important
324*9880d681SAndroid Build Coastguard Worker // factor too that we take into account here. This algorithm calculates a total
325*9880d681SAndroid Build Coastguard Worker // costs for selecting a constant as the base and substract the costs if
326*9880d681SAndroid Build Coastguard Worker // immediates are out of range. It has quadratic complexity, so we call this
327*9880d681SAndroid Build Coastguard Worker // function only when we're optimising for size and there are less than 100
328*9880d681SAndroid Build Coastguard Worker // constants, we fall back to the straightforward algorithm otherwise
329*9880d681SAndroid Build Coastguard Worker // which does not do all the offset calculations.
330*9880d681SAndroid Build Coastguard Worker unsigned
maximizeConstantsInRange(ConstCandVecType::iterator S,ConstCandVecType::iterator E,ConstCandVecType::iterator & MaxCostItr)331*9880d681SAndroid Build Coastguard Worker ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
332*9880d681SAndroid Build Coastguard Worker                                            ConstCandVecType::iterator E,
333*9880d681SAndroid Build Coastguard Worker                                            ConstCandVecType::iterator &MaxCostItr) {
334*9880d681SAndroid Build Coastguard Worker   unsigned NumUses = 0;
335*9880d681SAndroid Build Coastguard Worker 
336*9880d681SAndroid Build Coastguard Worker   if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
337*9880d681SAndroid Build Coastguard Worker     for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
338*9880d681SAndroid Build Coastguard Worker       NumUses += ConstCand->Uses.size();
339*9880d681SAndroid Build Coastguard Worker       if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
340*9880d681SAndroid Build Coastguard Worker         MaxCostItr = ConstCand;
341*9880d681SAndroid Build Coastguard Worker     }
342*9880d681SAndroid Build Coastguard Worker     return NumUses;
343*9880d681SAndroid Build Coastguard Worker   }
344*9880d681SAndroid Build Coastguard Worker 
345*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "== Maximize constants in range ==\n");
346*9880d681SAndroid Build Coastguard Worker   int MaxCost = -1;
347*9880d681SAndroid Build Coastguard Worker   for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
348*9880d681SAndroid Build Coastguard Worker     auto Value = ConstCand->ConstInt->getValue();
349*9880d681SAndroid Build Coastguard Worker     Type *Ty = ConstCand->ConstInt->getType();
350*9880d681SAndroid Build Coastguard Worker     int Cost = 0;
351*9880d681SAndroid Build Coastguard Worker     NumUses += ConstCand->Uses.size();
352*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue() << "\n");
353*9880d681SAndroid Build Coastguard Worker 
354*9880d681SAndroid Build Coastguard Worker     for (auto User : ConstCand->Uses) {
355*9880d681SAndroid Build Coastguard Worker       unsigned Opcode = User.Inst->getOpcode();
356*9880d681SAndroid Build Coastguard Worker       unsigned OpndIdx = User.OpndIdx;
357*9880d681SAndroid Build Coastguard Worker       Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
358*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "Cost: " << Cost << "\n");
359*9880d681SAndroid Build Coastguard Worker 
360*9880d681SAndroid Build Coastguard Worker       for (auto C2 = S; C2 != E; ++C2) {
361*9880d681SAndroid Build Coastguard Worker         llvm::Optional<APInt> Diff = calculateOffsetDiff(
362*9880d681SAndroid Build Coastguard Worker                                       C2->ConstInt->getValue(),
363*9880d681SAndroid Build Coastguard Worker                                       ConstCand->ConstInt->getValue());
364*9880d681SAndroid Build Coastguard Worker         if (Diff) {
365*9880d681SAndroid Build Coastguard Worker           const int ImmCosts =
366*9880d681SAndroid Build Coastguard Worker             TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
367*9880d681SAndroid Build Coastguard Worker           Cost -= ImmCosts;
368*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
369*9880d681SAndroid Build Coastguard Worker                        << "has penalty: " << ImmCosts << "\n"
370*9880d681SAndroid Build Coastguard Worker                        << "Adjusted cost: " << Cost << "\n");
371*9880d681SAndroid Build Coastguard Worker         }
372*9880d681SAndroid Build Coastguard Worker       }
373*9880d681SAndroid Build Coastguard Worker     }
374*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
375*9880d681SAndroid Build Coastguard Worker     if (Cost > MaxCost) {
376*9880d681SAndroid Build Coastguard Worker       MaxCost = Cost;
377*9880d681SAndroid Build Coastguard Worker       MaxCostItr = ConstCand;
378*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
379*9880d681SAndroid Build Coastguard Worker                    << "\n");
380*9880d681SAndroid Build Coastguard Worker     }
381*9880d681SAndroid Build Coastguard Worker   }
382*9880d681SAndroid Build Coastguard Worker   return NumUses;
383*9880d681SAndroid Build Coastguard Worker }
384*9880d681SAndroid Build Coastguard Worker 
385*9880d681SAndroid Build Coastguard Worker /// \brief Find the base constant within the given range and rebase all other
386*9880d681SAndroid Build Coastguard Worker /// constants with respect to the base constant.
findAndMakeBaseConstant(ConstCandVecType::iterator S,ConstCandVecType::iterator E)387*9880d681SAndroid Build Coastguard Worker void ConstantHoistingPass::findAndMakeBaseConstant(
388*9880d681SAndroid Build Coastguard Worker     ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
389*9880d681SAndroid Build Coastguard Worker   auto MaxCostItr = S;
390*9880d681SAndroid Build Coastguard Worker   unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
391*9880d681SAndroid Build Coastguard Worker 
392*9880d681SAndroid Build Coastguard Worker   // Don't hoist constants that have only one use.
393*9880d681SAndroid Build Coastguard Worker   if (NumUses <= 1)
394*9880d681SAndroid Build Coastguard Worker     return;
395*9880d681SAndroid Build Coastguard Worker 
396*9880d681SAndroid Build Coastguard Worker   ConstantInfo ConstInfo;
397*9880d681SAndroid Build Coastguard Worker   ConstInfo.BaseConstant = MaxCostItr->ConstInt;
398*9880d681SAndroid Build Coastguard Worker   Type *Ty = ConstInfo.BaseConstant->getType();
399*9880d681SAndroid Build Coastguard Worker 
400*9880d681SAndroid Build Coastguard Worker   // Rebase the constants with respect to the base constant.
401*9880d681SAndroid Build Coastguard Worker   for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
402*9880d681SAndroid Build Coastguard Worker     APInt Diff = ConstCand->ConstInt->getValue() -
403*9880d681SAndroid Build Coastguard Worker                  ConstInfo.BaseConstant->getValue();
404*9880d681SAndroid Build Coastguard Worker     Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
405*9880d681SAndroid Build Coastguard Worker     ConstInfo.RebasedConstants.push_back(
406*9880d681SAndroid Build Coastguard Worker       RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
407*9880d681SAndroid Build Coastguard Worker   }
408*9880d681SAndroid Build Coastguard Worker   ConstantVec.push_back(std::move(ConstInfo));
409*9880d681SAndroid Build Coastguard Worker }
410*9880d681SAndroid Build Coastguard Worker 
411*9880d681SAndroid Build Coastguard Worker /// \brief Finds and combines constant candidates that can be easily
412*9880d681SAndroid Build Coastguard Worker /// rematerialized with an add from a common base constant.
findBaseConstants()413*9880d681SAndroid Build Coastguard Worker void ConstantHoistingPass::findBaseConstants() {
414*9880d681SAndroid Build Coastguard Worker   // Sort the constants by value and type. This invalidates the mapping!
415*9880d681SAndroid Build Coastguard Worker   std::sort(ConstCandVec.begin(), ConstCandVec.end(),
416*9880d681SAndroid Build Coastguard Worker             [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
417*9880d681SAndroid Build Coastguard Worker     if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
418*9880d681SAndroid Build Coastguard Worker       return LHS.ConstInt->getType()->getBitWidth() <
419*9880d681SAndroid Build Coastguard Worker              RHS.ConstInt->getType()->getBitWidth();
420*9880d681SAndroid Build Coastguard Worker     return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
421*9880d681SAndroid Build Coastguard Worker   });
422*9880d681SAndroid Build Coastguard Worker 
423*9880d681SAndroid Build Coastguard Worker   // Simple linear scan through the sorted constant candidate vector for viable
424*9880d681SAndroid Build Coastguard Worker   // merge candidates.
425*9880d681SAndroid Build Coastguard Worker   auto MinValItr = ConstCandVec.begin();
426*9880d681SAndroid Build Coastguard Worker   for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
427*9880d681SAndroid Build Coastguard Worker        CC != E; ++CC) {
428*9880d681SAndroid Build Coastguard Worker     if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
429*9880d681SAndroid Build Coastguard Worker       // Check if the constant is in range of an add with immediate.
430*9880d681SAndroid Build Coastguard Worker       APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
431*9880d681SAndroid Build Coastguard Worker       if ((Diff.getBitWidth() <= 64) &&
432*9880d681SAndroid Build Coastguard Worker           TTI->isLegalAddImmediate(Diff.getSExtValue()))
433*9880d681SAndroid Build Coastguard Worker         continue;
434*9880d681SAndroid Build Coastguard Worker     }
435*9880d681SAndroid Build Coastguard Worker     // We either have now a different constant type or the constant is not in
436*9880d681SAndroid Build Coastguard Worker     // range of an add with immediate anymore.
437*9880d681SAndroid Build Coastguard Worker     findAndMakeBaseConstant(MinValItr, CC);
438*9880d681SAndroid Build Coastguard Worker     // Start a new base constant search.
439*9880d681SAndroid Build Coastguard Worker     MinValItr = CC;
440*9880d681SAndroid Build Coastguard Worker   }
441*9880d681SAndroid Build Coastguard Worker   // Finalize the last base constant search.
442*9880d681SAndroid Build Coastguard Worker   findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
443*9880d681SAndroid Build Coastguard Worker }
444*9880d681SAndroid Build Coastguard Worker 
445*9880d681SAndroid Build Coastguard Worker /// \brief Updates the operand at Idx in instruction Inst with the result of
446*9880d681SAndroid Build Coastguard Worker ///        instruction Mat. If the instruction is a PHI node then special
447*9880d681SAndroid Build Coastguard Worker ///        handling for duplicate values form the same incomming basic block is
448*9880d681SAndroid Build Coastguard Worker ///        required.
449*9880d681SAndroid Build Coastguard Worker /// \return The update will always succeed, but the return value indicated if
450*9880d681SAndroid Build Coastguard Worker ///         Mat was used for the update or not.
updateOperand(Instruction * Inst,unsigned Idx,Instruction * Mat)451*9880d681SAndroid Build Coastguard Worker static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
452*9880d681SAndroid Build Coastguard Worker   if (auto PHI = dyn_cast<PHINode>(Inst)) {
453*9880d681SAndroid Build Coastguard Worker     // Check if any previous operand of the PHI node has the same incoming basic
454*9880d681SAndroid Build Coastguard Worker     // block. This is a very odd case that happens when the incoming basic block
455*9880d681SAndroid Build Coastguard Worker     // has a switch statement. In this case use the same value as the previous
456*9880d681SAndroid Build Coastguard Worker     // operand(s), otherwise we will fail verification due to different values.
457*9880d681SAndroid Build Coastguard Worker     // The values are actually the same, but the variable names are different
458*9880d681SAndroid Build Coastguard Worker     // and the verifier doesn't like that.
459*9880d681SAndroid Build Coastguard Worker     BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
460*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0; i < Idx; ++i) {
461*9880d681SAndroid Build Coastguard Worker       if (PHI->getIncomingBlock(i) == IncomingBB) {
462*9880d681SAndroid Build Coastguard Worker         Value *IncomingVal = PHI->getIncomingValue(i);
463*9880d681SAndroid Build Coastguard Worker         Inst->setOperand(Idx, IncomingVal);
464*9880d681SAndroid Build Coastguard Worker         return false;
465*9880d681SAndroid Build Coastguard Worker       }
466*9880d681SAndroid Build Coastguard Worker     }
467*9880d681SAndroid Build Coastguard Worker   }
468*9880d681SAndroid Build Coastguard Worker 
469*9880d681SAndroid Build Coastguard Worker   Inst->setOperand(Idx, Mat);
470*9880d681SAndroid Build Coastguard Worker   return true;
471*9880d681SAndroid Build Coastguard Worker }
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker /// \brief Emit materialization code for all rebased constants and update their
474*9880d681SAndroid Build Coastguard Worker /// users.
emitBaseConstants(Instruction * Base,Constant * Offset,const ConstantUser & ConstUser)475*9880d681SAndroid Build Coastguard Worker void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
476*9880d681SAndroid Build Coastguard Worker                                              Constant *Offset,
477*9880d681SAndroid Build Coastguard Worker                                              const ConstantUser &ConstUser) {
478*9880d681SAndroid Build Coastguard Worker   Instruction *Mat = Base;
479*9880d681SAndroid Build Coastguard Worker   if (Offset) {
480*9880d681SAndroid Build Coastguard Worker     Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
481*9880d681SAndroid Build Coastguard Worker                                                ConstUser.OpndIdx);
482*9880d681SAndroid Build Coastguard Worker     Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
483*9880d681SAndroid Build Coastguard Worker                                  "const_mat", InsertionPt);
484*9880d681SAndroid Build Coastguard Worker 
485*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
486*9880d681SAndroid Build Coastguard Worker                  << " + " << *Offset << ") in BB "
487*9880d681SAndroid Build Coastguard Worker                  << Mat->getParent()->getName() << '\n' << *Mat << '\n');
488*9880d681SAndroid Build Coastguard Worker     Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
489*9880d681SAndroid Build Coastguard Worker   }
490*9880d681SAndroid Build Coastguard Worker   Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
491*9880d681SAndroid Build Coastguard Worker 
492*9880d681SAndroid Build Coastguard Worker   // Visit constant integer.
493*9880d681SAndroid Build Coastguard Worker   if (isa<ConstantInt>(Opnd)) {
494*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
495*9880d681SAndroid Build Coastguard Worker     if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
496*9880d681SAndroid Build Coastguard Worker       Mat->eraseFromParent();
497*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
498*9880d681SAndroid Build Coastguard Worker     return;
499*9880d681SAndroid Build Coastguard Worker   }
500*9880d681SAndroid Build Coastguard Worker 
501*9880d681SAndroid Build Coastguard Worker   // Visit cast instruction.
502*9880d681SAndroid Build Coastguard Worker   if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
503*9880d681SAndroid Build Coastguard Worker     assert(CastInst->isCast() && "Expected an cast instruction!");
504*9880d681SAndroid Build Coastguard Worker     // Check if we already have visited this cast instruction before to avoid
505*9880d681SAndroid Build Coastguard Worker     // unnecessary cloning.
506*9880d681SAndroid Build Coastguard Worker     Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
507*9880d681SAndroid Build Coastguard Worker     if (!ClonedCastInst) {
508*9880d681SAndroid Build Coastguard Worker       ClonedCastInst = CastInst->clone();
509*9880d681SAndroid Build Coastguard Worker       ClonedCastInst->setOperand(0, Mat);
510*9880d681SAndroid Build Coastguard Worker       ClonedCastInst->insertAfter(CastInst);
511*9880d681SAndroid Build Coastguard Worker       // Use the same debug location as the original cast instruction.
512*9880d681SAndroid Build Coastguard Worker       ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
513*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
514*9880d681SAndroid Build Coastguard Worker                    << "To               : " << *ClonedCastInst << '\n');
515*9880d681SAndroid Build Coastguard Worker     }
516*9880d681SAndroid Build Coastguard Worker 
517*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
518*9880d681SAndroid Build Coastguard Worker     updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
519*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
520*9880d681SAndroid Build Coastguard Worker     return;
521*9880d681SAndroid Build Coastguard Worker   }
522*9880d681SAndroid Build Coastguard Worker 
523*9880d681SAndroid Build Coastguard Worker   // Visit constant expression.
524*9880d681SAndroid Build Coastguard Worker   if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
525*9880d681SAndroid Build Coastguard Worker     Instruction *ConstExprInst = ConstExpr->getAsInstruction();
526*9880d681SAndroid Build Coastguard Worker     ConstExprInst->setOperand(0, Mat);
527*9880d681SAndroid Build Coastguard Worker     ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
528*9880d681SAndroid Build Coastguard Worker                                                 ConstUser.OpndIdx));
529*9880d681SAndroid Build Coastguard Worker 
530*9880d681SAndroid Build Coastguard Worker     // Use the same debug location as the instruction we are about to update.
531*9880d681SAndroid Build Coastguard Worker     ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
532*9880d681SAndroid Build Coastguard Worker 
533*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
534*9880d681SAndroid Build Coastguard Worker                  << "From              : " << *ConstExpr << '\n');
535*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
536*9880d681SAndroid Build Coastguard Worker     if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
537*9880d681SAndroid Build Coastguard Worker       ConstExprInst->eraseFromParent();
538*9880d681SAndroid Build Coastguard Worker       if (Offset)
539*9880d681SAndroid Build Coastguard Worker         Mat->eraseFromParent();
540*9880d681SAndroid Build Coastguard Worker     }
541*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "To    : " << *ConstUser.Inst << '\n');
542*9880d681SAndroid Build Coastguard Worker     return;
543*9880d681SAndroid Build Coastguard Worker   }
544*9880d681SAndroid Build Coastguard Worker }
545*9880d681SAndroid Build Coastguard Worker 
546*9880d681SAndroid Build Coastguard Worker /// \brief Hoist and hide the base constant behind a bitcast and emit
547*9880d681SAndroid Build Coastguard Worker /// materialization code for derived constants.
emitBaseConstants()548*9880d681SAndroid Build Coastguard Worker bool ConstantHoistingPass::emitBaseConstants() {
549*9880d681SAndroid Build Coastguard Worker   bool MadeChange = false;
550*9880d681SAndroid Build Coastguard Worker   for (auto const &ConstInfo : ConstantVec) {
551*9880d681SAndroid Build Coastguard Worker     // Hoist and hide the base constant behind a bitcast.
552*9880d681SAndroid Build Coastguard Worker     Instruction *IP = findConstantInsertionPoint(ConstInfo);
553*9880d681SAndroid Build Coastguard Worker     IntegerType *Ty = ConstInfo.BaseConstant->getType();
554*9880d681SAndroid Build Coastguard Worker     Instruction *Base =
555*9880d681SAndroid Build Coastguard Worker       new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
556*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
557*9880d681SAndroid Build Coastguard Worker                  << IP->getParent()->getName() << '\n' << *Base << '\n');
558*9880d681SAndroid Build Coastguard Worker     NumConstantsHoisted++;
559*9880d681SAndroid Build Coastguard Worker 
560*9880d681SAndroid Build Coastguard Worker     // Emit materialization code for all rebased constants.
561*9880d681SAndroid Build Coastguard Worker     for (auto const &RCI : ConstInfo.RebasedConstants) {
562*9880d681SAndroid Build Coastguard Worker       NumConstantsRebased++;
563*9880d681SAndroid Build Coastguard Worker       for (auto const &U : RCI.Uses)
564*9880d681SAndroid Build Coastguard Worker         emitBaseConstants(Base, RCI.Offset, U);
565*9880d681SAndroid Build Coastguard Worker     }
566*9880d681SAndroid Build Coastguard Worker 
567*9880d681SAndroid Build Coastguard Worker     // Use the same debug location as the last user of the constant.
568*9880d681SAndroid Build Coastguard Worker     assert(!Base->use_empty() && "The use list is empty!?");
569*9880d681SAndroid Build Coastguard Worker     assert(isa<Instruction>(Base->user_back()) &&
570*9880d681SAndroid Build Coastguard Worker            "All uses should be instructions.");
571*9880d681SAndroid Build Coastguard Worker     Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
572*9880d681SAndroid Build Coastguard Worker 
573*9880d681SAndroid Build Coastguard Worker     // Correct for base constant, which we counted above too.
574*9880d681SAndroid Build Coastguard Worker     NumConstantsRebased--;
575*9880d681SAndroid Build Coastguard Worker     MadeChange = true;
576*9880d681SAndroid Build Coastguard Worker   }
577*9880d681SAndroid Build Coastguard Worker   return MadeChange;
578*9880d681SAndroid Build Coastguard Worker }
579*9880d681SAndroid Build Coastguard Worker 
580*9880d681SAndroid Build Coastguard Worker /// \brief Check all cast instructions we made a copy of and remove them if they
581*9880d681SAndroid Build Coastguard Worker /// have no more users.
deleteDeadCastInst() const582*9880d681SAndroid Build Coastguard Worker void ConstantHoistingPass::deleteDeadCastInst() const {
583*9880d681SAndroid Build Coastguard Worker   for (auto const &I : ClonedCastMap)
584*9880d681SAndroid Build Coastguard Worker     if (I.first->use_empty())
585*9880d681SAndroid Build Coastguard Worker       I.first->eraseFromParent();
586*9880d681SAndroid Build Coastguard Worker }
587*9880d681SAndroid Build Coastguard Worker 
588*9880d681SAndroid Build Coastguard Worker /// \brief Optimize expensive integer constants in the given function.
runImpl(Function & Fn,TargetTransformInfo & TTI,DominatorTree & DT,BasicBlock & Entry)589*9880d681SAndroid Build Coastguard Worker bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
590*9880d681SAndroid Build Coastguard Worker                                    DominatorTree &DT, BasicBlock &Entry) {
591*9880d681SAndroid Build Coastguard Worker   this->TTI = &TTI;
592*9880d681SAndroid Build Coastguard Worker   this->DT = &DT;
593*9880d681SAndroid Build Coastguard Worker   this->Entry = &Entry;
594*9880d681SAndroid Build Coastguard Worker   // Collect all constant candidates.
595*9880d681SAndroid Build Coastguard Worker   collectConstantCandidates(Fn);
596*9880d681SAndroid Build Coastguard Worker 
597*9880d681SAndroid Build Coastguard Worker   // There are no constant candidates to worry about.
598*9880d681SAndroid Build Coastguard Worker   if (ConstCandVec.empty())
599*9880d681SAndroid Build Coastguard Worker     return false;
600*9880d681SAndroid Build Coastguard Worker 
601*9880d681SAndroid Build Coastguard Worker   // Combine constants that can be easily materialized with an add from a common
602*9880d681SAndroid Build Coastguard Worker   // base constant.
603*9880d681SAndroid Build Coastguard Worker   findBaseConstants();
604*9880d681SAndroid Build Coastguard Worker 
605*9880d681SAndroid Build Coastguard Worker   // There are no constants to emit.
606*9880d681SAndroid Build Coastguard Worker   if (ConstantVec.empty())
607*9880d681SAndroid Build Coastguard Worker     return false;
608*9880d681SAndroid Build Coastguard Worker 
609*9880d681SAndroid Build Coastguard Worker   // Finally hoist the base constant and emit materialization code for dependent
610*9880d681SAndroid Build Coastguard Worker   // constants.
611*9880d681SAndroid Build Coastguard Worker   bool MadeChange = emitBaseConstants();
612*9880d681SAndroid Build Coastguard Worker 
613*9880d681SAndroid Build Coastguard Worker   // Cleanup dead instructions.
614*9880d681SAndroid Build Coastguard Worker   deleteDeadCastInst();
615*9880d681SAndroid Build Coastguard Worker 
616*9880d681SAndroid Build Coastguard Worker   return MadeChange;
617*9880d681SAndroid Build Coastguard Worker }
618*9880d681SAndroid Build Coastguard Worker 
run(Function & F,FunctionAnalysisManager & AM)619*9880d681SAndroid Build Coastguard Worker PreservedAnalyses ConstantHoistingPass::run(Function &F,
620*9880d681SAndroid Build Coastguard Worker                                             FunctionAnalysisManager &AM) {
621*9880d681SAndroid Build Coastguard Worker   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
622*9880d681SAndroid Build Coastguard Worker   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
623*9880d681SAndroid Build Coastguard Worker   if (!runImpl(F, TTI, DT, F.getEntryBlock()))
624*9880d681SAndroid Build Coastguard Worker     return PreservedAnalyses::all();
625*9880d681SAndroid Build Coastguard Worker 
626*9880d681SAndroid Build Coastguard Worker   // FIXME: This should also 'preserve the CFG'.
627*9880d681SAndroid Build Coastguard Worker   return PreservedAnalyses::none();
628*9880d681SAndroid Build Coastguard Worker }
629